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
use crate::{ParseContext, ParseIter, Parser, Reported, Result};
pub struct ExactParseIter {
end: usize,
}
impl Parser for str {
type Output = ();
type RawOutput = ();
type Iter<'parse> = ExactParseIter;
fn parse_iter<'parse>(
&'parse self,
context: &mut ParseContext<'parse>,
start: usize,
) -> Result<ExactParseIter, Reported> {
if context.source()[start..].starts_with(self) {
Ok(ExactParseIter {
end: start + self.len(),
})
} else {
Err(context.error_expected(start, &format!("{self:?}")))
}
}
}
impl Parser for char {
type Output = ();
type RawOutput = ();
type Iter<'parse> = ExactParseIter;
fn parse_iter<'parse>(
&'parse self,
context: &mut ParseContext<'parse>,
start: usize,
) -> Result<ExactParseIter, Reported> {
if context.source()[start..].starts_with(*self) {
Ok(ExactParseIter {
end: start + self.len_utf8(),
})
} else {
Err(context.error_expected(start, &format!("{self:?}")))
}
}
}
impl<'parse> ParseIter<'parse> for ExactParseIter {
type RawOutput = ();
fn match_end(&self) -> usize {
self.end
}
fn backtrack(&mut self, _context: &mut ParseContext<'parse>) -> Result<(), Reported> {
Err(Reported)
}
fn convert(&self) {}
}
#[cfg(test)]
mod tests {
use crate::testing::*;
#[test]
fn test_string_lifetime() {
let x = format!("{} {}!", "hello", "world");
let p: &str = &x;
assert_parse_eq(&p, "hello world!", ());
}
#[test]
fn test_exact_char_errors() {
let p = '\n';
assert_parse_error(&p, "q", r#"expected '\n' at"#);
assert_parse_error(&p, "", r#"expected '\n' at end"#);
}
}