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
use std::str::Chars;
pub(crate) const EOF_CHAR: char = '\0';
#[derive(Debug, Clone)]
pub struct Cursor<'a> {
initial_len: usize,
chars: Chars<'a>,
}
impl<'a> Cursor<'a> {
pub fn new(input: &'a str) -> Self {
Self {
initial_len: input.len(),
chars: input.chars(),
}
}
pub fn first(&mut self) -> char {
self.chars.clone().next().unwrap_or(EOF_CHAR)
}
pub fn second(&mut self) -> char {
let mut it = self.chars.clone();
it.next();
it.next().unwrap_or(EOF_CHAR)
}
pub fn is_eof(&self) -> bool {
self.chars.as_str().is_empty()
}
pub fn bump(&mut self) -> Option<char> {
self.chars.next()
}
pub fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
while predicate(self.first()) && !self.is_eof() {
self.bump();
}
}
pub fn len_consumed(&self) -> usize {
self.initial_len - self.chars.as_str().len()
}
pub fn reset_len_consumed(&mut self) {
self.initial_len = self.chars.as_str().len();
}
}