tf_bindgen/value/
prepare.rs

1use std::{
2    collections::{HashMap, HashSet},
3    ops::Deref,
4    rc::Rc,
5};
6
7pub trait Prepare {
8    fn prepare(self, prefix: impl Into<String>) -> Self;
9}
10
11macro_rules! noop {
12    ($t:ty) => {
13        impl Prepare for $t {
14            fn prepare(self, _: impl Into<String>) -> Self {
15                self
16            }
17        }
18    };
19}
20
21noop!(String);
22noop!(bool);
23noop!(i64);
24noop!(serde_json::Value);
25
26impl<T: Prepare> Prepare for Option<T> {
27    fn prepare(self, prefix: impl Into<String>) -> Self {
28        self.map(|v| v.prepare(prefix))
29    }
30}
31
32impl<T: Prepare> Prepare for Vec<T> {
33    fn prepare(self, prefix: impl Into<String>) -> Self {
34        let prefix = prefix.into();
35        self.into_iter()
36            .enumerate()
37            .map(|(i, el)| {
38                let path = format!("{prefix}.{i}");
39                el.prepare(path)
40            })
41            .collect()
42    }
43}
44
45impl<T> Prepare for HashSet<T> {
46    fn prepare(self, _: impl Into<String>) -> Self {
47        self
48    }
49}
50
51impl<T> Prepare for HashMap<String, T> {
52    fn prepare(self, _: impl Into<String>) -> Self {
53        self
54    }
55}
56
57impl<T: Prepare + Clone> Prepare for Rc<T> {
58    fn prepare(self, prefix: impl Into<String>) -> Self {
59        let value = self.deref();
60        Rc::new(value.clone().prepare(prefix))
61    }
62}