const_irc_message_parser 0.3.0

A 0 dependency, no_std, const-only parser for the IRC message 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Methods for detecting, extracting and separating an [`IrcFmtByte`].
//!
//! ## Purpose
//!
//! IRC messages can contain formatting bytes to indicate the application of formatting to text.
//! Both [`IrcFmtByte::Colour`] and [`IrcFmtByte::HexColour`] may have bytes after them that are
//! to be interperated as colours rather than part of the message content.
//! Detecting these bytes allows you to decide what to do when they are encountered.
//! The [specification] indicates where they are likely to be encountered within an [`IrcMsg`](crate::IrcMsg).
//!
//! [specification]: <https://modern.ircdocs.horse/formatting>

/// A part of the input split up.
pub type MsgPart<'input> = &'input [u8];
/// A [`MsgPart`] wrapped in an [`Option`].
pub type OptMsgPart<'input> = Option<MsgPart<'input>>;
/// The contents of foreground and background colours if present.
pub type OptIrcColours<'input> = Option<(MsgPart<'input>, OptMsgPart<'input>)>;

/// A byte that indicates formatting to apply to text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IrcFmtByte {
    /// Toggle bold formatting. [`u8`] value of `2` (byte `\x02`).
    Bold,
    /// Toggle italic formatting. [`u8`] value of `29` (byte `\x1d`).
    Italics,
    /// Toggle underline formatting. [`u8`] value of `31` (byte `\x1f`).
    Underline,
    /// Toggle strikethrough formatting. [`u8`] value of `30` (byte `\x1e`).
    Strikethrough,
    /// Toggle monospace formatting. [`u8`] value of `17` (byte `\x11`).
    Monospace,
    /// Reset or apply foreground/background colours using irc colour codes. [`u8`] value of `3` (byte `\x03`).
    ///
    /// Valid colour codes are `0`-`99`.
    /// `0`-`15` are usually author defined.
    /// `16`-`98` are specified.
    /// `99` indicates a resetting to the default colour.
    /// No colour codes after the colour byte indicates a colour reset.
    /// Background colour cannot be specified without first specifying a foreground colour followed by a comma.
    Colour,
    /// Reset or apply foreground/background colours using hex values. [`u8`] value of `4` (byte `\x04`).
    ///
    /// `6` hexadecimal digits, `2` each representing the red, green and blue values.
    /// No colour codes after the colour byte indicates a colour reset.
    /// Background colour cannot be specified without first specifying a foreground colour followed by a comma.
    HexColour,
    /// Toggle reversing the colour. [`u8`] value of `22` (byte `\x16`).
    ReverseColour,
    /// Reset all formatting to default. [`u8`] value of `15` (byte `\x0f`).
    Reset,
}

impl IrcFmtByte {
    const fn detect(input: u8) -> Option<Self> {
        match input {
            2 => Some(Self::Bold),
            3 => Some(Self::Colour),
            4 => Some(Self::HexColour),
            15 => Some(Self::Reset),
            17 => Some(Self::Monospace),
            22 => Some(Self::ReverseColour),
            29 => Some(Self::Italics),
            30 => Some(Self::Strikethrough),
            31 => Some(Self::Underline),
            _ => None,
        }
    }
    /// Checks whether the `input` contains an [`IrcFmtByte`].
    #[must_use]
    pub const fn contains_irc_formatting(input: &[u8]) -> bool {
        let mut index = 0;
        while index < input.len() {
            if Self::detect(input[index]).is_some() {return true;}
            index += 1;
        }
        false
    }
    /// Returns both the [`IrcFmtByte`] and the `index` it occurs at if present.
    ///
    /// The `nth` parameter is a 0 based index.
    #[must_use]
    pub const fn find_nth_fmt_byte_and_position(input: &[u8], nth: usize) -> Option<(Self, usize)> {
        let (mut index, mut count) = (0, 0);
        while index < input.len() {
            if let Some(fb) = Self::detect(input[index]) {
                if count == nth {return Some((fb, index));}
                count += 1;
            }
            index += 1;
        }
        None
    }
    /// Counts each [`IrcFmtByte`] in `input`.
    ///
    /// The count does not contain the bytes that represent irc colour codes or hex values.
    #[must_use]
    pub const fn count_fmt_bytes(input: &[u8]) -> usize {
        let (mut index, mut count) = (0, 0);
        while index < input.len() {
            if Self::detect(input[index]).is_some() {count += 1;}
            index += 1;
        }
        count
    }
    /// Returns message parts split both sides of the [`IrcFmtByte`] along with the byte and colours if present.
    ///
    /// If `input` is empty it returns `None`.
    ///
    /// Output is split into 4 parts:
    ///
    /// 1 - All bytes before the first [`IrcFmtByte`]. `None` if the first byte is the [`IrcFmtByte`].
    ///
    /// 2 - The [`IrcFmtByte`] if present.
    ///
    /// 3 - The colours specified for [`IrcFmtByte::Colour`] or [`IrcFmtByte::HexColour`] if present.
    ///
    /// 4 - All bytes after the colours if present including further formatting bytes. `None` if the last byte is part of a colour or the [`IrcFmtByte`].
    #[must_use]
    pub const fn split_at_first_fmt_byte(input: &[u8]) -> Option<(OptMsgPart, Option<Self>, OptIrcColours, OptMsgPart)> {
        if input.is_empty() {return None;} // already made sure input is not empty
        if Self::contains_irc_formatting(input) {
            let mut index = 0;
            while index < input.len() {
                if let Some(fb) = Self::detect(input[index]) {
                    let (before, including) = input.split_at(index); // including = 1 or more bytes
                    let before = if before.is_empty() {None} else {Some(before)};
                    if let Some((_, after)) = including.split_first() { // always happens even if after is empty
                        match fb {
                            Self::Bold | Self::Italics | Self::Underline | Self::Strikethrough | Self::Monospace |
                            Self::ReverseColour | Self::Reset => {
                                let after = if after.is_empty() {None} else {Some(after)};
                                return Some((before, Some(fb), None, after));
                            },
                            Self::Colour => {
                                if after.is_empty() {
                                    return Some((before, Some(fb), None, None));
                                } else if let Some(codes) = Self::irc_colour_codes(after) {
                                    match codes {
                                        ColourCodeSize::SingleDigit => {
                                            let (code, after_code) = after.split_at(1);
                                            let after_code = if after_code.is_empty() {None} else {Some(after_code)};
                                            let colours = Some((code, None));
                                            return Some((before, Some(fb), colours, after_code));
                                        },
                                        ColourCodeSize::DoubleDigit => {
                                            let (code, after_code) = after.split_at(2);
                                            let after_code = if after_code.is_empty() {None} else {Some(after_code)};
                                            let colours = Some((code, None));
                                            return Some((before, Some(fb), colours, after_code));
                                        },
                                        ColourCodeSize::SingleAndSingle => {
                                            let (foreground, comma_onwards) = after.split_at(1);
                                            let (_, after_comma) = comma_onwards.split_at(1);
                                            let (background, after_codes) = after_comma.split_at(1);
                                            let after_codes = if after_codes.is_empty() {None} else {Some(after_codes)};
                                            let colours = Some((foreground, Some(background)));
                                            return Some((before, Some(fb), colours, after_codes));
                                        },
                                        ColourCodeSize::SingleAndDouble => {
                                            let (foreground, comma_onwards) = after.split_at(1);
                                            let (_, after_comma) = comma_onwards.split_at(1);
                                            let (background, after_codes) = after_comma.split_at(2);
                                            let after_codes = if after_codes.is_empty() {None} else {Some(after_codes)};
                                            let colours = Some((foreground, Some(background)));
                                            return Some((before, Some(fb), colours, after_codes));
                                        },
                                        ColourCodeSize::DoubleAndSingle => {
                                            let (foreground, comma_onwards) = after.split_at(2);
                                            let (_, after_comma) = comma_onwards.split_at(1);
                                            let (background, after_codes) = after_comma.split_at(1);
                                            let after_codes = if after_codes.is_empty() {None} else {Some(after_codes)};
                                            let colours = Some((foreground, Some(background)));
                                            return Some((before, Some(fb), colours, after_codes));
                                        },
                                        ColourCodeSize::DoubleAndDouble => {
                                            let (foreground, comma_onwards) = after.split_at(2);
                                            let (_, after_comma) = comma_onwards.split_at(1);
                                            let (background, after_codes) = after_comma.split_at(2);
                                            let after_codes = if after_codes.is_empty() {None} else {Some(after_codes)};
                                            let colours = Some((foreground, Some(background)));
                                            return Some((before, Some(fb), colours, after_codes));
                                        },
                                    }
                                }
                                return Some((before, Some(fb), None, Some(after)));
                            },
                            Self::HexColour => {
                                if after.is_empty() {
                                    return Some((before, Some(fb), None, None));
                                } else if after.len() > 5 {
                                    let (first_colour, comma_onwards) = after.split_at(6);
                                    if is_hex_colour(first_colour) {
                                        if comma_onwards.len() > 6 {
                                            if let Some((comma, after_comma)) = comma_onwards.split_first() {
                                                if *comma == b',' {
                                                    let (second_colour, onwards) = after_comma.split_at(6);
                                                    if is_hex_colour(second_colour) {
                                                        let onwards = if onwards.is_empty() {None} else {Some(onwards)};
                                                        let colours = Some((first_colour, Some(second_colour)));
                                                        return Some((before, Some(fb), colours, onwards));
                                                    }
                                                }
                                            }
                                        }
                                        let rest = if comma_onwards.is_empty() {None} else {Some(comma_onwards)};
                                        return Some((before, Some(fb), Some((first_colour, None)), rest));
                                    }
                                }
                                return Some((before, Some(fb), None, Some(after)));
                            },
                        }
                    }
                }
                index += 1;
            }
        }
        Some((Some(input), None, None, None))
    }
    const fn irc_colour_codes(input: &[u8]) -> Option<ColourCodeSize> {
        let mut index = 0;
        let (mut foreground_first, mut foreground_second) = (false, false);
        let mut comma = false;
        let (mut background_first, mut background_second) = (false, false);
        while index < input.len() {
            match index {
                0 => if input[index].is_ascii_digit() {foreground_first = true;} else {break;},
                1 => {
                    if input[index].is_ascii_digit() {foreground_second = true;}
                    else if input[index] == b',' {comma = true;}
                    else {break;}
                },
                2 => {
                    if input[index].is_ascii_digit() {background_first = true;}
                    else if input[index] == b',' {comma = true;}
                    else {break;}
                },
                3 => {
                    if input[index].is_ascii_digit() && foreground_first && foreground_second && comma {
                        background_first = true;
                    } else if input[index].is_ascii_digit() && foreground_first && !foreground_second && comma
                    && background_first {background_second = true;
                    } else {break;}
                },
                4 => if input[index].is_ascii_digit() {background_second = true;} else {break;},
                _ => break,
            }
            index += 1;
        }
        match (foreground_first, foreground_second, comma, background_first, background_second) {
            (true, false, true | false, false, false) => Some(ColourCodeSize::SingleDigit),
            (true, true, true | false, false, false) => Some(ColourCodeSize::DoubleDigit),
            (true, false, true, true, false) => Some(ColourCodeSize::SingleAndSingle),
            (true, false, true, true, true) => Some(ColourCodeSize::SingleAndDouble),
            (true, true, true, true, false) => Some(ColourCodeSize::DoubleAndSingle),
            (true, true, true, true, true) => Some(ColourCodeSize::DoubleAndDouble),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ColourCodeSize {
    SingleDigit,
    DoubleDigit,
    SingleAndSingle,
    SingleAndDouble,
    DoubleAndSingle,
    DoubleAndDouble,
}

const fn is_hex_colour(input: &[u8]) -> bool {
    let mut index = 0;
    while index < input.len() {
        if !input[index].is_ascii_hexdigit() {return false;}
        index += 1;
    }
    true
}

#[cfg(test)]
mod const_tests {
    use crate::const_tests::is_identical;
    use super::IrcFmtByte;
    #[test]
    const fn detect_irc_formatting() {
        assert!(IrcFmtByte::contains_irc_formatting(b"Hey \x0366,88wha\x0399t's\x0400ff07,6672f4 u\x0fp!"));
        assert!(!IrcFmtByte::contains_irc_formatting(b"Hey what's up!"));
    }
    #[test]
    const fn count_irc_formatting_bytes() {
        assert!(IrcFmtByte::count_fmt_bytes(b"\x02\x1d\x1f\x1e\x11\x16\x037\x04\x0f") == 9);
    }
    #[test]
    const fn find_nth_fmt_byte() {
        let result = IrcFmtByte::find_nth_fmt_byte_and_position(b"Hey \x0366,88wha\x0399t's\x0400ff07 u\x0fp!", 1);
        assert!(result.is_some());
        if let Some((fb, index)) = result {
            if let IrcFmtByte::Colour = fb {assert!(true);}
            assert!(index == 13);
        }
        assert!(IrcFmtByte::find_nth_fmt_byte_and_position(b"Hey what's up!", 1).is_none());
    }
    #[test]
    const fn splitting_messages() {
        assert!(IrcFmtByte::split_at_first_fmt_byte(&[]).is_none());
        let input = b"Hey what's up!";
        let output = IrcFmtByte::split_at_first_fmt_byte(input);
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(msg) = before {assert!(is_identical(input, msg));}
            assert!(fb.is_none());
            assert!(colours.is_none());
            assert!(after.is_none());
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey wh\x11at's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey wh"));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Monospace = fb {assert!(true);}}
            assert!(colours.is_none());
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"at's up!"));}
        }
    }
    #[test]
    const fn splitting_messages_colours() {
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x037what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"7"));
                assert!(bg.is_none());
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x0377what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"77"));
                assert!(bg.is_none());
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x037,8what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"7"));
                assert!(bg.is_some());
                if let Some(bg) = bg {assert!(is_identical(bg, b"8"));}
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x0376,8what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"76"));
                assert!(bg.is_some());
                if let Some(bg) = bg {assert!(is_identical(bg, b"8"));}
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x0376,88what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"76"));
                assert!(bg.is_some());
                if let Some(bg) = bg {assert!(is_identical(bg, b"88"));}
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x037,88what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"7"));
                assert!(bg.is_some());
                if let Some(bg) = bg {assert!(is_identical(bg, b"88"));}
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x03");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_none());
            assert!(after.is_none());
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x03!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::Colour = fb {assert!(true);}}
            assert!(colours.is_none());
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"!"));}
        }
    }
    #[test]
    const fn splitting_messages_hex() {
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x04787878what's up!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::HexColour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"787878"));
                assert!(bg.is_none());
            }
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"what's up!"));}
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x04787878,ffaabb");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::HexColour = fb {assert!(true);}}
            assert!(colours.is_some());
            if let Some((fg, bg)) = colours {
                assert!(is_identical(fg, b"787878"));
                assert!(bg.is_some());
                if let Some(bg) = bg {assert!(is_identical(bg, b"ffaabb"));}
            }
            assert!(after.is_none());
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x04");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::HexColour = fb {assert!(true);}}
            assert!(colours.is_none());
            assert!(after.is_none());
        }
        let output = IrcFmtByte::split_at_first_fmt_byte(b"Hey \x04!");
        assert!(output.is_some());
        if let Some((before, fb, colours, after)) = output {
            assert!(before.is_some());
            if let Some(before) = before {assert!(is_identical(before, b"Hey "));}
            assert!(fb.is_some());
            if let Some(fb) = fb {if let IrcFmtByte::HexColour = fb {assert!(true);}}
            assert!(colours.is_none());
            assert!(after.is_some());
            if let Some(after) = after {assert!(is_identical(after, b"!"));}
        }
    }
}