1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::{CreateParserState, ParseResult, Parser};

type CharFilter = fn(char) -> bool;

/// A parser that parses until a literal is found.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct StopOn<S: AsRef<str>, F: Fn(char) -> bool + 'static = CharFilter> {
    literal: S,
    character_filter: F,
}

impl<S: AsRef<str>> CreateParserState for StopOn<S> {
    fn create_parser_state(&self) -> <Self as Parser>::PartialState {
        StopOnOffset::default()
    }
}

impl<S: AsRef<str>> From<S> for StopOn<S> {
    fn from(literal: S) -> Self {
        Self {
            literal,
            character_filter: |_| true,
        }
    }
}

impl<S: AsRef<str>> StopOn<S> {
    /// Create a new literal parser.
    pub fn new(literal: S) -> Self {
        Self {
            literal,
            character_filter: |_| true,
        }
    }
}

impl<S: AsRef<str>, F: Fn(char) -> bool + 'static> StopOn<S, F> {
    /// Only allow characters that pass the filter.
    pub fn filter_characters(self, character_filter: F) -> StopOn<S, F> {
        StopOn {
            literal: self.literal,
            character_filter,
        }
    }

    /// Get the literal that this parser stops on.
    pub fn literal(&self) -> &str {
        self.literal.as_ref()
    }
}

/// An error that can occur while parsing a string literal.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StopOnParseError;

impl std::fmt::Display for StopOnParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        "StopOnParseError".fmt(f)
    }
}

impl std::error::Error for StopOnParseError {}

/// The state of a stop on literal parser.
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct StopOnOffset {
    offset: usize,
    text: String,
}

impl StopOnOffset {
    /// Create a new stop on literal parser state.
    pub fn new(offset: usize) -> Self {
        Self {
            offset,
            text: String::new(),
        }
    }
}

impl<S: AsRef<str>, F: Fn(char) -> bool + 'static> Parser for StopOn<S, F> {
    type Error = StopOnParseError;
    type Output = String;
    type PartialState = StopOnOffset;

    fn parse<'a>(
        &self,
        state: &StopOnOffset,
        input: &'a [u8],
    ) -> Result<ParseResult<'a, Self::PartialState, Self::Output>, Self::Error> {
        let mut new_offset = state.offset;
        let mut text = state.text.clone();

        let input_str = std::str::from_utf8(input).unwrap();
        let literal_length = self.literal.as_ref().len();
        let mut literal_iter = self.literal.as_ref()[state.offset..].chars();

        for (i, input_char) in input_str.char_indices() {
            if !(self.character_filter)(input_char) {
                return Err(StopOnParseError);
            }

            let literal_char = literal_iter.next();

            if Some(input_char) == literal_char {
                new_offset += 1;

                if new_offset == literal_length {
                    text += std::str::from_utf8(&input[..i + 1]).unwrap();
                    return Ok(ParseResult::Finished {
                        result: text,
                        remaining: &input[i + 1..],
                    });
                }
            } else {
                literal_iter = self.literal.as_ref()[state.offset..].chars();
                new_offset = 0;
            }
        }

        text.push_str(input_str);

        Ok(ParseResult::Incomplete {
            new_state: StopOnOffset {
                offset: new_offset,
                text,
            },
            required_next: "".into(),
        })
    }
}

#[test]
fn literal_parser() {
    let parser = StopOn::new("Hello, world!");
    let state = StopOnOffset {
        offset: 0,
        text: String::new(),
    };
    assert_eq!(
        parser.parse(&state, b"Hello, world!"),
        Ok(ParseResult::Finished {
            result: "Hello, world!".to_string(),
            remaining: &[]
        })
    );
    assert_eq!(
        parser.parse(&state, b"Hello, world! This is a test"),
        Ok(ParseResult::Finished {
            result: "Hello, world!".to_string(),
            remaining: b" This is a test"
        })
    );
    assert_eq!(
        parser.parse(&state, b"Hello, "),
        Ok(ParseResult::Incomplete {
            new_state: StopOnOffset {
                offset: 7,
                text: "Hello, ".into()
            },
            required_next: "".into()
        })
    );
    assert_eq!(
        parser.parse(
            &parser
                .parse(&state, b"Hello, ")
                .unwrap()
                .unwrap_incomplete()
                .0,
            b"world!"
        ),
        Ok(ParseResult::Finished {
            result: "Hello, world!".to_string(),
            remaining: &[]
        })
    );
    assert_eq!(
        parser.parse(&state, b"Goodbye, world!"),
        Ok(ParseResult::Incomplete {
            new_state: StopOnOffset {
                offset: 0,
                text: "Goodbye, world!".into()
            },
            required_next: "".into()
        })
    );
}