intuicio_parser/
literal.rs1use crate::{ParseResult, Parser, ParserExt, ParserHandle, ParserOutput, ParserRegistry};
2use std::borrow::Cow;
3
4pub mod shorthand {
5 use super::*;
6
7 pub fn lit(value: impl Into<Cow<'static, str>>) -> ParserHandle {
8 LiteralParser::new(value).into_handle()
9 }
10}
11
12#[derive(Clone)]
13pub struct LiteralParser {
14 literal: Cow<'static, str>,
15}
16
17impl LiteralParser {
18 pub fn new(value: impl Into<Cow<'static, str>>) -> Self {
19 Self {
20 literal: value.into(),
21 }
22 }
23}
24
25impl Parser for LiteralParser {
26 fn parse<'a>(&self, _: &ParserRegistry, input: &'a str) -> ParseResult<'a> {
27 if input.starts_with(&*self.literal) {
28 Ok((
29 &input[self.literal.len()..],
30 ParserOutput::new(self.literal.to_string()).ok().unwrap(),
31 ))
32 } else {
33 Err(format!("Expected '{}'", self.literal).into())
34 }
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use crate::{literal::LiteralParser, shorthand::lit, ParserRegistry};
41
42 fn is_async<T: Send + Sync>() {}
43
44 #[test]
45 fn test_literal() {
46 is_async::<LiteralParser>();
47
48 let registry = ParserRegistry::default();
49 let keyword = lit("foo");
50 let (rest, result) = keyword.parse(®istry, "foo bar").unwrap();
51 assert_eq!(rest, " bar");
52 let result = result.consume::<String>().ok().unwrap();
53 assert_eq!(result.as_str(), "foo");
54 }
55}