4 releases

0.0.4 Mar 2, 2024
0.0.3 Jul 8, 2023
0.0.2 Jan 30, 2021
0.0.1 Jan 9, 2021

#1016 in Parser implementations

Download history 62/week @ 2024-08-26 64/week @ 2024-09-02 50/week @ 2024-09-09 15/week @ 2024-09-16 40/week @ 2024-09-23 23/week @ 2024-09-30 67/week @ 2024-10-07 90/week @ 2024-10-14 191/week @ 2024-10-21 200/week @ 2024-10-28 187/week @ 2024-11-04 163/week @ 2024-11-11 48/week @ 2024-11-18 95/week @ 2024-11-25 57/week @ 2024-12-02 80/week @ 2024-12-09

284 downloads per month

MIT/Apache

15KB
401 lines

fieldmask

This is a Rust library that supports (de)serializing/applying fieldmask.

Example

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);
}

Dependencies

~2MB
~42K SLoC