add: string_parser and char_satisfy parser.
This commit is contained in:
37
src/text/string_parsers.rs
Normal file
37
src/text/string_parsers.rs
Normal 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),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user