Skip to main content

oni_comb_parser/primitive/
take.rs

1use core::marker::PhantomData;
2
3use crate::error::{ExpectError, Expected};
4use crate::fail::{Fail, PResult};
5use crate::input::Input;
6use crate::parser::Parser;
7
8pub struct Take<I: Input> {
9  n: usize,
10  _marker: PhantomData<fn(&mut I)>,
11}
12
13pub fn take<I: Input>(n: usize) -> Take<I> {
14  Take {
15    n,
16    _marker: PhantomData,
17  }
18}
19
20impl<I: Input> Parser<I> for Take<I> {
21  type Error = I::Error;
22  type Output = I::Slice;
23
24  #[inline]
25  fn parse_next(&mut self, input: &mut I) -> PResult<I::Slice, I::Error> {
26    let pos = input.offset();
27    let cp = input.checkpoint();
28    for _ in 0..self.n {
29      if input.next_token().is_none() {
30        input.reset(cp);
31        return Err(Fail::Backtrack(I::Error::from_expected(
32          pos,
33          Expected::Description("enough input"),
34        )));
35      }
36    }
37    Ok(input.slice_since(cp))
38  }
39}