1use alloc::{boxed::Box, format, string::String, vec::Vec};
5use core::fmt;
6
7use crate::inbound_key::KeyId;
8
9pub const MAX_CAPTURES: usize = 8;
11
12pub type Spans = [(u16, u16); MAX_CAPTURES];
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct PatternError(String);
18
19impl fmt::Display for PatternError {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 f.write_str(&self.0)
22 }
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum PatternPart<'a> {
28 Text(&'a str),
29 Capture {
31 name: &'a str,
32 multi: bool,
33 },
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TopicPattern<'a> {
39 topic: &'a str,
40 parts: Vec<PatternPart<'a>>,
41}
42
43impl<'a> TopicPattern<'a> {
44 pub fn parse(topic: &'a str) -> Result<Self, PatternError> {
47 let mut parts = Vec::new();
48 let mut captures = 0;
49 let mut rest = topic;
50
51 while let Some(open) = rest.find(['{', '}']) {
52 if rest[open..].starts_with('}') {
53 return Err(PatternError(format!("unbalanced '}}' in '{topic}'")));
54 }
55 let after = &rest[open + 1..];
56 let close = match after.find(['{', '}']) {
57 Some(i) if after[i..].starts_with('}') => i,
58 _ => return Err(PatternError(format!("unbalanced '{{' in '{topic}'"))),
59 };
60 let body = &after[..close];
61 let (name, multi) = match body.strip_suffix("..") {
62 Some(name) => (name, true),
63 None => (body, false),
64 };
65 if name.is_empty() {
66 return Err(PatternError(format!("empty capture name in '{topic}'")));
67 }
68 if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
69 return Err(PatternError(format!(
70 "capture name '{name}' in '{topic}' may only contain A-Z, a-z, 0-9 and _"
71 )));
72 }
73 if parts
74 .iter()
75 .any(|p| matches!(p, PatternPart::Capture { name: n, .. } if *n == name))
76 {
77 return Err(PatternError(format!(
78 "capture '{name}' appears twice in '{topic}'"
79 )));
80 }
81 if captures == MAX_CAPTURES {
82 return Err(PatternError(format!(
83 "'{topic}' has more than {MAX_CAPTURES} captures"
84 )));
85 }
86 if open > 0 {
87 parts.push(PatternPart::Text(&rest[..open]));
88 }
89 parts.push(PatternPart::Capture { name, multi });
90 captures += 1;
91 rest = &after[close + 1..];
92 }
93 if !rest.is_empty() {
94 parts.push(PatternPart::Text(rest));
95 }
96
97 Ok(Self { topic, parts })
98 }
99
100 pub fn as_str(&self) -> &'a str {
101 self.topic
102 }
103
104 pub(crate) fn capture_names(&self) -> impl Iterator<Item = &'a str> + '_ {
106 self.parts.iter().filter_map(|p| match p {
107 PatternPart::Capture { name, .. } => Some(*name),
108 PatternPart::Text(_) => None,
109 })
110 }
111
112 pub fn parts(&self) -> &[PatternPart<'a>] {
114 &self.parts
115 }
116
117 pub fn has_captures(&self) -> bool {
118 self.parts
119 .iter()
120 .any(|p| matches!(p, PatternPart::Capture { .. }))
121 }
122}
123
124#[derive(Debug, Clone, Copy)]
126pub struct TopicMatch<'a> {
127 topic: &'a str,
128 names: &'a [Box<str>],
129 spans: &'a Spans,
130 key: Option<KeyId>,
131}
132
133impl<'a> TopicMatch<'a> {
134 pub(crate) fn new(
135 topic: &'a str,
136 names: &'a [Box<str>],
137 spans: &'a Spans,
138 key: Option<KeyId>,
139 ) -> Self {
140 Self {
141 topic,
142 names,
143 spans,
144 key,
145 }
146 }
147
148 pub fn topic(&self) -> &'a str {
149 self.topic
150 }
151
152 pub fn get(&self, name: &str) -> Option<&'a str> {
154 let i = self.names.iter().position(|n| &**n == name)?;
155 let &(start, end) = self.spans.get(i)?;
156 self.topic.get(usize::from(start)..usize::from(end))
157 }
158
159 pub fn key(&self) -> Option<KeyId> {
161 self.key
162 }
163}
164
165pub trait TopicGrammar: Send + Sync {
167 fn compile(&self, pattern: &TopicPattern<'_>) -> Result<Box<dyn TopicFilter>, String>;
168
169 fn covers(&self, a: &str, b: &str) -> bool {
171 a == b
172 }
173}
174
175pub trait TopicFilter: Send + Sync {
177 fn filter(&self) -> &str;
179
180 fn is_literal(&self) -> bool;
182
183 fn matches(&self, topic: &str, spans: &mut Spans) -> bool;
185}
186
187#[derive(Debug, Clone, Copy, Default)]
189pub struct ExactGrammar;
190
191impl TopicGrammar for ExactGrammar {
192 fn compile(&self, pattern: &TopicPattern<'_>) -> Result<Box<dyn TopicFilter>, String> {
193 if pattern.has_captures() {
194 return Err(format!(
195 "'{}': this connector does not support topic patterns",
196 pattern.as_str()
197 ));
198 }
199 Ok(Box::new(ExactFilter(pattern.as_str().into())))
200 }
201}
202
203struct ExactFilter(Box<str>);
204
205impl TopicFilter for ExactFilter {
206 fn filter(&self) -> &str {
207 &self.0
208 }
209
210 fn is_literal(&self) -> bool {
211 true
212 }
213
214 fn matches(&self, topic: &str, _spans: &mut Spans) -> bool {
215 topic == &*self.0
216 }
217}
218
219#[cfg(test)]
221pub(crate) mod test_support {
222 use super::*;
223 use alloc::string::ToString;
224
225 pub(crate) struct Plus;
227
228 pub(crate) struct PlusFilter {
229 filter: String,
230 levels: Vec<Option<String>>,
232 captures: Vec<Option<usize>>,
234 }
235
236 impl TopicGrammar for Plus {
237 fn compile(&self, pattern: &TopicPattern<'_>) -> Result<Box<dyn TopicFilter>, String> {
238 let mut filter = String::new();
239 let mut captures = Vec::new();
240 for part in pattern.parts() {
241 match part {
242 PatternPart::Text(t) => filter.push_str(t),
243 PatternPart::Capture { .. } => {
244 filter.push('+');
245 captures.push(filter.split('/').count() - 1);
246 }
247 }
248 }
249 let levels: Vec<Option<String>> = filter
250 .split('/')
251 .map(|l| (l != "+").then(|| l.to_string()))
252 .collect();
253 let captures = (0..levels.len())
254 .map(|i| captures.iter().position(|&c| c == i))
255 .collect();
256 Ok(Box::new(PlusFilter {
257 filter,
258 levels,
259 captures,
260 }))
261 }
262
263 fn covers(&self, a: &str, b: &str) -> bool {
264 a.split('/').count() == b.split('/').count()
265 && a.split('/')
266 .zip(b.split('/'))
267 .all(|(x, y)| x == "+" || x == y)
268 }
269 }
270
271 impl TopicFilter for PlusFilter {
272 fn filter(&self) -> &str {
273 &self.filter
274 }
275 fn is_literal(&self) -> bool {
276 self.levels.iter().all(Option::is_some)
277 }
278 fn matches(&self, topic: &str, spans: &mut Spans) -> bool {
279 if topic.split('/').count() != self.levels.len() {
280 return false;
281 }
282 let mut start = 0;
283 for (i, level) in topic.split('/').enumerate() {
284 match &self.levels[i] {
285 Some(lit) if lit != level => return false,
286 _ => {}
287 }
288 if let Some(c) = self.captures[i] {
289 spans[c] = (start as u16, (start + level.len()) as u16);
290 }
291 start += level.len() + 1;
292 }
293 true
294 }
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301 use alloc::string::ToString;
302
303 fn parts(topic: &str) -> Vec<PatternPart<'_>> {
304 TopicPattern::parse(topic).unwrap().parts().to_vec()
305 }
306
307 #[test]
308 fn parse_splits_text_and_captures() {
309 use PatternPart::{Capture, Text};
310 assert_eq!(
311 parts("a/{x}/b/{rest..}"),
312 [
313 Text("a/"),
314 Capture {
315 name: "x",
316 multi: false
317 },
318 Text("/b/"),
319 Capture {
320 name: "rest",
321 multi: true
322 },
323 ]
324 );
325 assert_eq!(
326 parts("{x}"),
327 [Capture {
328 name: "x",
329 multi: false
330 }]
331 );
332 assert_eq!(parts("a/+/#"), [Text("a/+/#")]);
333 assert!(!TopicPattern::parse("a/+/#").unwrap().has_captures());
334 assert!(TopicPattern::parse("dev-{id}").unwrap().has_captures());
335 }
336
337 #[test]
338 fn parse_errors() {
339 for (topic, needle) in [
340 ("a/{x", "unbalanced '{'"),
341 ("a/x}", "unbalanced '}'"),
342 ("a/{{x}}", "unbalanced '{'"),
343 ("a/{}", "empty capture name"),
344 ("a/{..}", "empty capture name"),
345 ("a/{x-y}", "may only contain"),
346 ("a/{x}/{x..}", "appears twice"),
347 ("{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}", "more than 8"),
348 ] {
349 let err = TopicPattern::parse(topic).unwrap_err().to_string();
350 assert!(err.contains(needle), "'{topic}': {err}");
351 }
352 assert!(TopicPattern::parse("{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}").is_ok());
353 }
354
355 #[test]
356 fn exact_grammar_compares_strings() {
357 let filter = ExactGrammar
358 .compile(&TopicPattern::parse("a/+/#").unwrap())
359 .unwrap();
360 let mut spans = [(0, 0); MAX_CAPTURES];
361 assert!(filter.is_literal());
362 assert_eq!(filter.filter(), "a/+/#");
363 assert!(filter.matches("a/+/#", &mut spans));
364 assert!(!filter.matches("a/b/c", &mut spans));
365 }
366
367 #[test]
368 fn exact_grammar_rejects_captures() {
369 let err = ExactGrammar
370 .compile(&TopicPattern::parse("a/{x}").unwrap())
371 .err()
372 .unwrap();
373 assert!(err.contains("does not support topic patterns"), "{err}");
374 }
375
376 #[test]
377 fn default_covers_is_equality() {
378 assert!(ExactGrammar.covers("a/b", "a/b"));
379 assert!(!ExactGrammar.covers("a/+", "a/b"));
380 }
381}