rustrict/
buffer_proxy_iterator.rs

1use std::collections::VecDeque;
2use std::ops::RangeInclusive;
3
4/// This iterator buffers characters until they can be determined to be clean of profanity.
5pub(crate) struct BufferProxyIterator<I: Iterator<Item = char>> {
6    iter: I,
7    /// The index into iter of the start of buffer.
8    buffer_start_position: usize,
9    /// Staging area (to possibly censor).
10    buffer: VecDeque<I::Item>,
11}
12
13impl<I: Iterator<Item = char>> BufferProxyIterator<I> {
14    pub fn new(iter: I) -> Self {
15        BufferProxyIterator {
16            iter,
17            buffer_start_position: 0,
18            buffer: VecDeque::new(),
19        }
20    }
21
22    /// Returns index of the last character read, or None if nothing has been read yet.
23    pub fn index(&self) -> Option<usize> {
24        if self.buffer_start_position + self.buffer.len() == 0 {
25            // Didn't read anything yet.
26            return None;
27        }
28        Some(self.buffer_start_position + self.buffer.len() - 1)
29    }
30
31    /// Returns index of the next character that can be spied, or empty if no characters can be spied.
32    pub fn spy_next_index(&self) -> Option<usize> {
33        if self.buffer.is_empty() {
34            None
35        } else {
36            Some(self.buffer_start_position)
37        }
38    }
39
40    /// Spies one one more character.
41    pub fn spy_next(&mut self) -> Option<char> {
42        let ret = self.buffer.pop_front();
43        if ret.is_some() {
44            self.buffer_start_position += 1;
45        }
46        ret
47    }
48
49    /// Censors a given range (must be fully resident in the buffer).
50    pub fn censor(&mut self, range: RangeInclusive<usize>, replacement: char) {
51        let start = self.buffer_start_position;
52        for i in range {
53            self.buffer[i - start] = replacement;
54        }
55    }
56}
57
58impl<I: Iterator<Item = char>> Iterator for BufferProxyIterator<I> {
59    type Item = I::Item;
60
61    fn next(&mut self) -> Option<Self::Item> {
62        let ret = self.iter.next();
63        if let Some(val) = ret.as_ref() {
64            self.buffer.push_back(*val);
65        }
66        ret
67    }
68}