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

/// Check whether it is satisfied
/// ## example
/// ```
/// # use parser_fuck::*;
/// let code = "asd123".span();
/// let x = satisfy(|c: Char| c == 'a');
/// let r = x.parse(code);
/// assert_eq!(r, Some(0..1))
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Satisfy<F, I = ()> {
    f: ExtRefCell<F>,
    _i: PhantomData<I>,
}
impl<I, F> Satisfy<F, I>
where
    I: TimeTravel,
    F: FnMut(I::Item) -> bool,
{
    #[inline]
    pub fn new(f: F) -> Self {
        Self {
            f: ExtRefCell::new(f),
            _i: PhantomData,
        }
    }
}
impl<I, F> Parser<I> for Satisfy<F, I>
where
    I: TimeTravel,
    F: FnMut(I::Item) -> bool,
{
    type Output = Range<usize>;

    fn parse(&self, mut input: I) -> Option<Self::Output> {
        let from = input.save();
        let n: I::Item = input.next()?;
        input.do_ready();
        let f = unsafe { self.f.get_mut() };
        let r: bool = f(n);
        if r {
            Some(input.make_range(from))
        } else {
            None
        }
    }
}

/// Check whether it is satisfied
/// ## example
/// ```
/// # use parser_fuck::*;
/// let code = "asd123".span();
/// let x = satisfy(|c: Char| c == 'a');
/// let r = x.parse(code);
/// assert_eq!(r, Some(0..1))
/// ```
#[inline]
pub fn satisfy<I, F>(f: F) -> Satisfy<F, I>
where
    I: TimeTravel,
    F: FnMut(I::Item) -> bool,
{
    Satisfy::new(f)
}

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

    #[test]
    fn test() {
        let code = "asd";
        let span = code.span();
        let x = satisfy(|c: Char| c == 'a');

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

    #[test]
    fn test_one() {
        let code = "a";
        let span = code.span();
        let x = satisfy(|c: Char| c == 'a');

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

    #[test]
    fn test_none() {
        let code = "b";
        let span = code.span();
        let x = satisfy(|c: Char| c == 'a');

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

    #[test]
    fn test_empty() {
        let code = "";
        let span = code.span();
        let x = satisfy(|c: Char| c == 'a');

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