neotoma 0.1.1

A flexible, cached parser combinator framework for Rust.
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Literal string and byte sequence parsing.
//!
//! This module provides the [`Literal`] parser for matching exact byte sequences or strings.
//! It includes memory optimization that can store either
//! static string literals (zero allocation) or runtime-allocated byte sequences.
//!
//! The parser supports both string and byte array inputs, with convenient constructors
//! for compile-time constants that avoid heap allocation.

use std::{
    any::TypeId,
    hash::{DefaultHasher, Hash, Hasher},
};

use crate::{
    cache::ParsingCache,
    parser::{Parsable, Parser, Source},
    result::{Error, ParseResult},
};

/// A parser that matches a fixed sequence of bytes exactly.
///
/// The Literal parser consumes bytes from the input if and only if they match
/// the expected byte sequence exactly. It succeeds and returns the matched bytes
/// as a `Vec<u8>`, or fails if any byte doesn't match.
///
/// # Examples
///
/// ```rust
/// use neotoma::{literal::Literal, parser::{parse, Source}};
/// use std::io::Cursor;
///
/// // Match the exact byte sequence [72, 101, 108, 108, 111] ("Hello")
/// let hello_bytes = Literal::from_bytes(b"Hello");
/// let mut input = Cursor::new(b"Hello world");
/// let mut source = Source::new(input);
/// let result = parse(hello_bytes, &mut source).unwrap();
/// assert_eq!(result, b"Hello".as_slice().into());
///
/// // Match the string "world" as UTF-8 bytes
/// let world = Literal::from_str("world");
/// let mut input = Cursor::new(b"world");
/// let mut source = Source::new(input);
/// let result = parse(world, &mut source).unwrap();
/// assert_eq!(result, b"world".as_slice().into());
///
/// // Match a specific protocol header
/// let header = Literal::from_bytes(&[0x89, 0x50, 0x4E, 0x47]); // PNG signature
/// let mut input = Cursor::new(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]);
/// let mut source = Source::new(input);
/// let result = parse(header, &mut source).unwrap();
/// assert_eq!(result, [0x89, 0x50, 0x4E, 0x47].as_slice().into());
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Literal {
    expected: LiteralData,
}

#[derive(Clone, PartialEq, Eq)]
enum LiteralData {
    Owned(Box<[u8]>),
    Static(&'static [u8]),
}

impl Literal {
    /// Create a new Literal parser from a byte slice.
    ///
    /// The parser will match the exact sequence of bytes provided.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::{literal::Literal, parser::{parse, Source}};
    /// use std::io::Cursor;
    ///
    /// let parser = Literal::from_bytes(b"HTTP/1.1");
    /// let mut input = Cursor::new(b"HTTP/1.1 200 OK");
    /// let mut source = Source::new(input);
    /// let result = parse(parser, &mut source).unwrap();
    /// // Matches exactly the bytes [72, 84, 84, 80, 47, 49, 46, 49]
    /// assert_eq!(result, b"HTTP/1.1".as_slice().into());
    /// ```
    pub fn from_bytes(bytes: &[u8]) -> Self {
        Self {
            expected: LiteralData::Owned(bytes.into()),
        }
    }

    /// Create a new Literal parser from a string reference.
    ///
    /// The string will be converted to UTF-8 bytes for matching.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::{literal::Literal, parser::{parse, Source}};
    /// use std::io::Cursor;
    ///
    /// let parser = Literal::from_str("Hello, world!");
    /// let mut input = Cursor::new(b"Hello, world! How are you?");
    /// let mut source = Source::new(input);
    /// let result = parse(parser, &mut source).unwrap();
    /// // Matches the UTF-8 byte encoding of "Hello, world!"
    /// assert_eq!(result, b"Hello, world!".as_slice().into());
    /// ```
    // This is consistent with our other constructor names, and nothing like what FromStr is meant for.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str<S: AsRef<str>>(s: S) -> Self {
        Self {
            expected: LiteralData::Owned(s.as_ref().as_bytes().into()),
        }
    }

    /// Create a new Literal parser from a compile-time string literal.
    ///
    /// This is a const function that can be used to create Literal parsers
    /// at compile time for string literals.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::{literal::Literal, parser::{parse, Source}};
    /// use std::io::Cursor;
    ///
    /// const HELLO_PARSER: Literal = Literal::from_str_const("hello");
    /// let mut input = Cursor::new(b"hello world");
    /// let mut source = Source::new(input);
    /// let result = parse(HELLO_PARSER, &mut source).unwrap();
    /// assert_eq!(result, b"hello".as_slice().into());
    /// ```
    pub const fn from_str_const(s: &'static str) -> Self {
        Self {
            expected: LiteralData::Static(s.as_bytes()),
        }
    }

    /// Create a new Literal parser from compile-time byte slice.
    ///
    /// This is a const function that can be used to create Literal parsers
    /// at compile time for byte literals.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::{literal::Literal, parser::{parse, Source}};
    /// use std::io::Cursor;
    ///
    /// const PNG_HEADER: Literal = Literal::from_bytes_const(&[0x89, 0x50, 0x4E, 0x47]);
    /// let mut input = Cursor::new(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]);
    /// let mut source = Source::new(input);
    /// let result = parse(PNG_HEADER, &mut source).unwrap();
    /// assert_eq!(result, [0x89, 0x50, 0x4E, 0x47].as_slice().into());
    /// ```
    pub const fn from_bytes_const(bytes: &'static [u8]) -> Self {
        Self {
            expected: LiteralData::Static(bytes),
        }
    }

    /// Get the expected byte sequence.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::literal::Literal;
    ///
    /// let parser = Literal::from_str("test");
    /// assert_eq!(parser.bytes(), b"test");
    /// ```
    pub fn bytes(&self) -> &[u8] {
        match &self.expected {
            LiteralData::Owned(bytes) => bytes,
            LiteralData::Static(bytes) => bytes,
        }
    }

    /// Get the length of the expected sequence.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::literal::Literal;
    ///
    /// let parser = Literal::from_str("hello");
    /// assert_eq!(parser.len(), 5);
    /// ```
    pub fn len(&self) -> usize {
        self.bytes().len()
    }

    /// Check if the literal is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::literal::Literal;
    ///
    /// let empty = Literal::from_str("");
    /// assert!(empty.is_empty());
    ///
    /// let not_empty = Literal::from_str("a");
    /// assert!(!not_empty.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.bytes().is_empty()
    }
}

impl<Ctx> Parser<Ctx> for Literal {
    type Output = Box<[u8]>;

    fn id(&self) -> u64 {
        let mut hasher = DefaultHasher::new();
        TypeId::of::<Self>().hash(&mut hasher);
        self.bytes().hash(&mut hasher);
        hasher.finish()
    }

    fn read<S>(
        &self,
        source: &mut Source<S>,
        _cache: &mut impl ParsingCache,
        _context: &mut Ctx,
    ) -> ParseResult<Self::Output>
    where
        S: Parsable,
    {
        // Handle empty literal case
        if self.is_empty() {
            return Ok(Box::new([]));
        }

        let expected_bytes = self.bytes();

        // Try to read the expected number of bytes
        match source.peek(expected_bytes.len()) {
            Ok(bytes) => {
                // Check if the bytes match exactly
                if bytes == expected_bytes {
                    // Consume the matched bytes
                    source.advance(expected_bytes.len());
                    Ok(expected_bytes.into())
                } else {
                    // Bytes don't match
                    Err(Error::NoMatch)
                }
            }
            Err(Error::NoMatch) => {
                // Not enough bytes available (EOF or insufficient input)
                Err(Error::NoMatch)
            }
            Err(err) => Err(err),
        }
    }
}

// Convenience trait implementations for easier construction
impl From<&[u8]> for Literal {
    fn from(bytes: &[u8]) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<&str> for Literal {
    fn from(s: &str) -> Self {
        Self::from_str(s)
    }
}

impl From<String> for Literal {
    fn from(s: String) -> Self {
        Self::from_str(s)
    }
}

impl From<Vec<u8>> for Literal {
    fn from(bytes: Vec<u8>) -> Self {
        Self {
            expected: LiteralData::Owned(bytes.into_boxed_slice()),
        }
    }
}

impl From<Box<[u8]>> for Literal {
    fn from(bytes: Box<[u8]>) -> Self {
        Self {
            expected: LiteralData::Owned(bytes),
        }
    }
}

// Display and Debug implementations for better developer experience
impl std::fmt::Debug for Literal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Try to display as string if it's valid UTF-8, otherwise as bytes
        let bytes = self.bytes();
        match std::str::from_utf8(bytes) {
            Ok(s) => write!(f, "Literal::from_str({s:?})"),
            Err(_) => write!(f, "Literal::from_bytes({bytes:?})"),
        }
    }
}

impl std::fmt::Display for Literal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let bytes = self.bytes();
        match std::str::from_utf8(bytes) {
            Ok(s) => write!(f, "\"{s}\""),
            Err(_) => write!(f, "{bytes:?}"),
        }
    }
}

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

    #[test]
    fn test_literal_from_str() {
        let literal = Literal::from_str("hello");
        assert_eq!(literal.bytes(), b"hello");
        assert_eq!(literal.len(), 5);
        assert!(!literal.is_empty());
    }

    #[test]
    fn test_literal_from_bytes() {
        let literal = Literal::from_bytes(b"\x89PNG");
        assert_eq!(literal.bytes(), &[0x89, 0x50, 0x4E, 0x47]);
        assert_eq!(literal.len(), 4);
    }

    #[test]
    fn test_empty_literal() {
        let literal = Literal::from_str("");
        assert!(literal.is_empty());
        assert_eq!(literal.len(), 0);
    }

    #[test]
    fn test_literal_conversion_traits() {
        let _from_str: Literal = "test".into();
        let _from_string: Literal = String::from("test").into();
        let _from_bytes: Literal = b"test".as_slice().into();
        let _from_vec: Literal = vec![116, 101, 115, 116].into();
    }

    #[test]
    fn test_literal_parsing_success() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("hello");
        let mut input = Cursor::new(b"hello world");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"hello".as_slice().into());
    }

    #[test]
    fn test_literal_parsing_failure() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("hello");
        let mut input = Cursor::new(b"world");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source);
        assert!(matches!(result, Err(Error::NoMatch)));
    }

    #[test]
    fn test_literal_parsing_partial_match() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("hello");
        let mut input = Cursor::new(b"hell");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source);
        assert!(matches!(result, Err(Error::NoMatch)));
    }

    #[test]
    fn test_literal_parsing_prefix_match() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("he");
        let mut input = Cursor::new(b"hello");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"he".as_slice().into());
    }

    #[test]
    fn test_literal_parsing_empty() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("");
        let mut input = Cursor::new(b"anything");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"".as_slice().into());
    }

    #[test]
    fn test_literal_parsing_empty_input() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("hello");
        let mut input = Cursor::new(b"");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source);
        assert!(matches!(result, Err(Error::NoMatch)));
    }

    #[test]
    fn test_literal_parsing_empty_on_empty() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("");
        let mut input = Cursor::new(b"");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"".as_slice().into());
    }

    #[test]
    fn test_literal_parsing_binary_data() {
        use crate::parser::parse;
        use std::io::Cursor;

        let png_header = Literal::from_bytes(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
        let mut input = Cursor::new(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00]);
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(png_header, &mut source).unwrap();
        assert_eq!(
            result,
            [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
                .as_slice()
                .into()
        );
    }

    #[test]
    fn test_literal_parsing_unicode() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("héllo"); // Contains accented character
        let input_bytes = "héllo world".as_bytes();
        let mut input = Cursor::new(input_bytes);
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, "héllo".as_bytes().into());
    }

    #[test]
    fn test_literal_clone() {
        let literal1 = Literal::from_str("test");
        let literal2 = literal1.clone();

        assert_eq!(literal1.bytes(), literal2.bytes());
        assert_eq!(literal1.len(), literal2.len());
    }

    #[test]
    fn test_literal_equality() {
        let literal1 = Literal::from_str("test");
        let literal2 = Literal::from_str("test");
        let literal3 = Literal::from_str("different");
        let literal4 = Literal::from_bytes(b"test");

        assert_eq!(literal1, literal2);
        assert_eq!(literal1, literal4); // String and bytes should be equal if same content
        assert_ne!(literal1, literal3);
    }

    #[test]
    fn test_literal_debug_format() {
        let string_literal = Literal::from_str("hello");
        let debug_str = format!("{string_literal:?}");
        assert_eq!(debug_str, "Literal::from_str(\"hello\")");

        let binary_literal = Literal::from_bytes(&[0x89, 0x50]);
        let debug_str = format!("{binary_literal:?}");
        assert_eq!(debug_str, "Literal::from_bytes([137, 80])");
    }

    #[test]
    fn test_literal_display_format() {
        let string_literal = Literal::from_str("hello");
        let display_str = format!("{string_literal}");
        assert_eq!(display_str, "\"hello\"");

        let binary_literal = Literal::from_bytes(&[0x89, 0x50]);
        let display_str = format!("{binary_literal}");
        assert_eq!(display_str, "[137, 80]");
    }

    #[test]
    fn test_literal_large_input() {
        use crate::parser::parse;
        use std::io::Cursor;

        let large_string = "x".repeat(1000);
        let literal = Literal::from_str(&large_string);
        let input_data = format!("{large_string}more");
        let mut input = Cursor::new(input_data.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, large_string.as_bytes().into());
    }

    #[test]
    fn test_literal_from_box() {
        let boxed_bytes: Box<[u8]> = Box::new([1, 2, 3, 4]);
        let literal = Literal::from(boxed_bytes);
        assert_eq!(literal.bytes(), &[1, 2, 3, 4]);
    }

    #[test]
    fn test_literal_single_byte() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_bytes(b"A");
        let mut input = Cursor::new(b"ABCD");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"A".as_slice().into());
    }

    #[test]
    fn test_literal_case_sensitive() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("Hello");
        let mut input = Cursor::new(b"hello");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source);
        assert!(matches!(result, Err(Error::NoMatch)));
    }

    #[test]
    fn test_literal_newlines_and_whitespace() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_str("hello\nworld\t!");
        let mut input = Cursor::new(b"hello\nworld\t!more");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, b"hello\nworld\t!".as_slice().into());
    }

    #[test]
    fn test_literal_null_bytes() {
        use crate::parser::parse;
        use std::io::Cursor;

        let literal = Literal::from_bytes(&[b'a', 0, b'b']);
        let mut input = Cursor::new(&[b'a', 0, b'b', b'c']);
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(literal, &mut source).unwrap();
        assert_eq!(result, [b'a', 0, b'b'].as_slice().into());
    }

    #[test]
    fn test_literal_max_length() {
        let max_bytes = vec![255u8; 10000];
        let literal = Literal::from_bytes(&max_bytes);
        assert_eq!(literal.len(), 10000);
        assert_eq!(literal.bytes(), &max_bytes);
    }
}