nvim_gtk/render/
itemize.rs

1use std::str::CharIndices;
2
3pub struct ItemizeIterator<'a> {
4    char_iter: CharIndices<'a>,
5    line: &'a str,
6}
7
8impl<'a> ItemizeIterator<'a> {
9    pub fn new(line: &'a str) -> Self {
10        ItemizeIterator {
11            char_iter: line.char_indices(),
12            line,
13        }
14    }
15}
16
17impl<'a> Iterator for ItemizeIterator<'a> {
18    type Item = (usize, usize);
19
20    fn next(&mut self) -> Option<Self::Item> {
21        let mut start_index = None;
22
23        let end_index = loop {
24            if let Some((index, ch)) = self.char_iter.next() {
25                let is_whitespace = ch.is_whitespace();
26
27                if start_index.is_none() && !is_whitespace {
28                    start_index = Some(index);
29                }
30                if start_index.is_some() && is_whitespace {
31                    break index;
32                }
33            } else {
34                break self.line.len();
35            }
36        };
37
38        if let Some(start_index) = start_index {
39            Some((start_index, end_index - start_index))
40        } else {
41            None
42        }
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_iterator() {
52        let mut iter = ItemizeIterator::new("Test  line ");
53
54        assert_eq!(Some((0, 4)), iter.next());
55        assert_eq!(Some((6, 4)), iter.next());
56        assert_eq!(None, iter.next());
57    }
58}