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
use std::iter::FromIterator;
use crate::{eyre, Buffer, Parse};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Tag<const TAG: &'static str>;
impl<const TAG: &'static str> Parse<char> for Tag<TAG> {
fn parse(input: &mut impl Buffer<char>) -> eyre::Result<Self> {
let s = String::from_iter(input.take(TAG.len()));
if TAG == s {
Ok(Self)
} else {
Err(eyre::eyre!("failed to parse tag {:?}, found {:?}", TAG, s))
}
}
fn peek(input: &mut impl Buffer<char>) -> bool {
TAG.chars().eq(input.take(TAG.len()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{parse, IntoBuf, Parse};
#[test]
fn test_parse_matches() {
let mut input = "(){}[]<>".chars().into_buf();
Tag::<"(">::parse(&mut input).unwrap();
Tag::<")">::parse(&mut input).unwrap();
Tag::<"{">::parse(&mut input).unwrap();
Tag::<"}">::parse(&mut input).unwrap();
Tag::<"[">::parse(&mut input).unwrap();
Tag::<"]">::parse(&mut input).unwrap();
Tag::<"<">::parse(&mut input).unwrap();
Tag::<">">::parse(&mut input).unwrap();
assert!(input.next().is_none())
}
#[test]
fn test_peek_matches() {
let mut input = "(){}[]<>".chars().into_buf();
let mut cursor = input.cursor();
assert!(Tag::<"(">::peek(&mut cursor));
assert!(Tag::<")">::peek(&mut cursor));
assert!(Tag::<"{">::peek(&mut cursor));
assert!(Tag::<"}">::peek(&mut cursor));
assert!(Tag::<"[">::peek(&mut cursor));
assert!(Tag::<"]">::peek(&mut cursor));
assert!(Tag::<"<">::peek(&mut cursor));
assert!(Tag::<">">::peek(&mut cursor));
assert!(cursor.next().is_none())
}
#[test]
fn test_parse_errors() {
let res: Result<Tag<"(">, _> = parse("1".chars());
assert_eq!(
format!("{}", res.unwrap_err()),
"failed to parse tag \"(\", found \"1\""
);
let res: Result<Tag<")">, _> = parse("1".chars());
assert_eq!(
format!("{}", res.unwrap_err()),
"failed to parse tag \")\", found \"1\""
);
}
}