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
#![warn(missing_docs)]
pub struct KeyList<'a> {
input: &'a str,
start: char,
end: char
}
impl<'a> KeyList<'a> {
pub fn new(input: &'a str, start: char, end: char) -> Self {
Self {
input,
start,
end
}
}
}
impl<'a> Iterator for KeyList<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
let mut key = None;
if let Some(i) = self.input.find(self.start) {
self.input = &self.input[i..];
let mut first = true;
let rest = self.input.char_indices()
.take_while(|(_, c)| {
if first {
first = false;
return true;
}
*c != self.end
})
.last()
.map(|(idx, c)| idx + c.len_utf8())
.unwrap_or_default();
key = Some(&self.input[..(rest + 1)]);
self.input = &self.input[(rest + 1)..];
}
key
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn find_keys() {
let input = "<black> <red> one two <three>";
let key_count = KeyList::new(input, '<', '>').count();
assert_eq!(key_count, 3);
}
#[test]
fn different_start() {
let input = "<A/ <B> one two <C/";
let key_count = KeyList::new(input, '<', '/').count();
assert_eq!(key_count, 2);
}
#[test]
fn different_character() {
let input = "/A/ /B/ one two /C/";
let key_count = KeyList::new(input, '/', '/').count();
assert_eq!(key_count, 3);
}
}