#reflection #macro-derive #derive #run-time #struct #field-value #schema

macro avocado-schema-derive

A derive macro to support runtime reflection of struct values

4 releases (2 breaking)

0.8.0 Nov 3, 2023
0.7.0 Nov 3, 2023
0.6.3 Nov 2, 2023
0.6.2 Nov 2, 2023

#1670 in Procedural macros

33 downloads per month

MIT license

98KB
2.5K SLoC

Avocado Schema Derive

Avocado Schema defines the following enum FieldValue for runtime reflection of struct's structure and values:

Crates.io MIT licensed

#[derive(Debug, Clone, PartialEq)]
pub enum FieldValue {
    String(String),
    Integer(i64),
    UInteger(u64),
    Float(f64),
    Boolean(bool),
    Object(BTreeMap<String, FieldValue>),
    Array(Vec<FieldValue>),
    Email(EmailAddress),
    DateTime(DateTime<Utc>),
    Date(NaiveDate),
    Time(NaiveTime),
    Null,
}

This macro Reflect is for deriving FieldValue enum for struct:

#[derive(Reflect)]
struct Client {
    #[reflect("firstName")]
    first_name: String,
    #[reflect("lastName")]
    last_name: String,
    age: u64,
    #[reflect(ignore)]
    email: String
}

#[test]
fn main() {
    let client = Client {
        first_name: "Robert".to_string(),
        last_name: "Li".to_string(),
        age: 30,
        email: "admin@avocado.com".to_string(),
    };
    assert_eq!(
        client.field_value(),
        FieldValue::Object(BTreeMap::from([
            (
                "firstName".to_string(),
                FieldValue::String("Robert".to_string())
            ),
            ("lastName".to_string(), FieldValue::String("Li".to_string())),
            ("age".to_string(), FieldValue::UInteger(30))
        ]))
    )
}

Dependencies

~7–10MB
~172K SLoC