4 个版本

0.0.4 2024 年 3 月 2 日
0.0.3 2023 年 7 月 8 日
0.0.2 2021 年 1 月 30 日
0.0.1 2021 年 1 月 9 日

解析器实现 中排名 596

Download history 13/week @ 2024-03-10 31/week @ 2024-03-31

每月下载量 99

MIT/Apache

15KB
401

fieldmask

一个支持(反)序列化/应用字段掩码的 Rust 库。

示例

use std::convert::TryFrom;

use fieldmask::{FieldMask, FieldMaskInput, Maskable};

#[derive(Debug, PartialEq, Maskable)]
struct Parent {
    primitive: String,
    child_1: Child,
    child_2: Child,
    #[fieldmask(flatten)]
    one_of_field: Option<OneOfField>,
}

#[derive(Debug, PartialEq, Maskable)]
struct Child {
    field_one: String,
    field_two: u32,
}

#[derive(Debug, PartialEq, Maskable)]
enum OneOfField {
    VariantOne(String),
    VariantTwo(u32),
}

impl Default for OneOfField {
    fn default() -> Self {
        Self::VariantOne(String::default())
    }
}

#[test]
fn case_1() {
    let mut target_struct = Parent {
        primitive: "string".into(),
        child_1: Child {
            field_one: "child_1 field one".into(),
            field_two: 1,
        },
        child_2: Child {
            field_one: "child_2 field one".into(),
            field_two: 2,
        },
        one_of_field: Some(OneOfField::VariantOne("variant one".into())),
    };
    let src_struct = Parent {
        primitive: "updated string".into(),
        child_1: Child {
            field_one: "updated child_1 field one".into(),
            field_two: 10,
        },
        child_2: Child {
            field_one: "updated child_2 field one".into(),
            field_two: 20,
        },
        one_of_field: Some(OneOfField::VariantTwo(50)),
    };

    let expected_struct = Parent {
        primitive: "updated string".into(),
        child_1: Child {
            field_one: "child_1 field one".into(),
            field_two: 10,
        },
        child_2: Child {
            field_one: "updated child_2 field one".into(),
            field_two: 20,
        },
        one_of_field: Some(OneOfField::VariantTwo(50)),
    };

    FieldMask::try_from(FieldMaskInput(
        vec![
            "primitive",
            "child_1.field_two",
            "child_2", // if child properties are not specified, all properties are included.
            "variant_two", // if a field is marked with `flatten`, its properties are merged with its parents properties.
        ]
        .into_iter(),
    ))
    .expect("unable to deserialize mask")
    .apply(&mut target_struct, src_struct);

    assert_eq!(target_struct, expected_struct);
}

依赖项

~0.5–1MB
~22K SLoC