1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use lazy_regex::{lazy_regex, Lazy};
use regex::Regex;
use selium_std::errors::{Result, SeliumError};
use serde::{Deserialize, Serialize};
use std::fmt::Display;

const RESERVED_NAMESPACE: &str = "selium";
// Any [a-zA-Z0-9-_] with a length between 3 and 64 chars
static COMPONENT_REGEX: Lazy<Regex> = lazy_regex!(r"^[\w-]{3,64}$");
static TOPIC_REGEX: Lazy<Regex> = lazy_regex!(r"^\/([\w-]{3,64})\/([\w-]{3,64})$");

#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct TopicName {
    namespace: String,
    topic: String,
}

impl TopicName {
    pub fn create(namespace: &str, topic: &str) -> Result<Self> {
        let s = Self {
            namespace: namespace.to_owned(),
            topic: topic.to_owned(),
        };

        if s.is_valid() {
            Ok(s)
        } else {
            Err(SeliumError::ParseTopicNameError)
        }
    }

    #[doc(hidden)]
    pub fn _create_unchecked(namespace: &str, topic: &str) -> Self {
        Self {
            namespace: namespace.into(),
            topic: topic.into(),
        }
    }

    pub fn is_valid(&self) -> bool {
        !(self.namespace.starts_with(RESERVED_NAMESPACE)
            || !COMPONENT_REGEX.is_match(&self.namespace)
            || !COMPONENT_REGEX.is_match(&self.topic))
    }

    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    pub fn topic(&self) -> &str {
        &self.topic
    }
}

impl TryFrom<&str> for TopicName {
    type Error = SeliumError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Err(SeliumError::ParseTopicNameError);
        }

        #[cfg(not(feature = "__notopiccheck"))]
        if value[1..].starts_with(RESERVED_NAMESPACE) {
            return Err(SeliumError::ReservedNamespaceError);
        }

        let matches = TOPIC_REGEX
            .captures(value)
            .ok_or(SeliumError::ParseTopicNameError)?;

        let namespace = matches.get(1).unwrap().as_str().to_owned();
        let topic = matches.get(2).unwrap().as_str().to_owned();

        Ok(Self { namespace, topic })
    }
}

impl Display for TopicName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "/{}/{}", self.namespace, self.topic)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fails_to_parse_poorly_formatted_topic_names() {
        let topic_names = [
            "",
            "namespace",
            "/namespace/",
            "/namespace/topic/other",
            "/namespace/topic!",
        ];

        for topic_name in topic_names {
            let result = TopicName::try_from(topic_name);
            assert!(result.is_err());
        }
    }

    #[cfg(not(feature = "__notopiccheck"))]
    #[test]
    fn fails_to_parse_reserved_namespace() {
        assert!(TopicName::try_from("/selium/topic").is_err());
    }

    #[test]
    fn successfully_parses_topic_name() {
        let topic_names = [
            "/namespace/topic",
            "/name_space/topic",
            "/namespace/to_pic",
            "/name_space/to_pic",
        ];

        for topic_name in topic_names {
            let result = TopicName::try_from(topic_name);
            assert!(result.is_ok());
        }
    }

    #[test]
    fn outputs_formatted_topic_name() {
        let namespace = "namespace";
        let topic = "topic";
        let topic_name = TopicName::create(namespace, topic).unwrap();
        let expected = format!("/{namespace}/{topic}");

        assert_eq!(topic_name.to_string(), expected);
    }
}