lazy_template/enclosed/
simple_query.rs

1use super::ComponentParserInput;
2use crate::Parse;
3use derive_more::{Display, Error};
4use pipe_trait::Pipe;
5use split_char_from_str::SplitCharFromStr;
6
7pub type ParserInput<'a> = ComponentParserInput<'a>;
8
9#[derive(Debug, Clone, Copy)]
10pub struct SimpleQueryParser;
11pub type Parser = SimpleQueryParser;
12
13pub type SimpleQuery<'a> = &'a str;
14pub type ParseOutput<'a> = SimpleQuery<'a>;
15
16#[derive(Debug, Display, Error, Clone, Copy)]
17pub enum ParseError {
18    #[display("Unexpected token {_0:?}")]
19    UnexpectedChar(#[error(not(source))] char),
20    #[display("Unexpected end of input")]
21    UnexpectedEndOfInput,
22}
23
24impl<'a> Parse<'a, ParserInput<'a>> for Parser {
25    type Output = ParseOutput<'a>;
26    type Error = Option<ParseError>;
27
28    fn parse(&self, input: ParserInput<'a>) -> Result<(Self::Output, &'a str), Self::Error> {
29        let (head, tail) = input.text.split_first_char().ok_or(None)?;
30
31        if head == input.config.close_bracket {
32            return head.pipe(ParseError::UnexpectedChar).pipe(Some).pipe(Err);
33        }
34
35        if head != input.config.open_bracket {
36            return Err(None);
37        }
38
39        let (close_index, _) = tail
40            .char_indices()
41            .find(|(_, char)| *char == input.config.close_bracket)
42            .ok_or(ParseError::UnexpectedEndOfInput)
43            .map_err(Some)?;
44        let query = &tail[..close_index];
45        let rest = &tail[(close_index + 1)..];
46        Ok((query, rest))
47    }
48}