1extern crate alloc;
4use alloc::string::String;
5use core::fmt;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum NamespaceError {
10 Empty,
12 TooLong {
14 max: usize,
16 },
17 InvalidCharacter {
19 ch: char,
21 },
22 EmptySegment,
24 TrailingSeparator,
26}
27
28impl fmt::Display for NamespaceError {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::Empty => f.write_str("namespace must not be empty"),
32 Self::TooLong { max } => write!(f, "namespace exceeds {max} characters"),
33 Self::InvalidCharacter { ch } => {
34 write!(f, "namespace contains invalid character {ch:?}")
35 }
36 Self::EmptySegment => f.write_str("namespace must not contain empty path segments"),
37 Self::TrailingSeparator => f.write_str("namespace must not end with ':'"),
38 }
39 }
40}
41
42#[cfg(feature = "std")]
43impl std::error::Error for NamespaceError {}
44
45fn validate_namespace(value: &str) -> Result<(), NamespaceError> {
46 const MAX_LEN: usize = 256;
47 if value.is_empty() {
48 return Err(NamespaceError::Empty);
49 }
50 if value.len() > MAX_LEN {
51 return Err(NamespaceError::TooLong { max: MAX_LEN });
52 }
53 if value.ends_with(':') {
54 return Err(NamespaceError::TrailingSeparator);
55 }
56 for segment in value.split(':') {
57 if segment.is_empty() {
58 return Err(NamespaceError::EmptySegment);
59 }
60 for ch in segment.chars() {
61 if !ch.is_ascii_alphanumeric() && ch != '-' && ch != '_' && ch != '.' {
62 return Err(NamespaceError::InvalidCharacter { ch });
63 }
64 }
65 }
66 Ok(())
67}
68
69#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
74pub struct Namespace(String);
75
76impl Namespace {
77 pub const LOCAL: &'static str = "local";
79
80 pub fn parse(value: &str) -> Result<Self, NamespaceError> {
85 validate_namespace(value)?;
86 Ok(Self(String::from(value)))
87 }
88
89 pub fn local() -> Self {
91 Self(String::from(Self::LOCAL))
92 }
93
94 #[inline]
96 pub fn as_str(&self) -> &str {
97 &self.0
98 }
99
100 pub fn into_inner(self) -> String {
102 self.0
103 }
104}
105
106impl core::convert::TryFrom<String> for Namespace {
107 type Error = NamespaceError;
108
109 fn try_from(value: String) -> Result<Self, Self::Error> {
110 Self::parse(&value)
111 }
112}
113
114impl core::convert::TryFrom<&str> for Namespace {
115 type Error = NamespaceError;
116
117 fn try_from(value: &str) -> Result<Self, Self::Error> {
118 Self::parse(value)
119 }
120}
121
122impl fmt::Display for Namespace {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str(&self.0)
125 }
126}
127
128impl AsRef<str> for Namespace {
129 #[inline]
130 fn as_ref(&self) -> &str {
131 &self.0
132 }
133}
134
135pub fn has_segment_prefix(child: &Namespace, parent: &Namespace) -> bool {
139 let c = child.as_str();
140 let p = parent.as_str();
141 c.len() > p.len() && c.starts_with(p) && c.as_bytes().get(p.len()) == Some(&b':')
142}
143
144#[cfg(feature = "serde")]
145mod serde_impl {
146 use super::*;
147 use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
148
149 impl Serialize for Namespace {
150 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
151 s.serialize_str(&self.0)
152 }
153 }
154
155 impl<'de> Deserialize<'de> for Namespace {
156 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
157 let s = String::deserialize(d)?;
158 Namespace::parse(&s).map_err(de::Error::custom)
159 }
160 }
161}
162
163#[cfg(test)]
164#[path = "namespace_tests.rs"]
165mod tests;