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
pub mod byte;

// 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 a slice with elements of type `T`.
pub trait Pattern<T>: Clone + Copy {
    /// Evaluates the pattern against a slice of `T`s.
    /// If the pattern matches, the length of matching slice should be returned.
    /// Otherwise, `None` should be returned.
    ///
    /// It is assumed that the pattern begins matching from the start of the slice.
    fn eval(&self, input: &[T]) -> 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<T>,
    {
        Sequence {
            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<T>,
    {
        Choice {
            pat1: self,
            pat2: other,
        }
    }
}

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

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

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

/// Returns a new pattern that always matches the next element in the input if it exists.
///
/// ```
/// use bparse::{Pattern, one};
///
/// assert_eq!(one().eval(&[1, 2, 3]), Some(1));
/// ```
pub fn one() -> One {
    One
}

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

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

        Some(1)
    }
}

/// Returns a new pattern that will match if `slice` is a prefix of the input.
///
/// ```
/// use bparse::{Pattern, prefix};
///
/// let pattern = prefix(&[1]);
/// assert_eq!(pattern.eval(&[1, 2, 3]), Some(1));
/// ```
pub fn prefix<T>(slice: &[T]) -> Prefix<T>
where
    T: PartialEq,
    T: Copy,
{
    Prefix(slice)
}

/// See [`prefix`]
#[derive(Debug, Clone, Copy)]
pub struct Prefix<'p, T>(&'p [T]);

impl<T> Pattern<T> for Prefix<'_, T>
where
    T: PartialEq,
    T: Copy,
{
    fn eval(&self, input: &[T]) -> Option<usize> {
        if !input.starts_with(self.0) {
            return None;
        }

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

/// Returns a new pattern that will match an element 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<T>(lo: T, hi: T) -> ElementRange<T>
where
    T: PartialOrd,
    T: Copy,
{
    ElementRange(lo, hi)
}

/// See [`range()`]
#[derive(Debug, Clone, Copy)]
pub struct ElementRange<T>(T, T);

impl<T> Pattern<T> for ElementRange<T>
where
    T: PartialOrd,
    T: Copy,
{
    fn eval(&self, input: &[T]) -> Option<usize> {
        let first = input.first()?;

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

        None
    }
}

/// Returns a new pattern that matches 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<T, P>(pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P>(n: usize, pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P>(n: usize, pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P>(pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P>(n: usize, pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P>(lo: usize, hi: usize, pattern: P) -> Repetition<P>
where
    P: Pattern<T>,
{
    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<T, P> Pattern<T> for Repetition<P>
where
    P: Pattern<T>,
{
    fn eval<'i>(&self, input: &[T]) -> 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 returns `Some(0)` if the underlying pattern did not match which makes it function as a negative lookahead.
pub fn not<T, P>(pattern: P) -> Not<P>
where
    P: Pattern<T>,
{
    Not(pattern)
}

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

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

        Some(0)
    }
}

#[cfg(test)]
mod tests {
    use super::byte::*;
    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("b").eval(b"a"), Some(0));
        assert_eq!(not("a").eval(b"a"), 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));
    }
}