add: string_parser and char_satisfy parser.

This commit is contained in:
2024-11-19 21:34:55 +08:00
parent e2c4388a0c
commit dd00a37369
2 changed files with 68 additions and 17 deletions

View File

@@ -0,0 +1,37 @@
use crate::parser::{FailedParserResult, Parser, ParserContext, ParserResult};
use std::cell::RefCell;
use std::rc::Rc;
pub struct StringParser {
pub(crate) str: &'static str,
}
impl<'a, TContext> Parser<'a, char, &'a [char], TContext> for StringParser {
fn parse(
&self,
_: Rc<RefCell<ParserContext<char, TContext>>>,
input: &'a [char],
) -> ParserResult<'a, char, &'a [char]> {
let length = self.str.chars().count();
if input.len() < length {
return Err(FailedParserResult::new(
input,
format!("Failed to get enough elements for string '{}'.", self.str),
));
}
if (&input[..length])
.iter()
.zip(self.str.chars())
.map(|(x, y)| *x == y)
.all(|x| x)
{
Ok((&input[length..], &input[..length]))
} else {
Err(FailedParserResult::new(
input,
format!("Input is not string '{}'", self.str),
))
}
}
}