iterator_endiate/lib.rs
1#![doc = include_str!("../README.md")]
2
3/// Extension trait for adding [EndiateIteratorExt::endiate] and [EndiateIteratorExt::nendiate]
4pub trait EndiateIteratorExt: Sized {
5 /// Similar to [`Iterator::enumerate`] but rather including indexes, it includes whether the item
6 /// is the last item in the iterator
7 /// ```
8 /// use iterator_endiate::EndiateIteratorExt;
9 /// let endiate = [1, 2, 3].into_iter().endiate().collect::<Vec<_>>();
10 /// assert_eq!(
11 /// endiate,
12 /// [
13 /// (false, 1),
14 /// (false, 2),
15 /// (true, 3),
16 /// ]
17 /// )
18 /// ```
19 fn endiate(self) -> Endiate<Self>;
20
21 /// Same as [EndiateIteratorExt::endiate] but bool is **not** at end
22 /// ```
23 /// use iterator_endiate::EndiateIteratorExt;
24 /// let nendiate = [1, 2, 3].into_iter().nendiate().collect::<Vec<_>>();
25 /// assert_eq!(
26 /// nendiate,
27 /// [
28 /// (true, 1),
29 /// (true, 2),
30 /// (false, 3),
31 /// ]
32 /// )
33 /// ```
34 fn nendiate(self) -> NEndiate<Self>;
35}
36
37impl<Iter: ExactSizeIterator> EndiateIteratorExt for Iter {
38 fn endiate(self) -> Endiate<Self> {
39 Endiate(self)
40 }
41
42 fn nendiate(self) -> NEndiate<Self> {
43 NEndiate(Endiate(self))
44 }
45}
46
47/// From [EndiateIteratorExt::endiate]
48pub struct Endiate<Iter>(pub(crate) Iter);
49
50/// From [EndiateIteratorExt::nendiate]
51pub struct NEndiate<Iter>(pub(crate) Endiate<Iter>);
52
53impl<Iter: ExactSizeIterator> Iterator for Endiate<Iter> {
54 type Item = (bool, Iter::Item);
55
56 fn next(&mut self) -> Option<Self::Item> {
57 self.0.next().map(|v| (self.0.len() == 0, v))
58 }
59}
60
61impl<Iter: ExactSizeIterator> Iterator for NEndiate<Iter> {
62 type Item = (bool, Iter::Item);
63
64 fn next(&mut self) -> Option<Self::Item> {
65 self.0.next().map(|(at_end, v)| (!at_end, v))
66 }
67}
68
69impl<Iter: ExactSizeIterator> ExactSizeIterator for Endiate<Iter> {}
70
71impl<Iter: ExactSizeIterator> ExactSizeIterator for NEndiate<Iter> {}