hebo_codec 0.2.3

Packet codec for MQTT protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright (c) 2020 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

use byteorder::{BigEndian, WriteBytesExt};
use std::hash::{Hash, Hasher};
use std::io::Write;

use crate::QoS;
use crate::{ByteArray, DecodeError, DecodePacket, EncodeError, EncodePacket};

// TODO(Shaohua): Simplify topic structs.
#[derive(Debug, Default, Clone, Eq, PartialOrd, Ord)]
pub struct Topic {
    topic: String,
    parts: Vec<TopicPart>,
}

#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq, Eq)]
pub enum TopicError {
    EmptyTopic,
    TooManyData,
    InvalidChar,
    ContainsWildChar,
}

impl PartialEq for Topic {
    fn eq(&self, other: &Self) -> bool {
        self.topic.eq(&other.topic)
    }
}

impl Hash for Topic {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.topic.hash(state);
    }
}

impl Topic {
    // TODO(Shaohua): Replace with `std::str::FromStr` trait.

    /// Parse topic from string slice.
    ///
    /// # Errors
    ///
    /// Returns error if string contains invalid chars or too large.
    pub fn parse(s: &str) -> Result<Self, TopicError> {
        let parts = Self::parse_parts(s)?;
        Ok(Self {
            topic: s.to_string(),
            parts,
        })
    }

    fn parse_parts(s: &str) -> Result<Vec<TopicPart>, TopicError> {
        s.split('/').map(TopicPart::parse).collect()
    }

    /// Returns true if this topic matches string slice.
    #[must_use]
    pub fn is_match(&self, s: &str) -> bool {
        for (index, part) in s.split('/').into_iter().enumerate() {
            match self.parts.get(index) {
                None | Some(TopicPart::Empty) => return false,
                Some(TopicPart::Normal(ref s_part) | TopicPart::Internal(ref s_part)) => {
                    if s_part != part {
                        return false;
                    }
                }
                Some(TopicPart::SingleWildcard) => {
                    // Continue
                }
                Some(TopicPart::MultiWildcard) => return true,
            }
        }
        true
    }

    /// Used as a string slice.
    #[must_use]
    pub const fn topic(&self) -> &String {
        &self.topic
    }

    /// Get topic length.
    #[must_use]
    pub fn len(&self) -> usize {
        self.topic.len()
    }

    /// Returns true if topic is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.topic.is_empty()
    }

    /// Used as byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.topic.as_bytes()
    }
}

/// Validate topic filter.
///
/// Rules are defined in `MQTT chapter-4.7 Topic Name and Filters`
///
/// # Errors
///
/// Returns error if topic string contains invalid chars or too large.
///
/// # Examples
///
/// ```
/// use hebo_codec::topic;
/// let name = "sport/tennis/player/#";
/// assert!(topic::validate_sub_topic(name).is_ok());
///
/// let name = "sport/tennis/player#";
/// assert!(topic::validate_sub_topic(name).is_err());
///
/// let name = "#";
/// assert!(topic::validate_sub_topic(name).is_ok());
///
/// let name = "sport/#/player/ranking";
/// assert!(topic::validate_sub_topic(name).is_err());
///
/// let name = "+";
/// assert!(topic::validate_sub_topic(name).is_ok());
///
/// let name = "sport+";
/// assert!(topic::validate_sub_topic(name).is_err());
/// ```
#[allow(clippy::module_name_repetitions)]
pub fn validate_sub_topic(topic: &str) -> Result<(), TopicError> {
    if topic.is_empty() {
        return Err(TopicError::EmptyTopic);
    }
    if topic == "#" {
        return Ok(());
    }
    let bytes = topic.as_bytes();
    for (index, b) in bytes.iter().enumerate() {
        if b == &b'#' {
            // Must have a prefix level separator.
            if index > 0 && bytes[index - 1] != b'/' {
                return Err(TopicError::InvalidChar);
            }

            // Must be the last wildcard.
            if index != bytes.len() - 1 {
                return Err(TopicError::InvalidChar);
            }
        } else if b == &b'+' {
            // Must have a prefix level separator.
            if index > 0 && bytes[index - 1] != b'/' {
                return Err(TopicError::InvalidChar);
            }
        }
    }

    Ok(())
}

/// Check whether topic name contains wildchard characters or not.
///
/// # Errors
///
/// Returns error if topic string contains invalid characters or too large.
///
/// # Examples
///
/// ```
/// use hebo_codec::topic;
/// let name = "sport/tennis/player/#";
/// assert!(topic::validate_pub_topic(name).is_err());
///
/// let name = "sport/tennis/player/ranking";
/// assert!(topic::validate_pub_topic(name).is_ok());
/// ```
#[allow(clippy::module_name_repetitions)]
pub fn validate_pub_topic(topic: &str) -> Result<(), TopicError> {
    if topic.is_empty() {
        return Err(TopicError::EmptyTopic);
    }
    if topic.len() > u16::MAX as usize {
        return Err(TopicError::TooManyData);
    }

    if topic.as_bytes().iter().any(|c| c == &b'+' || c == &b'#') {
        Err(TopicError::InvalidChar)
    } else {
        Ok(())
    }
}

// TODO(Shaohua): Impl internal reference to `topic` String.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TopicPart {
    /// Special internal part, like `$SYS`.
    /// Topics start will `$` char will be traited as internal topic, even so
    /// only `$SYS` is used currently.
    Internal(String),

    /// Normal part.
    Normal(String),

    /// Empty part.
    #[default]
    Empty,

    /// `#` char, to match any remaining parts.
    MultiWildcard,

    /// `+` char, to match right part.
    SingleWildcard,
}

impl TopicPart {
    fn has_wildcard(s: &str) -> bool {
        s.contains(|c| c == '#' || c == '+')
    }

    /// Returns true if topic is used in broker inner only.
    #[must_use]
    fn is_internal(s: &str) -> bool {
        s.starts_with('$')
    }

    /// Parse topic parts.
    ///
    /// # Errors
    ///
    /// Returns error if string slice contains invalid chars.
    fn parse(s: &str) -> Result<Self, TopicError> {
        match s {
            "" => Ok(Self::Empty),
            "+" => Ok(Self::SingleWildcard),
            "#" => Ok(Self::MultiWildcard),
            _ => {
                if Self::has_wildcard(s) {
                    Err(TopicError::ContainsWildChar)
                } else if Self::is_internal(s) {
                    Ok(Self::Internal(s.to_string()))
                } else {
                    Ok(Self::Normal(s.to_string()))
                }
            }
        }
    }
}

/// Topic/QoS pair.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubscribePattern {
    /// Subscribed `topic` contains wildcard characters to match interested topics with patterns.
    topic: Topic,

    /// Maximum level of QoS of packet the Server can send to the Client.
    qos: QoS,
}

impl SubscribePattern {
    /// # Errors
    ///
    /// Returns error if `topic` is invalid.
    pub fn parse(topic: &str, qos: QoS) -> Result<Self, TopicError> {
        let topic = Topic::parse(topic)?;
        Ok(Self { topic, qos })
    }

    /// Create a new subscription topic pattern.
    #[must_use]
    #[inline]
    pub const fn new(topic: Topic, qos: QoS) -> Self {
        Self { topic, qos }
    }

    /// Get topic value.
    #[must_use]
    #[inline]
    pub const fn topic(&self) -> &Topic {
        &self.topic
    }

    /// Get current `QoS` value.
    #[must_use]
    #[inline]
    pub const fn qos(&self) -> QoS {
        self.qos
    }
}

/// Topic used in publish packet.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PubTopic(String);

impl PubTopic {
    /// Create a new publish topic.
    ///
    /// # Errors
    ///
    /// Returns error if `topic` is invalid.
    pub fn new(topic: &str) -> Result<Self, TopicError> {
        validate_pub_topic(topic)?;
        Ok(Self(topic.to_string()))
    }

    /// Get byte length in packet.
    #[must_use]
    pub fn bytes(&self) -> usize {
        2 + self.0.len()
    }
}

impl AsRef<str> for PubTopic {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl DecodePacket for PubTopic {
    fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
        let len = ba.read_u16()?;
        let s = ba.read_string(len as usize)?;
        validate_pub_topic(&s)?;
        Ok(Self(s))
    }
}

impl EncodePacket for PubTopic {
    fn encode(&self, buf: &mut Vec<u8>) -> Result<usize, EncodeError> {
        #[allow(clippy::cast_possible_truncation)]
        let len = self.0.len() as u16;
        buf.write_u16::<BigEndian>(len)?;
        buf.write_all(self.0.as_bytes())?;
        Ok(self.bytes())
    }
}

/// Topic pattern used in subscribe/unsubscribe packet.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubTopic(String);

impl SubTopic {
    /// Create a new subscription topic.
    ///
    /// # Errors
    ///
    /// Returns error if `topic` pattern is invalid.
    pub fn new(topic: &str) -> Result<Self, TopicError> {
        validate_sub_topic(topic)?;
        Ok(Self(topic.to_string()))
    }

    /// Get byte length in packet.
    #[must_use]
    pub fn bytes(&self) -> usize {
        2 + self.0.len()
    }
}

impl AsRef<str> for SubTopic {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl DecodePacket for SubTopic {
    fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
        let len = ba.read_u16()?;
        let s = ba.read_string(len as usize)?;
        validate_sub_topic(&s)?;
        Ok(Self(s))
    }
}

impl EncodePacket for SubTopic {
    fn encode(&self, buf: &mut Vec<u8>) -> Result<usize, EncodeError> {
        #[allow(clippy::cast_possible_truncation)]
        let len = self.0.len() as u16;
        buf.write_u16::<BigEndian>(len)?;
        buf.write_all(self.0.as_bytes())?;
        Ok(self.bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse() {
        let t_sys = Topic::parse("$SYS/uptime");
        assert!(t_sys.is_ok());
    }

    #[test]
    fn test_topic_match() {
        let t_sys = Topic::parse("$SYS");
        assert!(t_sys.is_ok());
        //let t_sys = t_sys.unwrap();
        //let t_any = Topic::parse("#").unwrap();
        // FIXME(Shaohua):
        //assert!(t_any.is_match(t_sys.str()));

        let t_dev = Topic::parse("dev/#").unwrap();
        assert!(t_dev.is_match("dev/cpu/0"));
    }
}