#struct #proc-macro #subset #automatic #create #another #derive

macro no-std substruct

A proc-macro to create subsets of structs

2 releases

0.1.1 May 20, 2024
0.1.0 May 17, 2024

#478 in Procedural macros

Download history 188/week @ 2024-06-18 181/week @ 2024-06-25 226/week @ 2024-07-02 99/week @ 2024-07-09 206/week @ 2024-07-16 83/week @ 2024-07-23 223/week @ 2024-07-30 135/week @ 2024-08-06 351/week @ 2024-08-13 81/week @ 2024-08-20 145/week @ 2024-08-27 139/week @ 2024-09-03 266/week @ 2024-09-10 142/week @ 2024-09-17 220/week @ 2024-09-24 219/week @ 2024-10-01

965 downloads per month

MIT/Apache

29KB
490 lines

substruct

crates.io license docs.rs ci

Substruct is a proc-macro wich allows you to easily declare strucs which are subsets of another struct.

Simple Example

A basic use of substruct looks like this

use substruct::substruct;

#[substruct(LimitedQueryParams)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QueryParams {
    #[substruct(LimitedQueryParams)]
    pub name: Option<String>,

    #[substruct(LimitedQueryParams)]
    pub parent: Option<String>,

    pub limit: usize
}

which expands out to produce

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QueryParams {
    pub name: Option<String>,
    pub parent: Option<String>,
    pub limit: usize
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LimitedQueryParams {
    pub name: Option<String>,
    pub parent: Option<String>,
}

Complex Example

Substruct also supports copying attributes or adding attributes specific to a subset of the child structs.

use std::time::SystemTime;
use substruct::substruct;

#[substruct(PostQueryParams, ThreadQueryParams)]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct QueryParams {
    /// Query only within forums with this id
    pub forum: Option<u64>,

    /// Query only with threads with this id.
    #[substruct(PostQueryParams)]
    pub thread: Option<u64>,

    /// The username to search.
    #[substruct(PostQueryParams, ThreadQueryParams)]
    // Alias only applied for ThreadQueryParams
    #[substruct_attr(ThreadQueryParams, serde(alias = "username"))]
    pub user: Option<String>,

    #[substruct(PostQueryParams, ThreadQueryParams)]
    // Field is renamed (in serde) for PostQueryParams and ThreadQueryParams
    // but not for QueryParams.
    #[substruct_attr(not(QueryParams), serde(rename = "before_ts"))]
    pub before: Option<SystemTime>,

    #[substruct(PostQueryParams, ThreadQueryParams)]
    #[substruct_attr(not(QueryParams), serde(rename = "before_ts"))]
    pub after: Option<SystemTime>,

    // Limit is only present on QueryParams.
    pub limit: Option<usize>,
}

Limitations

Substruct supports generics but will fail if the generic parameters are not used by all of the child structs.

See Also

Dependencies

~1–1.7MB
~32K SLoC