mikrotik_rs/protocol/
word.rs

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
use std::{
    fmt::{self, Display, Formatter},
    num::ParseIntError,
    str::Utf8Error,
};

use super::error::WordType;

/// Represents a word in a Mikrotik [`Sentence`].
///
/// Words can be of three types:
/// - A category word, which represents the type of sentence, such as `!done`, `!re`, `!trap`, or `!fatal`.
/// - A tag word, which represents a tag value like `.tag=123`.
/// - An attribute word, which represents a key-value pair like `=name=ether1`.
///
/// The word can be converted into one of these types using the [`TryFrom`] trait.
///
/// # Examples
///
/// ```
/// use mikrotik::command::reader::Word;
///
/// let word = Word::try_from(b"=name=ether1");
/// assert_eq!(word.unwrap().attribute(), Some(("name", Some("ether1"))));
/// ```
#[derive(Debug, PartialEq)]
pub enum Word<'a> {
    /// A category word, such as `!done`, `!re`, `!trap`, or `!fatal`.
    Category(WordCategory),
    /// A tag word, such as `.tag=123`.
    Tag(u16),
    /// An attribute word, such as `=name=ether1`.
    Attribute(WordAttribute<'a>),
    /// An unrecognized word. Usually this is a `!fatal` reason message.
    Message(&'a str),
}

impl Word<'_> {
    /// Returns the category of the word, if it is a category word.
    pub fn category(&self) -> Option<&WordCategory> {
        match self {
            Word::Category(category) => Some(category),
            _ => None,
        }
    }

    /// Returns the tag of the word, if it is a tag word.
    pub fn tag(&self) -> Option<u16> {
        match self {
            Word::Tag(tag) => Some(*tag),
            _ => None,
        }
    }

    /// Returns the attribute of the word, if it is an attribute word.
    pub fn attribute(&self) -> Option<(&str, Option<&str>)> {
        match self {
            Word::Attribute(WordAttribute { key, value }) => Some((*key, *value)),
            _ => None,
        }
    }

    /// Returns the generic word, if it is a generic word.
    /// This is usually a `!fatal` reason message.
    pub fn generic(&self) -> Option<&str> {
        match self {
            Word::Message(generic) => Some(generic),
            _ => None,
        }
    }

    /// Returns the type of the Word.
    pub fn word_type(&self) -> WordType {
        match self {
            Word::Category(_) => WordType::Category,
            Word::Tag(_) => WordType::Tag,
            Word::Attribute(_) => WordType::Attribute,
            Word::Message(_) => WordType::Message,
        }
    }
}

impl Display for Word<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Word::Category(category) => write!(f, "{}", category),
            Word::Tag(tag) => write!(f, ".tag={}", tag),
            Word::Attribute(WordAttribute { key, value }) => {
                write!(f, "={}={}", key, value.unwrap_or(""))
            }
            Word::Message(generic) => write!(f, "{}", generic),
        }
    }
}

impl<'a> TryFrom<&'a [u8]> for Word<'a> {
    type Error = WordError;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        let s = std::str::from_utf8(value)?;

        // Parse tag
        if let Some(stripped) = s.strip_prefix(".tag=") {
            let tag = stripped.parse::<u16>()?;
            return Ok(Word::Tag(tag));
        }

        // Parse attribute pair
        if s.starts_with('=') {
            let attribute = WordAttribute::try_from(s)?;
            return Ok(Word::Attribute(attribute));
        }

        // Parse category
        match WordCategory::try_from(s) {
            Ok(category) => Ok(Word::Category(category)),
            // If the word is not a category, tag, or attribute, it's likely a generic word
            Err(_) => Ok(Word::Message(s)),
        }
    }
}

/// Represents the type of of a response.
/// The type is derived from the first [`Word`] in a [`Sentence`].
/// Valid types are `!done`, `!re`, `!trap`, and `!fatal`.
#[derive(Debug, Clone, PartialEq)]
pub enum WordCategory {
    /// Represents a `!done` response.
    Done,
    /// Represents a `!re` response.
    Reply,
    /// Represents a `!trap` response.
    Trap,
    /// Represents a `!fatal` response.
    Fatal,
}

impl TryFrom<&str> for WordCategory {
    type Error = ();

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "!done" => Ok(Self::Done),
            "!re" => Ok(Self::Reply),
            "!trap" => Ok(Self::Trap),
            "!fatal" => Ok(Self::Fatal),
            _ => Err(()),
        }
    }
}

impl Display for WordCategory {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            WordCategory::Done => write!(f, "!done"),
            WordCategory::Reply => write!(f, "!re"),
            WordCategory::Trap => write!(f, "!trap"),
            WordCategory::Fatal => write!(f, "!fatal"),
        }
    }
}

/// Represents a key-value pair in a Mikrotik [`Sentence`].
#[derive(Debug, PartialEq)]
pub struct WordAttribute<'a> {
    /// The key of the attribute.
    pub key: &'a str,
    /// The value of the attribute, if present.
    pub value: Option<&'a str>,
}

impl<'a> TryFrom<&'a str> for WordAttribute<'a> {
    type Error = WordError;

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        let mut parts = value
            .strip_prefix('=')
            .ok_or(WordError::Attribute)?
            .splitn(2, '=');
        let key = parts.next().ok_or(WordError::Attribute)?;
        let value = parts.next();
        Ok(Self { key, value })
    }
}

/// Represents an error that occurred while parsing a [`Word`].
#[derive(Debug, PartialEq)]
pub enum WordError {
    /// The word is not a valid UTF-8 string.
    Utf8(Utf8Error),
    /// The word is a tag, but the tag value is invalid.
    Tag(ParseIntError),
    /// The word is an attribute pair, but the format is invalid.
    Attribute,
}

impl From<Utf8Error> for WordError {
    fn from(e: Utf8Error) -> Self {
        Self::Utf8(e)
    }
}

impl From<ParseIntError> for WordError {
    fn from(e: ParseIntError) -> Self {
        Self::Tag(e)
    }
}

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

    impl<'a> From<(&'a str, Option<&'a str>)> for WordAttribute<'a> {
        fn from(value: (&'a str, Option<&'a str>)) -> Self {
            Self {
                key: value.0,
                value: value.1,
            }
        }
    }

    #[test]
    fn test_word_parsing() {
        // Test cases for `Word::try_from` function
        assert_eq!(
            Word::try_from(b"!done".as_ref()).unwrap(),
            Word::Category(WordCategory::Done)
        );

        assert_eq!(
            Word::try_from(b".tag=123".as_ref()).unwrap(),
            Word::Tag(123)
        );

        assert_eq!(
            Word::try_from(b"=name=ether1".as_ref()).unwrap(),
            Word::Attribute(("name", Some("ether1")).into())
        );

        assert_eq!(
            Word::try_from(b"!fatal".as_ref()).unwrap(),
            Word::Category(WordCategory::Fatal)
        );

        assert_eq!(
            Word::try_from(b"unknownword".as_ref()).unwrap(),
            Word::Message("unknownword")
        );

        // Invalid tag value
        assert!(Word::try_from(b".tag=notanumber".as_ref()).is_err());

        // Invalid UTF-8 sequence
        assert!(Word::try_from(b"\xFF\xFF".as_ref()).is_err());
    }

    #[test]
    fn test_display_for_word() {
        // Test cases for `Display` implementation for `Word`
        let word = Word::Category(WordCategory::Done);
        assert_eq!(format!("{}", word), "!done");

        let word = Word::Tag(123);
        assert_eq!(format!("{}", word), ".tag=123");

        let word = Word::Attribute(("name", Some("ether1")).into());
        assert_eq!(format!("{}", word), "=name=ether1");

        let word = Word::Message("unknownword");
        assert_eq!(format!("{}", word), "unknownword");
    }
}