reactive_graph_graph/types/namespaces/
segment.rs

1use crate::INSTANCE_ID_SEPARATOR;
2use crate::NAMESPACE_SEPARATOR;
3use serde::Deserialize;
4use serde::Serialize;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::str::FromStr;
8use thiserror::Error;
9
10#[cfg(any(test, feature = "test"))]
11use reactive_graph_utils_test::r_namespace_path_segment;
12
13#[cfg(any(test, feature = "test"))]
14use reactive_graph_utils_test::r_namespace_type_name;
15
16#[derive(Debug, Error, PartialEq)]
17pub enum NamespaceSegmentError {
18    #[error("The namespace segment must not be empty")]
19    MustNotBeEmpty,
20    #[error("The namespace segment {0} must not contain the namespace delimiter ::")]
21    MustNotContainDelimiter(String),
22    #[error("The namespace segment {0} must contain alphanumeric characters only")]
23    MustBeAlphanumeric(String),
24}
25
26/// A namespace segment only contains these alphanumeric chars and the underscore.
27#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
28pub struct NamespaceSegment(String);
29
30impl NamespaceSegment {
31    pub fn is_path(&self) -> bool {
32        !self.is_type()
33    }
34    pub fn is_type(&self) -> bool {
35        self.0.chars().next().map(char::is_uppercase).unwrap_or_default()
36    }
37}
38
39impl Display for NamespaceSegment {
40    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
41        write!(f, "{}", self.0)
42    }
43}
44
45impl AsRef<str> for NamespaceSegment {
46    fn as_ref(&self) -> &str {
47        self.0.as_str()
48    }
49}
50
51impl FromStr for NamespaceSegment {
52    type Err = NamespaceSegmentError;
53
54    fn from_str(segment: &str) -> Result<Self, Self::Err> {
55        let segment = segment.to_string();
56        if segment.is_empty() {
57            return Err(NamespaceSegmentError::MustNotBeEmpty.into());
58        }
59        if segment.contains(NAMESPACE_SEPARATOR) {
60            return Err(NamespaceSegmentError::MustNotContainDelimiter(segment).into());
61        }
62        if segment.contains(INSTANCE_ID_SEPARATOR) {
63            return Err(NamespaceSegmentError::MustNotContainDelimiter(segment).into());
64        }
65        if !segment.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
66            return Err(NamespaceSegmentError::MustBeAlphanumeric(segment).into());
67        }
68        Ok(NamespaceSegment(segment))
69    }
70}
71
72#[cfg(any(test, feature = "test"))]
73impl NamespaceSegment {
74    pub fn random_path_segment() -> Result<Self, NamespaceSegmentError> {
75        NamespaceSegment::from_str(&r_namespace_path_segment())
76    }
77
78    pub fn random_type_segment() -> Result<Self, NamespaceSegmentError> {
79        NamespaceSegment::from_str(&r_namespace_type_name())
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::NamespaceSegment;
86    use super::NamespaceSegmentError;
87    use std::str::FromStr;
88
89    #[test]
90    fn segment_from_str_test() {
91        assert_eq!(NamespaceSegmentError::MustNotBeEmpty, NamespaceSegment::from_str("").unwrap_err());
92        assert_eq!(
93            NamespaceSegmentError::MustNotContainDelimiter("namespace::namespace".to_string()),
94            NamespaceSegment::from_str("namespace::namespace").unwrap_err()
95        );
96        assert_eq!(
97            NamespaceSegmentError::MustNotContainDelimiter("namespace__namespace".to_string()),
98            NamespaceSegment::from_str("namespace__namespace").unwrap_err()
99        );
100        assert_eq!(NamespaceSegmentError::MustBeAlphanumeric("(".to_string()), NamespaceSegment::from_str("(").unwrap_err());
101        assert_eq!(NamespaceSegmentError::MustBeAlphanumeric(")".to_string()), NamespaceSegment::from_str(")").unwrap_err());
102        assert!(NamespaceSegment::from_str("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_").is_ok());
103    }
104
105    #[test]
106    fn segment_type_test() {
107        assert!(NamespaceSegment::from_str("TypeNameSegment").unwrap().is_type());
108        assert!(NamespaceSegment::from_str("namespace_path_segment").unwrap().is_path());
109    }
110
111    #[test]
112    fn random_path_segment_test() {
113        assert!(NamespaceSegment::random_path_segment().is_ok(), "Failed to create random path segment");
114    }
115
116    #[test]
117    fn random_type_segment_test() {
118        assert!(NamespaceSegment::random_type_segment().is_ok(), "Failed to create random type segment");
119    }
120}