Debian Codegraph @

src/sudoers/char_stream.rs

raw symbols SCIP
1 #[derive(Clone)]
2 pub struct CharStream<'a> {
3 iter: std::iter::Peekable<std::str::Chars<'a>>,
4 line: usize,
5 col: usize,
6 }
7
8 impl<'a> CharStream<'a> {
9 pub fn new_with_pos(src: &'a str, (line, col): (usize, usize)) -> Self {
10 CharStream {
11 iter: src.chars().peekable(),
12 line,
13 col,
14 }
15 }
16
17 pub fn new(src: &'a str) -> Self {
18 Self::new_with_pos(src, (1, 1))
19 }
20
21 pub fn next_if(&mut self, f: impl FnOnce(char) -> bool) -> Option<char> {
22 let item = self.iter.next_if(|&c| f(c));
23 match item {
24 Some('\n') => {
25 self.line += 1;
26 self.col = 1;
27 }
28 Some(_) => self.col += 1,
29 _ => {}
30 }
31 item
32 }
33
34 pub fn eat_char(&mut self, expect_char: char) -> bool {
35 self.next_if(|c| c == expect_char).is_some()
36 }
37
38 pub fn skip_to_newline(&mut self) {
39 while self.next_if(|c| c != '\n').is_some() {}
40 }
41
42 pub fn peek(&mut self) -> Option<char> {
43 self.iter.peek().cloned()
44 }
45
46 pub fn get_pos(&self) -> (usize, usize) {
47 (self.line, self.col)
48 }
49
50 pub fn advance(&mut self, n: usize) {
51 for _ in 0..n {
52 self.next_if(|_| true);
53 }
54 }
55 }
56
57 #[cfg(test)]
58 mod test {
59 use super::*;
60
61 #[test]
62 fn test_iter() {
63 let mut stream = CharStream::new("12\n3\n");
64 assert_eq!(stream.peek(), Some('1'));
65 assert!(stream.eat_char('1'));
66 assert_eq!(stream.peek(), Some('2'));
67 assert!(stream.eat_char('2'));
68 assert!(stream.eat_char('\n'));
69 assert_eq!(stream.peek(), Some('3'));
70 assert!(stream.eat_char('3'));
71 assert_eq!(stream.get_pos(), (2, 2));
72 }
73 }