looking_glass/field_mask.rs
1use std::collections::HashMap;
2
3use smol_str::SmolStr;
4
5/// As tree structure that repersents a set of nested fields.
6///
7/// This is based on the `FieldMaskTree` that is found in the C++ & Java protobuf libraries. It can be used for conditionally clearing or updating [`crate::Instance`]. A tree is used to simplify & speed up filtering fields
8/// A field mask contains a series of paths to attributes such as `["foo.a", "foo.b", "bar"]`. Internally that would be repersented as a tree like below:
9/// ```text
10/// foo bar
11/// / \
12/// a b
13/// ```
14#[derive(Default)]
15pub struct FieldMask {
16 children: HashMap<SmolStr, FieldMask>,
17}
18
19impl FieldMask {
20 pub fn new<'a, I: IntoIterator<Item = &'a str>>(iter: I) -> FieldMask {
21 let mut mask = FieldMask::default();
22 for path in iter {
23 let path = path.split('.');
24 let mut new_mask = &mut mask;
25 for p in path {
26 new_mask = new_mask.children.entry(SmolStr::new(p)).or_default();
27 }
28 }
29 mask
30 }
31
32 /// Returns a field mask for a specific field.
33 pub fn child(&self, path: &SmolStr) -> Option<&FieldMask> {
34 self.children.get(path)
35 }
36}