mqtt5_protocol/validation/
shared_subscription.rs

1#[must_use]
2pub fn parse_shared_subscription(topic_filter: &str) -> (&str, Option<&str>) {
3    if let Some(after_share) = topic_filter.strip_prefix("$share/") {
4        if let Some(slash_pos) = after_share.find('/') {
5            let group_name = &after_share[..slash_pos];
6            let actual_filter = &after_share[slash_pos + 1..];
7            return (actual_filter, Some(group_name));
8        }
9    }
10    (topic_filter, None)
11}
12
13#[must_use]
14pub fn strip_shared_subscription_prefix(topic_filter: &str) -> &str {
15    parse_shared_subscription(topic_filter).0
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21
22    #[test]
23    fn test_parse_shared_subscription() {
24        assert_eq!(
25            parse_shared_subscription("$share/workers/tasks/+"),
26            ("tasks/+", Some("workers"))
27        );
28        assert_eq!(
29            parse_shared_subscription("$share/group1/sensor/temperature"),
30            ("sensor/temperature", Some("group1"))
31        );
32        assert_eq!(
33            parse_shared_subscription("$share/mygroup/#"),
34            ("#", Some("mygroup"))
35        );
36        assert_eq!(
37            parse_shared_subscription("normal/topic"),
38            ("normal/topic", None)
39        );
40        assert_eq!(parse_shared_subscription("#"), ("#", None));
41        assert_eq!(
42            parse_shared_subscription("$share/incomplete"),
43            ("$share/incomplete", None)
44        );
45        assert_eq!(parse_shared_subscription(""), ("", None));
46    }
47
48    #[test]
49    fn test_strip_shared_subscription_prefix() {
50        assert_eq!(
51            strip_shared_subscription_prefix("$share/workers/tasks/+"),
52            "tasks/+"
53        );
54        assert_eq!(
55            strip_shared_subscription_prefix("$share/group1/sensor/temp"),
56            "sensor/temp"
57        );
58        assert_eq!(
59            strip_shared_subscription_prefix("normal/topic"),
60            "normal/topic"
61        );
62        assert_eq!(strip_shared_subscription_prefix("#"), "#");
63        assert_eq!(
64            strip_shared_subscription_prefix("$share/nofilter"),
65            "$share/nofilter"
66        );
67    }
68}