memx/iter/
iter_rchr_tpl.rs

1#[inline]
2pub fn memrchr_tpl_iter(
3    haystack: &[u8],
4    needle1: u8,
5    needle2: u8,
6    needle3: u8,
7) -> MemrchrTplIter<'_> {
8    MemrchrTplIter::new(haystack, needle1, needle2, needle3)
9}
10
11pub struct MemrchrTplIter<'a> {
12    haystack: &'a [u8],
13    needle1: u8,
14    needle2: u8,
15    needle3: u8,
16    position: usize, // 0: idx is -1, 1: idx is 0, 2: idx is 1
17}
18impl MemrchrTplIter<'_> {
19    #[inline]
20    pub fn new(haystack: &[u8], needle1: u8, needle2: u8, needle3: u8) -> MemrchrTplIter<'_> {
21        MemrchrTplIter {
22            needle1,
23            needle2,
24            needle3,
25            haystack,
26            position: haystack.len() + 1,
27        }
28    }
29}
30impl Iterator for MemrchrTplIter<'_> {
31    type Item = usize;
32    #[inline]
33    fn next(&mut self) -> Option<usize> {
34        if self.position == 0 {
35            return None;
36        }
37        match crate::memrchr_tpl(
38            &self.haystack[..(self.position - 1)],
39            self.needle1,
40            self.needle2,
41            self.needle3,
42        ) {
43            Some(idx) => {
44                self.position = idx + 1;
45                Some(idx)
46            }
47            None => {
48                self.position = 0;
49                None
50            }
51        }
52    }
53    #[inline]
54    fn size_hint(&self) -> (usize, Option<usize>) {
55        (0, Some(self.haystack.len()))
56    }
57}
58
59impl DoubleEndedIterator for MemrchrTplIter<'_> {
60    #[inline]
61    fn next_back(&mut self) -> Option<Self::Item> {
62        if self.position > self.haystack.len() {
63            return None;
64        }
65        match crate::memchr_tpl(
66            &self.haystack[self.position..],
67            self.needle1,
68            self.needle2,
69            self.needle3,
70        ) {
71            Some(idx) => {
72                let found = self.position + idx;
73                self.position = self.position + idx + 1;
74                Some(found)
75            }
76            None => {
77                self.position = self.haystack.len() + 1;
78                None
79            }
80        }
81    }
82}