bparse/
pattern.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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// The Clone & Copy super traits allow patterns to be re-used even when a function returns `impl Pattern`
/// Expresses that the implementing type may be used to match part of a slice of bytes.
pub trait Pattern: Clone + Copy {
    /// Evaluates the pattern against a slice of bytes.
    /// If the pattern matches, the length of matching bytes should be returned.
    /// Otherwise, `None` should be returned.
    ///
    /// It is assumed that the pattern begins matching from the beining of the slice.
    fn eval(&self, input: &[u8]) -> Option<usize>;

    /// Returns a new pattern that will match if `self` and `other` match in sequence.
    ///
    /// ```
    /// use bparse::Pattern;
    ///
    /// let pattern = "a".then("b");
    /// assert_eq!(pattern.eval(b"abc"), Some(2));
    /// ```
    fn then<P>(self, other: P) -> Sequence<Self, P>
    where
        Self: Sized,
        P: Pattern,
    {
        Sequence {
            pat1: self,
            pat2: other,
        }
    }

    /// Returns a new pattern that will match if both `self` and `other` match.
    ///
    /// Unlike [`Pattern::then`], `self` and `other` are evaluated against the same input.
    ///
    /// ```
    /// use bparse::{Pattern, hex, alpha};
    ///
    /// let pattern = hex().and(alpha());
    /// assert_eq!(pattern.eval(b"a"), Some(1));
    /// assert_eq!(pattern.eval(b"3"), None);
    /// ```
    fn and<P>(self, other: P) -> Composition<Self, P>
    where
        Self: Sized,
        P: Pattern,
    {
        Composition {
            pat1: self,
            pat2: other,
        }
    }

    /// Returns a new pattern that will match if either `self` or `other` match.
    ///
    /// ```
    /// use bparse::Pattern;
    ///
    /// let pattern = "a".or("b");
    /// assert_eq!(pattern.eval(b"ba"), Some(1));
    /// ```
    fn or<P>(self, other: P) -> Choice<Self, P>
    where
        Self: Sized,
        P: Pattern,
    {
        Choice {
            pat1: self,
            pat2: other,
        }
    }
}

impl<T> Pattern for &T
where
    T: Pattern,
{
    fn eval(&self, input: &[u8]) -> Option<usize> {
        (*self).eval(input)
    }
}

/// See [`Pattern::or`]
#[derive(Clone, Copy, Debug)]
pub struct Choice<C1, C2> {
    pat1: C1,
    pat2: C2,
}

impl<P1, P2> Pattern for Choice<P1, P2>
where
    P1: Pattern,
    P2: Pattern,
{
    fn eval(&self, input: &[u8]) -> Option<usize> {
        match self.pat1.eval(input) {
            Some(res) => Some(res),
            None => self.pat2.eval(input),
        }
    }
}

/// See [`Pattern::then`]
#[derive(Clone, Copy, Debug)]
pub struct Sequence<P1, P2> {
    pat1: P1,
    pat2: P2,
}

impl<P1, P2> Pattern for Sequence<P1, P2>
where
    P1: Pattern,
    P2: Pattern,
{
    fn eval(&self, input: &[u8]) -> Option<usize> {
        if let Some(a) = self.pat1.eval(input) {
            if let Some(b) = self.pat2.eval(&input[a..]) {
                return Some(a + b);
            }
        }
        None
    }
}

/// See [`Pattern::and`]
#[derive(Debug, Clone, Copy)]
pub struct Composition<P1, P2> {
    pat1: P1,
    pat2: P2,
}

impl<P1, P2> Pattern for Composition<P1, P2>
where
    P1: Pattern,
    P2: Pattern,
{
    fn eval(&self, input: &[u8]) -> Option<usize> {
        if let Some(a) = self.pat1.eval(input) {
            if let Some(b) = self.pat2.eval(input) {
                return Some(std::cmp::max(a, b));
            }
        }
        None
    }
}

/// Returns a pattern that will match any single byte in the input
///
/// ```
/// use bparse::{Pattern, byte};
///
/// assert_eq!(byte().eval(&[1, 2, 3]), Some(1));
/// ```
///
pub fn byte() -> SingleByte {
    SingleByte
}

/// See [`byte`]
#[derive(Debug, Clone, Copy)]
pub struct SingleByte;

impl Pattern for SingleByte {
    fn eval(&self, input: &[u8]) -> Option<usize> {
        if input.is_empty() {
            return None;
        }

        Some(1)
    }
}

/// Returns a pattern that will match `slice` if it occurs at the start of the input.
///
/// ```
/// use bparse::{Pattern, bytes};
///
/// let pattern = bytes(&[1]);
/// assert_eq!(pattern.eval(&[1, 2, 3]), Some(1));
/// ```
pub fn bytes(slice: &[u8]) -> ByteSlice {
    ByteSlice(slice)
}

/// Returns a pattern that will match the string slice `s` at the start of the input.
///
/// ```
/// use bparse::{Pattern, utf8};
///
/// let pattern = utf8("he");
/// assert_eq!(pattern.eval(b"hello"), Some(2));
/// ```
///
/// As a convenience, the `Pattern` trait is implemented for string slices with the same effect:
///
/// ```
/// use bparse::Pattern;
///
/// assert_eq!("he".eval(b"hello"), Some(2));
/// ```
pub fn utf8(s: &str) -> ByteSlice {
    ByteSlice(s.as_bytes())
}

impl Pattern for &str {
    fn eval(&self, input: &[u8]) -> Option<usize> {
        utf8(self).eval(input)
    }
}

/// See [`bytes`]
#[derive(Debug, Clone, Copy)]
pub struct ByteSlice<'p>(&'p [u8]);

impl Pattern for ByteSlice<'_> {
    fn eval(&self, input: &[u8]) -> Option<usize> {
        if self.0.len() > input.len() {
            return None;
        }

        for (i, byte) in self.0.iter().enumerate() {
            if &input[i] != byte {
                return None;
            }
        }

        Some(self.0.len())
    }
}

/// Returns a pattern that will match any byte in the closed interval `[lo, hi]`
///
/// ```
/// use bparse::{Pattern, range};
///
/// let pattern = range(b'a', b'z');
/// assert_eq!(pattern.eval(b"b"), Some(1));
/// ```
pub fn range(lo: u8, hi: u8) -> ByteRange {
    ByteRange(lo, hi)
}

/// See [`range()`]
#[derive(Debug, Clone, Copy)]
pub struct ByteRange(u8, u8);

impl Pattern for ByteRange {
    fn eval(&self, input: &[u8]) -> Option<usize> {
        let first = *input.first()?;

        if first >= self.0 && first <= self.1 {
            return Some(1);
        }

        None
    }
}

/// Returns a pattern that will match any ascii digit at the start of the input
///
/// ```
/// use bparse::{Pattern, digit};
///
/// assert_eq!(digit().eval(b"a"), None);
/// assert_eq!(digit().eval(b"8"), Some(1));
/// ```
pub fn digit() -> LookupTable {
    oneof(b"0123456789")
}

/// Returns a pattern that will match any ascii letter at the start of the input
///
/// ```
/// use bparse::{Pattern, alpha};
///
/// assert_eq!(alpha().eval(b"1"), None);
/// assert_eq!(alpha().eval(b"a"), Some(1));
/// ```
pub fn alpha() -> LookupTable {
    oneof(b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
}

/// Returns a pattern that will match any hexadecimal character at the start of the input
///
/// ```
/// use bparse::{Pattern, hex};
///
/// assert_eq!(hex().eval(b"z"), None);
/// assert_eq!(hex().eval(b"f"), Some(1));
/// ```
pub fn hex() -> Choice<LookupTable, LookupTable> {
    oneof(b"abcdefABCDEF").or(digit())
}

/// Returns a pattern that will match any byte in `bytes` at the start of the input
///
/// ```
/// use bparse::{Pattern, oneof};
///
/// let pattern = oneof(b"?!.:");
/// assert_eq!(pattern.eval(b"hi"), None);
/// assert_eq!(pattern.eval(b"!!"), Some(1));
/// assert_eq!(pattern.eval(b":"), Some(1));
/// ```
pub fn oneof(bytes: &[u8]) -> LookupTable {
    let mut set: [bool; 256] = [false; 256];

    let mut i = 0;
    while i < bytes.len() {
        set[bytes[i] as usize] = true;
        i += 1;
    }

    LookupTable(set)
}

/// Inverse of [`oneof`].
pub fn noneof(bytes: &[u8]) -> LookupTable {
    let mut set = oneof(bytes).0;
    let mut i = 0;
    while i < set.len() {
        set[i] = !set[i];
        i += 1;
    }

    LookupTable(set)
}

/// See [`oneof`]
#[derive(Debug, Clone, Copy)]
pub struct LookupTable([bool; 256]);

impl Pattern for LookupTable {
    fn eval<'i>(&self, input: &[u8]) -> Option<usize> {
        let first = *input.first()?;

        if self.0[first as usize] {
            return Some(1);
        }
        None
    }
}

/// Returns a new pattern that as many repetitions as possible of the given `pattern`, including 0.
///
///
/// ```
/// use bparse::{Pattern, any};
///
/// assert_eq!(any("a").eval(b"aaa"), Some(3));
/// assert_eq!(any("a").eval(b"aa"), Some(2));
/// assert_eq!(any("a").eval(b""), Some(0));
/// ```
pub fn any<P: Pattern>(pattern: P) -> Repetition<P> {
    Repetition {
        lo: 0,
        hi: None,
        pattern,
    }
}

/// Returns a new pattern that matches at least `n` repetitions of `pattern`.
///
/// ```
/// use bparse::{Pattern, at_least};
///
/// assert_eq!(at_least(2, "a").eval(b"a"), None);
/// assert_eq!(at_least(2, "a").eval(b"aaa"), Some(3));
/// ```
pub fn at_least<P: Pattern>(n: usize, pattern: P) -> Repetition<P> {
    Repetition {
        lo: n,
        hi: None,
        pattern,
    }
}

/// Returns a new pattern that matches at most `n` repetitions of `pattern`.
///
/// ```
/// use bparse::{Pattern, at_most};
///
/// assert_eq!(at_most(2, "b").eval(b"b"), Some(1));
/// assert_eq!(at_most(2, "b").eval(b"bbbb"), Some(2));
/// assert_eq!(at_most(2, "b").eval(b"aa"), Some(0));
/// ```
pub fn at_most<P: Pattern>(n: usize, pattern: P) -> Repetition<P> {
    Repetition {
        lo: 0,
        hi: Some(n),
        pattern,
    }
}

/// Returns a new pattern that matches 0 or 1 repetitions of `pattern`
///
/// This implies the new pattern always matches the input.
///
/// ```
/// use bparse::{Pattern, optional};
///
/// assert_eq!(optional("a").eval(b"b"), Some(0));
/// assert_eq!(optional("a").eval(b"a"), Some(1));
/// ```
pub fn optional<P: Pattern>(pattern: P) -> Repetition<P> {
    Repetition {
        lo: 0,
        hi: Some(1),
        pattern,
    }
}

/// Returns a new pattern that matches exactly `n` repetitions of `pattern`.
///
/// ```
/// use bparse::{Pattern, count};
///
/// assert_eq!(count(2, "z").eval(b"zzz"), Some(2));
/// assert_eq!(count(2, "z").eval(b"z"), None);
/// ```
pub fn count<P: Pattern>(n: usize, pattern: P) -> Repetition<P> {
    Repetition {
        lo: n,
        hi: Some(n),
        pattern,
    }
}

/// Returns a new pattern that matches between `lo` and `hi` repetitions of `pattern`.
///
/// Both bounds are inclusive.
pub fn between<P: Pattern>(lo: usize, hi: usize, pattern: P) -> Repetition<P> {
    Repetition {
        lo,
        hi: Some(hi),
        pattern,
    }
}

/// Exppresses pattern repetition.
/// Many patterns (e.g. [`between`], [`optional`], [`at_least`]) are expressed in terms of this pattern.
#[derive(Debug, Clone, Copy)]
pub struct Repetition<P> {
    pattern: P,
    lo: usize,
    hi: Option<usize>,
}

impl<P> Pattern for Repetition<P>
where
    P: Pattern,
{
    fn eval<'i>(&self, input: &[u8]) -> Option<usize> {
        let mut match_count = 0;
        let mut offset = 0;

        if let Some(upper_bound) = self.hi {
            assert!(
                upper_bound >= self.lo,
                "upper bound should be greater than or equal to the lower bound"
            );
        };

        loop {
            // We hit the upper bound of pattern repetition
            if let Some(upper_bound) = self.hi {
                if match_count == upper_bound {
                    return Some(offset);
                }
            };

            let Some(value) = self.pattern.eval(&input[offset..]) else {
                if match_count < self.lo {
                    return None;
                }
                return Some(offset);
            };

            match_count += 1;
            offset += value;
        }
    }
}

/// Returns a new pattern that matches only if `pattern` does not match
///
/// This pattern always matches exactly one byte if the underlyuing pattern did not match.
/// That is, it will always return  `Some(1)` if the inner pattern does not match.
pub fn not<P: Pattern>(pattern: P) -> Not<P> {
    Not(pattern)
}

/// See [`not`]
#[derive(Debug, Clone, Copy)]
pub struct Not<P>(P);

impl<P> Pattern for Not<P>
where
    P: Pattern,
{
    fn eval<'i>(&self, input: &[u8]) -> Option<usize> {
        if self.0.eval(input).is_some() {
            return None;
        }

        Some(1)
    }
}

/// Returns a pattern that matches if the input is empty.
///
/// ```
/// use bparse::{Pattern, end};
///
/// assert_eq!(end().eval(b"a"), None);
/// assert_eq!(end().eval(b""), Some(0));
/// ```
pub fn end() -> End {
    End
}

/// See [`end`]
#[derive(Debug, Clone, Copy)]
pub struct End;

impl Pattern for End {
    fn eval(&self, input: &[u8]) -> Option<usize> {
        if input.is_empty() {
            return Some(0);
        }
        None
    }
}

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

    #[test]
    fn match_bytes() {
        assert_eq!("".eval(b""), Some(0));
        assert_eq!("".eval(b"a1b2"), Some(0));
        assert_eq!("a".eval(b"a1"), Some(1));
        assert_eq!("a1b".eval(b"a1"), None);
        assert_eq!("١".eval(b"\xd9\xa1"), Some(2));
    }

    #[test]
    fn match_range() {
        assert_eq!(range(b'a', b'z').eval(b"d"), Some(1));
        assert_eq!(range(b'a', b'z').eval(b"0"), None);
    }

    #[test]
    fn match_oneof_noneof() {
        assert_eq!(oneof(b"abc").eval(b"a"), Some(1));
        assert_eq!(noneof(b"abc").eval(b"1"), Some(1));
        assert_eq!(oneof(b"abc").eval(b"123"), None);
    }

    #[test]
    fn match_repetition() {
        assert_eq!(between(0, 0, "a").eval(b"aabb"), Some(0));
        assert_eq!(between(1, 1, "a").eval(b"aabb"), Some(1));
        assert_eq!(between(1, 2, "a").eval(b"aabb"), Some(2));
        assert_eq!(between(1, 10, "a").eval(b"aabb"), Some(2));

        assert_eq!(at_least(0, "a").eval(b"aaaab"), Some(4));
        assert_eq!(at_least(4, "a").eval(b"aaaab"), Some(4));
        assert_eq!(at_least(10, "a").eval(b"aaaab"), None);

        assert_eq!(at_most(3, "a").eval(b"bb"), Some(0));
        assert_eq!(at_most(0, "a").eval(b"aaabb"), Some(0));
        assert_eq!(at_most(1, "a").eval(b"aaabb"), Some(1));
        assert_eq!(at_most(10, "a").eval(b"aaabb"), Some(3));

        assert_eq!(optional("a").eval(b"aa"), Some(1));
        assert_eq!(optional("a").eval(b"baa"), Some(0));

        assert_eq!(any("a").eval(b"aaa"), Some(3));
        assert_eq!(any("a").eval(b""), Some(0));
    }

    #[test]
    fn match_negative_lookahead() {
        assert_eq!(not(end()).eval(b"a"), Some(1));
        assert_eq!(not(end()).eval(b""), None);
    }

    #[test]
    fn match_choice() {
        assert_eq!("a".or("b").eval(b"b"), Some(1));
        assert_eq!("a".or("b").eval(b"a"), Some(1));
        assert_eq!("a".or("b").eval(b"c"), None);
    }

    #[test]
    fn match_sequence() {
        assert_eq!("a".then("b").eval(b"ab"), Some(2));
        assert_eq!("a".then("c").eval(b"ab"), None);
        assert_eq!("z".then("b").eval(b"ab"), None);
    }

    #[test]
    fn patterns_are_reusable() {
        let pattern = "a".then("b".or("c"));
        assert_eq!(pattern.eval(b"ac"), Some(2));
        assert_eq!(pattern.eval(b"ab"), Some(2));
    }

    fn mutable_refeence(input: &mut &[u8]) {
        *input = &input[1..]
    }

    #[test]
    fn testmut() {
        let mut input: &[u8] = &[1, 2, 3];
        mutable_refeence(&mut input);
        println!("{:?}", input);
    }
}