Skip to main content

oni_comb_parser/text/
take_while1.rs

1use crate::error::ParseError;
2use crate::fail::{Fail, PResult};
3use crate::input::Input;
4use crate::parser::Parser;
5use crate::str_input::StrInput;
6
7pub struct TakeWhile1<F>(F);
8
9pub fn take_while1<F: FnMut(char) -> bool>(f: F) -> TakeWhile1<F> {
10  TakeWhile1(f)
11}
12
13impl<'a, F> Parser<StrInput<'a>> for TakeWhile1<F>
14where
15  F: FnMut(char) -> bool,
16{
17  type Error = ParseError;
18  type Output = &'a str;
19
20  #[inline]
21  fn parse_next(&mut self, input: &mut StrInput<'a>) -> PResult<&'a str, ParseError> {
22    let pos = input.offset();
23    let remaining = input.as_str();
24    let mut consumed = 0;
25    for c in remaining.chars() {
26      if (self.0)(c) {
27        consumed += c.len_utf8();
28      } else {
29        break;
30      }
31    }
32    if consumed == 0 {
33      return Err(Fail::Backtrack(ParseError::expected_description(
34        pos,
35        "at least one matching character",
36      )));
37    }
38    input.advance(consumed);
39    Ok(&remaining[..consumed])
40  }
41}