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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::collections::VecDeque;
use std::iter::Iterator;
use std::ops::RangeInclusive;

/// This iterator buffers characters until they can be determined to be clean of profanity.
pub(crate) struct BufferProxyIterator<I: Iterator<Item = char>> {
    iter: I,
    /// The index into iter of the start of buffer.
    buffer_start_position: usize,
    /// Staging area (to possibly censor).
    buffer: VecDeque<I::Item>,
}

impl<I: Iterator<Item = char>> BufferProxyIterator<I> {
    pub fn new(iter: I) -> Self {
        BufferProxyIterator {
            iter,
            buffer_start_position: 0,
            buffer: VecDeque::new(),
        }
    }

    /// Returns index of the last character read, or None if nothing has been read yet.
    pub fn index(&self) -> Option<usize> {
        if self.buffer_start_position + self.buffer.len() == 0 {
            // Didn't read anything yet.
            return None;
        }
        Some(self.buffer_start_position + self.buffer.len() - 1)
    }

    /// Returns index of the next character that can be spied, or empty if no characters can be spied.
    pub fn spy_next_index(&self) -> Option<usize> {
        if self.buffer.is_empty() {
            None
        } else {
            Some(self.buffer_start_position)
        }
    }

    /// Spies one one more character.
    pub fn spy_next(&mut self) -> Option<char> {
        let ret = self.buffer.pop_front();
        if ret.is_some() {
            self.buffer_start_position += 1;
        }
        ret
    }

    /// Censors a given range (must be fully resident in the buffer).
    pub fn censor(&mut self, range: RangeInclusive<usize>, replacement: char) {
        let start = self.buffer_start_position;
        for i in range {
            self.buffer[i - start] = replacement;
        }
    }
}

impl<I: Iterator<Item = char>> Iterator for BufferProxyIterator<I> {
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let ret = self.iter.next();
        if let Some(val) = ret.as_ref() {
            self.buffer.push_back(*val);
        }
        ret
    }
}