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

/// Map a `Parser<Output = T>` to `Parser<Output = U>` by applying a function to a contained value
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Map<B: Parser<I>, I: TimeTravel, F> {
    base: B,
    f: ExtRefCell<F>,
    _i: PhantomData<I>,
}
impl<B: Parser<I>, I: TimeTravel, U, F> Map<B, I, F>
where
    F: FnMut(B::Output) -> U,
{
    pub fn new(base: B, f: F) -> Self {
        Self {
            base,
            f: ExtRefCell::new(f),
            _i: PhantomData,
        }
    }
}
impl<B: Parser<I>, I: TimeTravel, U, F> Parser<I> for Map<B, I, F>
where
    F: FnMut(B::Output) -> U,
{
    type Output = U;

    fn parse(&self, input: I) -> Option<Self::Output> {
        let base = self.base.parse(input)?;
        let f = unsafe { self.f.get_mut() };
        Some(f(base))
    }
}

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

    #[test]
    fn test() {
        let code = "asd";
        let span = code.span();
        let x = substr("asd");
        let m = x.map(|r| span.com_string(r));

        let r = m.parse(span.ref_clone());
        println!("{:?}", r);
        assert_eq!(r, Some(Some("asd".to_string())));
    }
}