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
use crate::{
    apply::Apply,
    ruled::Ruled,
};

#[derive(Copy, Clone, Debug)]
pub struct Opt<R>(pub R);

impl<I, R> Apply<I> for Opt<R>
    where
        R: Apply<I>,
        I: Copy,
{
    type Err = R::Err;
    type Res = Option<R::Res>;

    fn apply(self, input: I) -> Ruled<I, Self::Res, Self::Err> {
        match self.0.apply(input) {
            Ruled::Ok(r, i) => Ruled::Ok(Some(r), i),
            Ruled::Err(_) => Ruled::Ok(None, input),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        apply::apply,
        rule::rule,
    };

    #[test]
    fn opt() {
        let r = rule("q").opt();
        assert_eq!(apply(r, "qw"), Ruled::Ok(Some("q"), "w"));
        assert_eq!(apply(r, "w"), Ruled::Ok(None, "w"));
    }
}