pub struct PeekCharIterator {
chars: Vec<char>,
current_index: usize,
peeked_index: Option<usize>,
marked_index: Option<usize>,
}
impl PeekCharIterator {
pub fn new(chars: Vec<char>) -> Self {
PeekCharIterator {
chars,
current_index: 0,
peeked_index: None,
marked_index: None,
}
}
pub fn peek(&mut self) -> Option<char> {
if self.peeked_index.is_none() {
self.peeked_index = Some(self.current_index);
}
self.chars.get(self.peeked_index.unwrap()).copied()
}
pub fn mark(&mut self) {
self.marked_index = Some(self.current_index);
}
pub fn get_mark2cur(&self) -> Option<Vec<char>> {
self.marked_index
.map(|marked_index| self.chars[marked_index..self.current_index].to_vec())
}
}
impl Iterator for PeekCharIterator {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
if let Some(index) = self.peeked_index.take() {
self.current_index = index + 1;
return self.chars.get(index).copied();
}
let result = self.chars.get(self.current_index).copied();
self.current_index += 1;
result
}
}