tightbeam_pubsub/
topic.rs1use core::error::Error;
5use core::fmt;
6use core::str::{from_utf8, FromStr, Utf8Error};
7use std::sync::Arc;
8
9pub const SUB_PREFIX: &str = "sub/";
11
12pub const UNSUB_PREFIX: &str = "unsub/";
14
15pub const PUB_PREFIX: &str = "pub/";
17
18pub const END_PREFIX: &str = "end/";
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub(crate) enum Verb {
24 Subscribe,
26 Unsubscribe,
28 Publish,
30 End,
32}
33
34impl Verb {
35 pub(crate) const ALL: [Self; 4] = [Self::Subscribe, Self::Unsubscribe, Self::Publish, Self::End];
37
38 pub(crate) const fn prefix(self) -> &'static str {
40 match self {
41 Self::Subscribe => SUB_PREFIX,
42 Self::Unsubscribe => UNSUB_PREFIX,
43 Self::Publish => PUB_PREFIX,
44 Self::End => END_PREFIX,
45 }
46 }
47
48 pub(crate) fn tag(self) -> &'static str {
50 let prefix = self.prefix();
51 prefix.trim_end_matches('/')
52 }
53}
54
55#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
65pub struct Topic(Arc<str>);
66
67impl Topic {
68 pub const MAX_LEN: usize = 256;
74
75 #[must_use]
77 pub fn as_str(&self) -> &str {
78 &self.0
79 }
80}
81
82impl fmt::Display for Topic {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(&self.0)
85 }
86}
87
88impl FromStr for Topic {
89 type Err = TopicError;
90
91 fn from_str(name: &str) -> Result<Self, Self::Err> {
99 if name.is_empty() {
100 return Err(TopicError::Empty);
101 }
102 if name.len() > Self::MAX_LEN {
103 return Err(TopicError::TooLong(name.len()));
104 }
105
106 let reserved = Verb::ALL.into_iter().find(|verb| name.starts_with(verb.prefix()));
107 if let Some(verb) = reserved {
108 return Err(TopicError::ReservedPrefix(verb.prefix()));
109 }
110
111 Ok(Self(Arc::from(name)))
112 }
113}
114
115impl TryFrom<&str> for Topic {
116 type Error = TopicError;
117
118 fn try_from(name: &str) -> Result<Self, Self::Error> {
119 name.parse()
120 }
121}
122
123impl TryFrom<&[u8]> for Topic {
124 type Error = TopicError;
125
126 fn try_from(name: &[u8]) -> Result<Self, Self::Error> {
133 let text = from_utf8(name)?;
134 text.parse()
135 }
136}
137
138impl From<Utf8Error> for TopicError {
139 fn from(cause: Utf8Error) -> Self {
140 Self::NotUtf8(cause)
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum TopicError {
147 Empty,
149 TooLong(usize),
152 ReservedPrefix(&'static str),
154 NotUtf8(Utf8Error),
156}
157
158impl fmt::Display for TopicError {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 match self {
161 Self::Empty => f.write_str("a topic name must be non-empty"),
162 Self::TooLong(len) => {
163 let max = Topic::MAX_LEN;
164 write!(f, "a topic name must fit in {max} octets, and this one holds {len}")
165 }
166 Self::NotUtf8(cause) => write!(f, "a topic name must be UTF-8: {cause}"),
167 Self::ReservedPrefix(prefix) => {
168 write!(f, "a topic name must not start with the reserved prefix {prefix}")
169 }
170 }
171 }
172}
173
174impl Error for TopicError {
175 fn source(&self) -> Option<&(dyn Error + 'static)> {
176 match self {
177 Self::NotUtf8(cause) => Some(cause),
178 _ => None,
179 }
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 fn parsed(name: &str) -> Topic {
189 name.parse().expect("the name should parse as a topic")
190 }
191
192 #[test]
193 fn accepts_hierarchical_names() {
194 let topic = parsed("prices/spot/BTC");
195 assert_eq!(topic.as_str(), "prices/spot/BTC");
196 assert_eq!(topic.to_string(), "prices/spot/BTC");
197 }
198
199 #[test]
200 fn accepts_names_containing_reserved_words_after_the_start() {
201 let topic = parsed("orders/sub/updates");
202 assert_eq!(topic.as_str(), "orders/sub/updates");
203 }
204
205 #[test]
206 fn rejects_an_empty_name() {
207 let outcome: Result<Topic, TopicError> = "".parse();
208 assert!(matches!(outcome, Err(TopicError::Empty)));
209 }
210
211 fn refused_prefix(name: &str) -> Option<&'static str> {
213 let outcome: Result<Topic, TopicError> = name.parse();
214 match outcome {
215 Err(TopicError::ReservedPrefix(prefix)) => Some(prefix),
216 _ => None,
217 }
218 }
219
220 #[test]
221 fn rejects_the_subscribe_prefix() {
222 assert_eq!(refused_prefix("sub/prices"), Some(SUB_PREFIX));
223 }
224
225 #[test]
226 fn rejects_the_unsubscribe_prefix() {
227 assert_eq!(refused_prefix("unsub/prices"), Some(UNSUB_PREFIX));
228 }
229
230 #[test]
231 fn rejects_the_publish_prefix() {
232 assert_eq!(refused_prefix("pub/prices"), Some(PUB_PREFIX));
233 }
234
235 #[test]
236 fn rejects_the_end_prefix() {
237 assert_eq!(refused_prefix("end/prices"), Some(END_PREFIX));
238 }
239
240 #[test]
241 fn a_verb_tags_audit_records_with_its_prefix() {
242 assert_eq!(Verb::Unsubscribe.tag(), "unsub");
243 }
244
245 #[test]
246 fn rejects_non_utf8_bytes() {
247 let outcome = Topic::try_from([0xff, 0xfe].as_slice());
248 assert!(matches!(outcome, Err(TopicError::NotUtf8(_))));
249 }
250
251 #[test]
252 fn accepts_a_name_at_the_length_ceiling() {
253 let name = "x".repeat(Topic::MAX_LEN);
254 let outcome: Result<Topic, TopicError> = name.parse();
255 assert!(outcome.is_ok());
256 }
257
258 #[test]
259 fn rejects_a_name_past_the_length_ceiling() {
260 let name = "x".repeat(Topic::MAX_LEN + 1);
261 let outcome: Result<Topic, TopicError> = name.parse();
262 assert!(matches!(outcome, Err(TopicError::TooLong(_))));
263 }
264
265 #[test]
266 fn parses_from_frame_id_octets() {
267 let parsed = Topic::try_from(b"chat/lobby".as_slice());
268 assert!(matches!(parsed, Ok(topic) if topic.as_str() == "chat/lobby"));
269 }
270}