1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use std::collections::HashMap;

use thiserror::Error;

#[derive(Debug, Error)]
#[error(r#"there's no "{field}" in `{type_str}`"#)]
pub struct DeserializeMaskError {
    pub type_str: &'static str,
    pub field: String,
    pub depth: u8,
}

pub trait Maskable: Sized {
    type Mask;

    /// Perform a 'bitor' operation between the `mask` and a fieldmask in string format.
    /// When the function returns Ok, `mask` should be modified to include fields in
    /// `field_mask_segs`.
    fn try_bitor_assign_mask(
        // Take a reference here instead of the ownership. Because:
        // 1. We may want to try performing other operations on `mask` if the current one doesn't
        // work.
        // 2. Therefore, if we take the ownership, we will need to return the ownership even when
        // the method failed, which is cumbersome.
        mask: &mut Self::Mask,
        // Take a slice of segments instead of a full fieldmask string. Because:
        // 1. It's easier to perform pattern matching on slices.
        // 2. It's easier to distinguish empty fieldmask (e.g. "") and empty tail (e.g. "parent.").
        field_mask_segs: &[&str],
    ) -> Result<(), DeserializeMaskError>;
}

pub trait SelfMaskable: Maskable {
    /// Implementation of the application process of a mask.
    fn apply_mask(&mut self, src: Self, mask: &Self::Mask);
}

pub trait OptionMaskable: Maskable {
    /// Implementation of the application process of a mask.
    fn apply_mask(&mut self, src: Self, mask: &Self::Mask) -> bool;
}

impl<T: SelfMaskable> OptionMaskable for T
where
    T: Default,
    T::Mask: PartialEq,
{
    fn apply_mask(&mut self, src: Self, mask: &Self::Mask) -> bool {
        self.apply_mask(src, mask);
        true
    }
}

impl<T: Maskable> Maskable for Option<T>
where
    T: Default,
    T::Mask: PartialEq,
{
    type Mask = T::Mask;

    fn try_bitor_assign_mask(
        mask: &mut Self::Mask,
        field_mask_segs: &[&str],
    ) -> Result<(), DeserializeMaskError> {
        T::try_bitor_assign_mask(mask, field_mask_segs)
    }
}

impl<T: OptionMaskable> SelfMaskable for Option<T>
where
    T: Default,
    T::Mask: PartialEq + Default,
{
    fn apply_mask(&mut self, src: Self, mask: &Self::Mask) {
        if mask == &Self::Mask::default() {
            return;
        }
        match self {
            Some(s) => match src {
                Some(o) => {
                    if !s.apply_mask(o, mask) {
                        *self = None;
                    }
                }
                None => *self = None,
            },
            None => {
                if let Some(o) = src {
                    let mut new = T::default();
                    if new.apply_mask(o, mask) {
                        *self = Some(new);
                    } else {
                        *self = None;
                    }
                }
            }
        }
    }
}

macro_rules! maskable {
    ($T:path) => {
        impl Maskable for $T {
            type Mask = bool;

            fn try_bitor_assign_mask(
                mask: &mut Self::Mask,
                field_mask_segs: &[&str],
            ) -> Result<(), DeserializeMaskError> {
                if field_mask_segs.len() == 0 {
                    *mask = true;
                    Ok(())
                } else {
                    Err(DeserializeMaskError {
                        type_str: stringify!($T),
                        field: field_mask_segs[0].into(),
                        depth: 0,
                    })
                }
            }
        }

        impl SelfMaskable for $T {
            fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
                if *mask {
                    *self = other;
                }
            }
        }
    };
}

maskable!(bool);
maskable!(char);

maskable!(f32);
maskable!(f64);

maskable!(i8);
maskable!(u8);
maskable!(i16);
maskable!(u16);
maskable!(i32);
maskable!(u32);
maskable!(i64);
maskable!(u64);
maskable!(i128);
maskable!(u128);
maskable!(isize);
maskable!(usize);

maskable!(String);

#[cfg(feature = "prost")]
maskable!(prost::bytes::Bytes);

impl<T> Maskable for Vec<T> {
    type Mask = bool;

    fn try_bitor_assign_mask(
        mask: &mut Self::Mask,
        field_mask_segs: &[&str],
    ) -> Result<(), DeserializeMaskError> {
        if field_mask_segs.is_empty() {
            *mask = true;
            Ok(())
        } else {
            Err(DeserializeMaskError {
                type_str: "Vec",
                field: field_mask_segs[0].into(),
                depth: 0,
            })
        }
    }
}

impl<T> SelfMaskable for Vec<T> {
    fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
        if *mask {
            *self = other;
        }
    }
}

impl<K, V> Maskable for HashMap<K, V> {
    type Mask = bool;

    fn try_bitor_assign_mask(
        mask: &mut Self::Mask,
        field_mask_segs: &[&str],
    ) -> Result<(), DeserializeMaskError> {
        if field_mask_segs.is_empty() {
            *mask = true;
            Ok(())
        } else {
            Err(DeserializeMaskError {
                type_str: "HashMap",
                field: field_mask_segs[0].into(),
                depth: 0,
            })
        }
    }
}

impl<K, V> SelfMaskable for HashMap<K, V> {
    fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
        if *mask {
            *self = other;
        }
    }
}