Skip to main content

oni_comb_parser/primitive/
take.rs

1use core::marker::PhantomData;
2
3use crate::error::ParseError;
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 = ParseError;
22  type Output = I::Slice;
23
24  #[inline]
25  fn parse_next(&mut self, input: &mut I) -> PResult<I::Slice, ParseError> {
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(ParseError::expected_description(pos, "enough input")));
32      }
33    }
34    Ok(input.slice_since(cp))
35  }
36}