datagen_rs/generate/
schema_path.rs

1#[cfg(feature = "serialize")]
2use serde::{Serialize, Serializer};
3use std::collections::VecDeque;
4use std::fmt::Display;
5
6#[derive(Clone, Debug)]
7pub struct SchemaPath(VecDeque<String>);
8
9impl SchemaPath {
10    #[cfg(feature = "generate")]
11    pub fn root() -> Self {
12        Self(VecDeque::new())
13    }
14
15    #[cfg(feature = "map-schema")]
16    pub fn append(&self, path: String) -> SchemaPath {
17        let mut res = self.0.clone();
18        res.push_back(path);
19        Self(res)
20    }
21
22    #[cfg(feature = "map-schema")]
23    pub fn len(&self) -> usize {
24        self.0.len()
25    }
26
27    #[cfg(feature = "map-schema")]
28    #[allow(dead_code)]
29    pub fn is_empty(&self) -> bool {
30        self.0.is_empty()
31    }
32
33    #[cfg(any())]
34    pub fn normalized_len(&self) -> usize {
35        self.0
36            .iter()
37            .filter(|s| !s.chars().all(|c| c.is_numeric()))
38            .count()
39    }
40
41    #[cfg(feature = "map-schema")]
42    pub fn pop(&self, num: i32) -> SchemaPath {
43        if num < 0 {
44            return self.clone();
45        }
46
47        let mut res = self.0.clone();
48        for _ in 0..num {
49            assert!(
50                res.pop_front().is_some(),
51                "Tried to remove more elements from path {} than exist",
52                self
53            );
54        }
55
56        Self(res)
57    }
58
59    #[cfg(feature = "map-schema")]
60    pub fn to_normalized_path(&self) -> String {
61        self.0
62            .iter()
63            .filter(|s| !s.chars().all(|c| c.is_numeric()))
64            .cloned()
65            .collect::<Vec<_>>()
66            .join(".")
67    }
68}
69
70#[cfg(feature = "serialize")]
71impl Serialize for SchemaPath {
72    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73    where
74        S: Serializer,
75    {
76        serializer.serialize_str(&self.to_string())
77    }
78}
79
80impl Display for SchemaPath {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        write!(
83            f,
84            "{}",
85            self.0.iter().cloned().collect::<Vec<_>>().join(".")
86        )
87    }
88}