Function neure::re::ctor::into_dyn_ctor

source ·
pub fn into_dyn_ctor<'a, 'b, C, O>(
    invoke: impl Fn(&mut C) -> Result<O, Error> + 'b
) -> DynamicCtor<'b, C, O>where
    C: Context<'a>,
Expand description

For use in recursive parsers, it will construct a type that implements Ctor<'_, C, M, O> from a closure(Fn(&mut C) -> Result<O, Error>).

Example 1

    pub fn parser<'a: 'b, 'b>(
        ctor: RecursiveCtor<'b, BytesCtx<'a>, &'a [u8]>,
    ) -> impl Fn(&mut BytesCtx<'a>) -> Result<&'a [u8], Error> + 'b {
        move |ctx| {
            let re = u8::is_ascii_lowercase.repeat_one();
            let re = ctor
                .clone()
                .or(re)
                .quote(b"{", b"}")
                .or(ctor.clone().or(re).quote(b"[", b"]"));

            ctx.ctor(&re)
        }
    }
     
    // into_dyn_ctor using by rec_parser
    let parser = re::ctor::rec_parser(parser);

    assert_eq!(BytesCtx::new(b"[a]").ctor(&parser)?, b"a");
    assert_eq!(BytesCtx::new(b"{{[[{[{b}]}]]}}").ctor(&parser)?, b"b");
    assert_eq!(BytesCtx::new(b"[{{{[c]}}}]").ctor(&parser)?, b"c");
    Ok(())

Example 2

    let num = u8::is_ascii_digit
        .repeat_one()
        .map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
        .map(map::from_str::<usize>());
    let num = num.clone().sep_once(b",", num);
    let re = re::ctor::into_dyn_ctor(|ctx: &mut BytesCtx| ctx.ctor(&num));

    assert_eq!(BytesCtx::new(b"3,0").ctor(&re)?, (3, 0));
    assert_eq!(BytesCtx::new(b"2,1").ctor(&re)?, (2, 1));
    assert_eq!(BytesCtx::new(b"0,3").ctor(&re)?, (0, 3));
    Ok(())