reactive_graph_graph/types/namespaces/
namespace.rs

1use convert_case::Case::Pascal;
2use convert_case::Casing;
3use schemars::JsonSchema;
4use serde::Deserialize;
5use serde::Serialize;
6use std::collections::BTreeSet;
7use std::collections::btree_set::IntoIter;
8use std::fmt::Display;
9use std::fmt::Formatter;
10use std::hash::Hash;
11use std::hash::Hasher;
12use std::ops::Deref;
13use std::ops::DerefMut;
14use std::path::PathBuf;
15use std::str::FromStr;
16use thiserror::Error;
17
18use crate::NamespaceSegment;
19use crate::NamespaceSegmentError;
20
21#[cfg(any(test, feature = "test"))]
22use rand::Rng;
23
24/// Separator for the string representation of a type definition.
25pub static NAMESPACE_SEPARATOR: &str = "::";
26
27/// Separator for the relative path representation of a type definition.
28pub static RELATIVE_PATH_SEPARATOR: &str = "/";
29
30#[derive(Debug, Error)]
31pub enum NamespaceError {
32    #[error("The namespace is invalid because a segment is invalid: {0}")]
33    SegmentError(#[from] NamespaceSegmentError),
34    #[error("\"{0}\" is not a valid namespace because a type must be prefixed with a path")]
35    MissingPathForType(NamespaceSegment),
36    #[error("Type \"{0}\" cannot be appended with \"{1}\" because types must be the last segment of a namespace.")]
37    TypeCannotBeAppended(Namespace, NamespaceSegment),
38}
39
40#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, JsonSchema, Serialize, Deserialize)]
41#[serde(into = "String", try_from = "String")]
42pub struct Namespace(Vec<NamespaceSegment>);
43
44impl Namespace {
45    pub fn new_top_level_from_segment(segment: NamespaceSegment) -> Result<Namespace, NamespaceError> {
46        if segment.is_type() {
47            return Err(NamespaceError::MissingPathForType(segment));
48        }
49        Ok(Namespace(vec![segment]))
50    }
51
52    pub fn try_new_top_level<S: Into<String>>(segment: S) -> Result<Namespace, NamespaceError> {
53        let segment = segment.into();
54        NamespaceSegment::from_str(&segment)
55            .map_err(NamespaceError::from)
56            .and_then(Namespace::new_top_level_from_segment)
57    }
58
59    pub fn try_append_segment(&self, segment: NamespaceSegment) -> Result<Self, NamespaceError> {
60        let mut namespace = self.clone();
61        if self.is_type() {
62            return Err(NamespaceError::TypeCannotBeAppended(namespace, segment));
63        }
64        namespace.0.push(segment);
65        Ok(namespace)
66    }
67
68    pub fn try_append<S: Into<String>>(self, segment: S) -> Result<Self, NamespaceError> {
69        let segment = segment.into();
70        self.try_append_segment(NamespaceSegment::from_str(&segment).map_err(NamespaceError::from)?)
71    }
72
73    pub fn parent(&self) -> Option<Namespace> {
74        let mut segments = self.get_segments();
75        if segments.len() <= 1 {
76            return None;
77        }
78        if segments.pop().is_none() {
79            return None;
80        }
81        Some(Namespace(segments))
82    }
83
84    pub fn get_segments(&self) -> Vec<NamespaceSegment> {
85        self.0.clone()
86    }
87
88    pub fn last_segment(&self) -> Option<NamespaceSegment> {
89        self.0.last().cloned()
90    }
91
92    pub fn is_path(&self) -> bool {
93        !self.is_type()
94    }
95
96    pub fn is_type(&self) -> bool {
97        self.last_segment().map(|segment| segment.is_type()).unwrap_or(false)
98    }
99
100    pub fn relative_url(&self) -> String {
101        self.to_string().replace(NAMESPACE_SEPARATOR, RELATIVE_PATH_SEPARATOR)
102    }
103
104    pub fn relative_path(&self) -> PathBuf {
105        PathBuf::from(self.relative_url())
106    }
107
108    /// Returns the fully qualified type name in pascal case.
109    /// For example, namespace1::namespace2::namespace3::TypeName will become
110    /// Namespace1Namespace2Namespace3TypeName
111    pub fn fully_qualified_type_name(&self) -> String {
112        format!("{}", self.0.iter().map(|y| y.to_string().to_case(Pascal)).collect::<Vec<String>>().join(""))
113    }
114
115    pub fn parse_optional_namespace(namespace: Option<String>) -> Result<Option<Self>, NamespaceError>
116    where
117        Self: Sized,
118    {
119        match namespace {
120            None => Ok(None),
121            Some(namespace) => Self::from_str(&namespace).map(Some),
122        }
123    }
124}
125
126impl Display for Namespace {
127    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
128        write!(
129            f,
130            "{}",
131            self.0
132                .iter()
133                .map(|segment| segment.to_string())
134                .collect::<Vec<String>>()
135                .join(NAMESPACE_SEPARATOR)
136        )
137    }
138}
139
140impl From<&Namespace> for Namespace {
141    fn from(namespace: &Namespace) -> Self {
142        namespace.clone()
143    }
144}
145
146impl From<Namespace> for String {
147    fn from(namespace: Namespace) -> Self {
148        namespace.to_string()
149    }
150}
151
152impl FromStr for Namespace {
153    type Err = NamespaceError;
154
155    fn from_str(namespace: &str) -> Result<Self, Self::Err> {
156        let mut split = namespace.split(NAMESPACE_SEPARATOR);
157        let Some(top_level_segment) = split.next() else {
158            return Err(NamespaceError::SegmentError(NamespaceSegmentError::MustNotBeEmpty));
159        };
160        let mut namespace = Namespace::try_new_top_level(top_level_segment)?;
161        while let Some(segment) = split.next() {
162            namespace = namespace.try_append(segment)?;
163        }
164        Ok(namespace)
165    }
166}
167
168impl TryFrom<NamespaceSegment> for Namespace {
169    type Error = NamespaceError;
170
171    fn try_from(segment: NamespaceSegment) -> Result<Self, Self::Error> {
172        Namespace::new_top_level_from_segment(segment)
173    }
174}
175
176// Required because of #[serde(try_from = "String")]
177impl TryFrom<String> for Namespace {
178    type Error = NamespaceError;
179
180    fn try_from(namespace: String) -> Result<Self, Self::Error> {
181        Self::from_str(namespace.as_str())
182    }
183}
184
185#[derive(Clone, Debug, Default, Serialize, Deserialize)]
186pub struct Namespaces(BTreeSet<Namespace>);
187
188impl Namespaces {
189    pub fn new() -> Self {
190        Self(BTreeSet::new())
191    }
192
193    pub fn is_empty(&self) -> bool {
194        self.0.is_empty()
195    }
196
197    pub fn to_vec(&self) -> Vec<Namespace> {
198        let mut tys: Vec<Namespace> = self.iter().map(|ty| ty.clone()).collect();
199        tys.sort();
200        tys
201    }
202
203    // TODO: to_sorted_vec()
204}
205
206impl Deref for Namespaces {
207    type Target = BTreeSet<Namespace>;
208
209    fn deref(&self) -> &Self::Target {
210        &self.0
211    }
212}
213
214impl DerefMut for Namespaces {
215    fn deref_mut(&mut self) -> &mut Self::Target {
216        &mut self.0
217    }
218}
219
220impl IntoIterator for Namespaces {
221    type Item = Namespace;
222    type IntoIter = IntoIter<Namespace>;
223
224    fn into_iter(self) -> Self::IntoIter {
225        self.0.into_iter()
226    }
227}
228
229impl PartialEq for Namespaces {
230    fn eq(&self, other: &Self) -> bool {
231        let this = self.to_vec();
232        let other = other.to_vec();
233        this.eq(&other)
234    }
235}
236
237impl Eq for Namespaces {}
238
239impl Hash for Namespaces {
240    fn hash<H: Hasher>(&self, state: &mut H) {
241        self.to_vec().hash(state);
242    }
243}
244
245impl From<Vec<Namespace>> for Namespaces {
246    fn from(tys: Vec<Namespace>) -> Self {
247        Self(tys.into_iter().collect())
248    }
249}
250
251impl From<Namespaces> for Vec<Namespace> {
252    fn from(tys: Namespaces) -> Self {
253        tys.to_vec()
254    }
255}
256
257impl From<&Namespaces> for Vec<Namespace> {
258    fn from(tys: &Namespaces) -> Self {
259        tys.0.iter().map(|ty| ty.clone()).collect()
260    }
261}
262
263impl From<BTreeSet<Namespace>> for Namespaces {
264    fn from(tys: BTreeSet<Namespace>) -> Self {
265        Self(tys)
266    }
267}
268
269impl From<&BTreeSet<Namespace>> for Namespaces {
270    fn from(tys: &BTreeSet<Namespace>) -> Self {
271        Self(tys.clone())
272    }
273}
274
275impl From<Namespaces> for BTreeSet<Namespace> {
276    fn from(tys: Namespaces) -> Self {
277        tys.0
278    }
279}
280
281impl FromIterator<Namespace> for Namespaces {
282    fn from_iter<I: IntoIterator<Item = Namespace>>(iter: I) -> Self {
283        let mut tys = Self::new();
284        for ty in iter {
285            tys.insert(ty);
286        }
287        tys
288    }
289}
290
291#[cfg(any(test, feature = "test"))]
292impl Namespace {
293    pub fn random_path() -> Result<Self, NamespaceError> {
294        let mut namespace = Namespace::new_top_level_from_segment(NamespaceSegment::random_path_segment().map_err(NamespaceError::SegmentError)?)?;
295        let mut rng = rand::rng();
296        for _ in 1..rng.random_range(1..5) {
297            namespace = namespace.try_append_segment(NamespaceSegment::random_path_segment().map_err(NamespaceError::SegmentError)?)?;
298        }
299        Ok(namespace)
300    }
301
302    pub fn random_child_path(&self) -> Result<Self, NamespaceError> {
303        let mut namespace = self.clone();
304        let mut rng = rand::rng();
305        for _ in 1..rng.random_range(1..5) {
306            namespace = namespace.try_append_segment(NamespaceSegment::random_path_segment().map_err(NamespaceError::SegmentError)?)?;
307        }
308        Ok(namespace)
309    }
310
311    pub fn random_type() -> Result<Self, NamespaceError> {
312        Self::random_path()?.try_append_segment(NamespaceSegment::random_type_segment().map_err(NamespaceError::SegmentError)?)
313    }
314
315    pub fn random_child_type(&self) -> Result<Self, NamespaceError> {
316        self.random_child_path()?
317            .try_append_segment(NamespaceSegment::random_type_segment().map_err(NamespaceError::SegmentError)?)
318    }
319}
320
321#[cfg(any(test, feature = "test"))]
322impl Namespaces {
323    pub fn random_types() -> Result<Self, NamespaceError> {
324        let mut types = Self::new();
325        let mut rng = rand::rng();
326        for _ in 0..rng.random_range(0..10) {
327            types.insert(Namespace::random_type()?);
328        }
329        Ok(types)
330    }
331
332    pub fn random_path_tree() -> Result<Self, NamespaceError> {
333        let mut types = Self::new();
334        let mut rng = rand::rng();
335        for _ in 0..rng.random_range(0..10) {
336            let namespace = Namespace::random_path()?;
337            for _ in 0..rng.random_range(0..10) {
338                types.insert(namespace.random_child_path()?);
339            }
340        }
341        Ok(types)
342    }
343    pub fn random_type_tree() -> Result<Self, NamespaceError> {
344        let mut types = Self::new();
345        let mut rng = rand::rng();
346        for _ in 0..rng.random_range(0..10) {
347            let namespace = Namespace::random_path()?;
348            for _ in 0..rng.random_range(0..10) {
349                types.insert(namespace.random_child_type()?);
350            }
351        }
352        Ok(types)
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::Namespace;
359    use std::str::FromStr;
360
361    #[test]
362    fn random_path_namespace_test() {
363        assert!(Namespace::random_path().is_ok(), "Failed to create random path namespace");
364    }
365
366    #[test]
367    fn random_type_namespace_test() {
368        assert!(Namespace::random_type().is_ok(), "Failed to create random type namespace");
369    }
370
371    #[test]
372    fn namespace_from_str_test() {
373        assert!(Namespace::from_str("namespace").is_ok());
374        assert!(Namespace::from_str("namespace::Type").is_ok());
375        assert!(Namespace::from_str("name_space::TypeName").is_ok());
376        assert!(Namespace::from_str("namespace::namespace").is_ok());
377        assert!(Namespace::from_str("namespace::namespace::Type").is_ok());
378        assert!(Namespace::from_str("namespace::namespace::namespace").is_ok());
379        assert!(Namespace::from_str("namespace::namespace::namespace::Type").is_ok());
380        assert!(Namespace::from_str("namespace::namespace::namespace::namespace").is_ok());
381        assert!(Namespace::from_str("namespace::namespace::namespace::namespace::Type").is_ok());
382
383        assert!(Namespace::from_str("").is_err());
384        assert!(Namespace::from_str("::").is_err());
385        assert!(Namespace::from_str("::::").is_err());
386        assert!(Namespace::from_str("__").is_err());
387        assert!(Namespace::from_str("____").is_err());
388        assert!(Namespace::from_str("namespace__Type").is_err());
389        assert!(Namespace::from_str("namespace::namespace__Type").is_err());
390        assert!(Namespace::from_str("Type").is_err());
391        assert!(Namespace::from_str("Namespace::Type").is_err());
392        assert!(Namespace::from_str("namespace::Namespace::Type").is_err());
393        assert!(Namespace::from_str("Namespace::namespace::type").is_err());
394        assert!(Namespace::from_str("namespace::Namespace::type").is_err());
395        assert!(Namespace::from_str("::Namespace::Type").is_err());
396        assert!(Namespace::from_str("::Namespace::Type::").is_err());
397        assert!(Namespace::from_str("namespace::Type::").is_err());
398        assert!(Namespace::from_str("Namespace::Type::").is_err());
399    }
400}