1use std::str::Chars;
2
3pub enum FrontmatterAllowed {
4    Yes,
5    No,
6}
7
8pub struct Cursor<'a> {
13    len_remaining: usize,
14    chars: Chars<'a>,
16    pub(crate) frontmatter_allowed: FrontmatterAllowed,
17    #[cfg(debug_assertions)]
18    prev: char,
19}
20
21pub(crate) const EOF_CHAR: char = '\0';
22
23impl<'a> Cursor<'a> {
24    pub fn new(input: &'a str, frontmatter_allowed: FrontmatterAllowed) -> Cursor<'a> {
25        Cursor {
26            len_remaining: input.len(),
27            chars: input.chars(),
28            frontmatter_allowed,
29            #[cfg(debug_assertions)]
30            prev: EOF_CHAR,
31        }
32    }
33
34    pub fn as_str(&self) -> &'a str {
35        self.chars.as_str()
36    }
37
38    pub(crate) fn prev(&self) -> char {
41        #[cfg(debug_assertions)]
42        {
43            self.prev
44        }
45
46        #[cfg(not(debug_assertions))]
47        {
48            EOF_CHAR
49        }
50    }
51
52    pub fn first(&self) -> char {
57        self.chars.clone().next().unwrap_or(EOF_CHAR)
59    }
60
61    pub(crate) fn second(&self) -> char {
63        let mut iter = self.chars.clone();
65        iter.next();
66        iter.next().unwrap_or(EOF_CHAR)
67    }
68
69    pub fn third(&self) -> char {
71        let mut iter = self.chars.clone();
73        iter.next();
74        iter.next();
75        iter.next().unwrap_or(EOF_CHAR)
76    }
77
78    pub(crate) fn is_eof(&self) -> bool {
80        self.chars.as_str().is_empty()
81    }
82
83    pub(crate) fn pos_within_token(&self) -> u32 {
85        (self.len_remaining - self.chars.as_str().len()) as u32
86    }
87
88    pub(crate) fn reset_pos_within_token(&mut self) {
90        self.len_remaining = self.chars.as_str().len();
91    }
92
93    pub(crate) fn bump(&mut self) -> Option<char> {
95        let c = self.chars.next()?;
96
97        #[cfg(debug_assertions)]
98        {
99            self.prev = c;
100        }
101
102        Some(c)
103    }
104
105    pub(crate) fn bump_bytes(&mut self, n: usize) {
107        self.chars = self.as_str()[n..].chars();
108    }
109
110    pub(crate) fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
112        while predicate(self.first()) && !self.is_eof() {
115            self.bump();
116        }
117    }
118
119    pub(crate) fn eat_until(&mut self, byte: u8) {
120        self.chars = match memchr::memchr(byte, self.as_str().as_bytes()) {
121            Some(index) => self.as_str()[index..].chars(),
122            None => "".chars(),
123        }
124    }
125}