Skip to main content

quill/
pattern.rs

1//! Subscription patterns with MQTT-style wildcards.
2
3use std::fmt;
4
5use crate::topic::{DEFAULT_DELIMITER, ParseError, Topic, split_segments};
6
7/// One segment of a [`Pattern`].
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub enum Segment {
10    /// Exact segment match.
11    Literal(String),
12    /// Single-level wildcard (`+`): matches exactly one topic segment.
13    Single,
14    /// Multi-level wildcard (`#`): matches zero or more remaining segments.
15    /// Must be the final segment of a pattern.
16    Multi,
17}
18
19impl Segment {
20    fn from_raw(raw: &str) -> Self {
21        match raw {
22            "+" => Self::Single,
23            "#" => Self::Multi,
24            other => Self::Literal(other.to_owned()),
25        }
26    }
27}
28
29impl fmt::Display for Segment {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::Literal(s) => write!(f, "{s}"),
33            Self::Single => write!(f, "+"),
34            Self::Multi => write!(f, "#"),
35        }
36    }
37}
38
39/// A subscription filter that may include wildcards.
40///
41/// Wildcards follow MQTT conventions:
42/// - `+` matches exactly one level
43/// - `#` matches the remainder of the topic (including zero levels) and may
44///   only appear as the **last** segment
45///
46/// # Examples
47///
48/// ```
49/// use quill::{Pattern, Topic};
50///
51/// let pat = Pattern::parse("sensors/+/temp").unwrap();
52/// let topic = Topic::parse("sensors/kitchen/temp").unwrap();
53/// assert!(pat.matches(&topic));
54/// ```
55#[derive(Debug, Clone, PartialEq, Eq, Hash)]
56pub struct Pattern {
57    segments: Vec<Segment>,
58    delimiter: char,
59}
60
61impl Pattern {
62    /// Parse `input` using the [default delimiter](DEFAULT_DELIMITER).
63    pub fn parse(input: &str) -> Result<Self, ParseError> {
64        Self::parse_with(input, DEFAULT_DELIMITER)
65    }
66
67    /// Parse `input` using a custom segment `delimiter`.
68    pub fn parse_with(input: &str, delimiter: char) -> Result<Self, ParseError> {
69        let raw = split_segments(input, delimiter)?;
70        let segments: Vec<Segment> = raw.iter().map(|s| Segment::from_raw(s)).collect();
71        validate_segments(&segments)?;
72        Ok(Self {
73            segments,
74            delimiter,
75        })
76    }
77
78    /// Borrowed pattern segments in order.
79    pub fn segments(&self) -> &[Segment] {
80        &self.segments
81    }
82
83    /// The delimiter used when this pattern was parsed.
84    pub fn delimiter(&self) -> char {
85        self.delimiter
86    }
87
88    /// Returns `true` if this pattern matches `topic`.
89    ///
90    /// Matching compares segments only; delimiters need not be equal as long
91    /// as both values were parsed consistently by the caller.
92    pub fn matches(&self, topic: &Topic) -> bool {
93        matches_rec(self.segments(), topic.segments(), 0, 0)
94    }
95}
96
97impl TryFrom<&str> for Pattern {
98    type Error = ParseError;
99
100    fn try_from(value: &str) -> Result<Self, Self::Error> {
101        Self::parse(value)
102    }
103}
104
105impl fmt::Display for Pattern {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        for (i, seg) in self.segments.iter().enumerate() {
108            if i > 0 {
109                write!(f, "{}", self.delimiter)?;
110            }
111            write!(f, "{seg}")?;
112        }
113        Ok(())
114    }
115}
116
117fn validate_segments(segments: &[Segment]) -> Result<(), ParseError> {
118    let last = segments.len().saturating_sub(1);
119    for (i, seg) in segments.iter().enumerate() {
120        if matches!(seg, Segment::Multi) && i != last {
121            return Err(ParseError::MultiLevelNotFinal);
122        }
123    }
124    Ok(())
125}
126
127fn matches_rec(pat: &[Segment], topic: &[String], pi: usize, ti: usize) -> bool {
128    if pi == pat.len() {
129        return ti == topic.len();
130    }
131
132    match &pat[pi] {
133        Segment::Multi => {
134            // `#` must be final (validated at parse); matches any suffix.
135            true
136        }
137        Segment::Single => {
138            if ti >= topic.len() {
139                return false;
140            }
141            matches_rec(pat, topic, pi + 1, ti + 1)
142        }
143        Segment::Literal(lit) => {
144            if ti >= topic.len() || topic[ti] != *lit {
145                return false;
146            }
147            matches_rec(pat, topic, pi + 1, ti + 1)
148        }
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    fn topic(s: &str) -> Topic {
157        Topic::parse(s).unwrap()
158    }
159
160    fn pattern(s: &str) -> Pattern {
161        Pattern::parse(s).unwrap()
162    }
163
164    #[test]
165    fn parse_literals_and_wildcards() {
166        let p = pattern("sensors/+/temp/#");
167        assert_eq!(
168            p.segments(),
169            &[
170                Segment::Literal("sensors".into()),
171                Segment::Single,
172                Segment::Literal("temp".into()),
173                Segment::Multi,
174            ]
175        );
176    }
177
178    #[test]
179    fn parse_hash_alone() {
180        let p = pattern("#");
181        assert_eq!(p.segments(), &[Segment::Multi]);
182    }
183
184    #[test]
185    fn reject_multi_not_final() {
186        assert_eq!(
187            Pattern::parse("sensors/#/temp"),
188            Err(ParseError::MultiLevelNotFinal)
189        );
190    }
191
192    #[test]
193    fn reject_empty_and_bad_segments() {
194        assert_eq!(Pattern::parse(""), Err(ParseError::Empty));
195        assert_eq!(Pattern::parse("/a"), Err(ParseError::EmptySegment));
196        assert_eq!(Pattern::parse("a/"), Err(ParseError::EmptySegment));
197        assert_eq!(Pattern::parse("a//b"), Err(ParseError::EmptySegment));
198    }
199
200    #[test]
201    fn plus_is_only_whole_segment() {
202        // "foo+" is a literal, not a wildcard.
203        let p = pattern("foo+");
204        assert_eq!(p.segments(), &[Segment::Literal("foo+".into())]);
205        assert!(p.matches(&topic("foo+")));
206        assert!(!p.matches(&topic("foo")));
207    }
208
209    #[test]
210    fn exact_match() {
211        let p = pattern("sensors/kitchen/temp");
212        assert!(p.matches(&topic("sensors/kitchen/temp")));
213        assert!(!p.matches(&topic("sensors/kitchen/humidity")));
214        assert!(!p.matches(&topic("sensors/kitchen")));
215    }
216
217    #[test]
218    fn single_level_wildcard() {
219        let p = pattern("sensors/+/temp");
220        assert!(p.matches(&topic("sensors/kitchen/temp")));
221        assert!(p.matches(&topic("sensors/garage/temp")));
222        assert!(!p.matches(&topic("sensors/kitchen/humidity")));
223        assert!(!p.matches(&topic("sensors/kitchen/pantry/temp")));
224        assert!(!p.matches(&topic("sensors/temp")));
225    }
226
227    #[test]
228    fn multi_level_wildcard() {
229        let p = pattern("sensors/#");
230        assert!(p.matches(&topic("sensors")));
231        assert!(p.matches(&topic("sensors/kitchen")));
232        assert!(p.matches(&topic("sensors/kitchen/temp")));
233        assert!(!p.matches(&topic("actuators/relay")));
234    }
235
236    #[test]
237    fn hash_matches_everything() {
238        let p = pattern("#");
239        assert!(p.matches(&topic("a")));
240        assert!(p.matches(&topic("a/b/c")));
241    }
242
243    #[test]
244    fn mixed_wildcards() {
245        let p = pattern("+/+/temp/#");
246        assert!(p.matches(&topic("sensors/kitchen/temp")));
247        assert!(p.matches(&topic("sensors/kitchen/temp/celsius")));
248        assert!(!p.matches(&topic("sensors/kitchen/humidity")));
249    }
250
251    #[test]
252    fn display_round_trip_shape() {
253        let p = pattern("a/+/b/#");
254        assert_eq!(p.to_string(), "a/+/b/#");
255    }
256
257    #[test]
258    fn custom_delimiter() {
259        let p = Pattern::parse_with("a.+.b", '.').unwrap();
260        let t = Topic::parse_with("a.x.b", '.').unwrap();
261        assert!(p.matches(&t));
262    }
263}