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
70
71
72
73
74
75
76
77
78
79
//! A helper trait for bounded iteration over characters in an arbitrary
//! piece of text.
use crate::{
    buffer::{Buffer, GapBuffer, IdxChars},
    exec::cached_stdin::{CachedStdin, CachedStdinIter},
};

/// Something that can yield characters between two offsets from within
/// a piece of text.
///
/// To avoid boxing, the return of the methods provided by this trait
/// are an enum rather than a trait object.
pub trait IterBoundedChars {
    /// Iterate forward: from -> to
    ///
    /// This should be an inclusive range from..=to
    fn iter_between(&self, from: usize, to: usize) -> CharIter<'_>;

    /// Iterate backward: from -> to
    ///
    /// This should be an inclusive range from..=to
    fn rev_iter_between(&self, from: usize, to: usize) -> CharIter<'_>;
}

impl IterBoundedChars for GapBuffer {
    fn iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::Slice(self.slice(from, to).indexed_chars(from, false))
    }

    fn rev_iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::Slice(self.slice(to, from).indexed_chars(to, true))
    }
}

impl IterBoundedChars for Buffer {
    fn iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::Slice(self.txt.slice(from, to).indexed_chars(from, false))
    }

    fn rev_iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::Slice(self.txt.slice(to, from).indexed_chars(to, true))
    }
}

/// Supported iterator types that can be returned by an InterBoundedChars
pub enum CharIter<'a> {
    Slice(IdxChars<'a>),
    StdIn(CachedStdinIter<'a>),
}

impl<'a> Iterator for CharIter<'a> {
    type Item = (usize, char);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Slice(it) => it.next(),
            Self::StdIn(it) => it.next(),
        }
    }
}

impl IterBoundedChars for CachedStdin {
    fn iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::StdIn(CachedStdinIter {
            inner: self,
            from,
            to,
        })
    }

    /// This will always return None
    fn rev_iter_between(&self, from: usize, to: usize) -> CharIter {
        CharIter::StdIn(CachedStdinIter {
            inner: self,
            from,
            to,
        })
    }
}