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
use crate::*;
use std::marker::PhantomData;

/// Parse 1 or 0 times
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct May<A, I = ()> {
    a: A,
    _i: PhantomData<I>,
}
impl<I: TimeTravel, A> May<A, I>
where
    A: Parser<I>,
{
    #[inline]
    pub fn new(a: A) -> Self {
        Self { a, _i: PhantomData }
    }
}
impl<I: TimeTravel, A> Parser<I> for May<A, I>
where
    A: Parser<I>,
{
    type Output = Option<A::Output>;

    fn parse(&self, mut input: I) -> Option<Self::Output> {
        let from = input.save();
        let a = self.a.parse(input.ref_clone());
        if a.is_none() {
            input.back(from);
        } else {
            input.re_ready();
        }
        Some(a)
    }
}

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

    #[test]
    fn test() {
        let code = "asd123";
        let span = code.span();
        let a = substr("asd");
        let x = a.may();

        let r = x.parse(span);
        println!("{:?}", r);
        assert_eq!(r, Some(Some(0..3)));
    }

    #[test]
    fn test_none() {
        let code = "123123";
        let span = code.span();
        let a = substr("asd");
        let x = a.may();

        let r = x.parse(span);
        println!("{:?}", r);
        assert_eq!(r, Some(None));
    }

    #[test]
    fn test_2() {
        let code = "asdasd";
        let span = code.span();
        let a = substr("asd");
        let x = a.may();

        let r = x.parse(span);
        println!("{:?}", r);
        assert_eq!(r, Some(Some(0..3)));
    }

    #[test]
    fn test_multi() {
        let code = "asd123";
        let span = code.span();
        let a = substr("asd");
        let b = substr("123");
        let x = a.may();
        let y = b.may();

        let r = x.parse(span.ref_clone());
        println!("{:?}", r);
        assert_eq!(r, Some(Some(0..3)));
        let r = y.parse(span);
        println!("{:?}", r);
        assert_eq!(r, Some(Some(3..6)));
    }
}