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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use num_traits::{FromPrimitive, One};

use crate::IdxSize;

/// An iterator that yields the current count and the element during iteration.
///
/// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`enumerate`]: Iterator::enumerate
/// [`Iterator`]: trait.Iterator.html
#[derive(Clone, Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct EnumerateIdx<I, IdxType> {
    iter: I,
    count: IdxType,
}

impl<I, IdxType> Iterator for EnumerateIdx<I, IdxType>
where
    I: Iterator,
    IdxType: std::ops::Add<Output = IdxType> + FromPrimitive + std::ops::AddAssign + One + Copy,
{
    type Item = (IdxType, <I as Iterator>::Item);

    /// # Overflow Behavior
    ///
    /// The method does no guarding against overflows, so enumerating more than
    /// `idx::MAX` elements either produces the wrong result or panics. If
    /// debug assertions are enabled, a panic is guaranteed.
    ///
    /// # Panics
    ///
    /// Might panic if the index of the element overflows a `idx`.
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let a = self.iter.next()?;
        let i = self.count;
        self.count += IdxType::one();
        Some((i, a))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        let a = self.iter.nth(n)?;
        let i = self.count + IdxType::from_usize(n).unwrap();
        self.count = i + IdxType::one();
        Some((i, a))
    }

    #[inline]
    fn count(self) -> usize {
        self.iter.count()
    }
}

impl<I, IdxType> DoubleEndedIterator for EnumerateIdx<I, IdxType>
where
    I: ExactSizeIterator + DoubleEndedIterator,
    IdxType: std::ops::Add<Output = IdxType> + FromPrimitive + std::ops::AddAssign + One + Copy,
{
    #[inline]
    fn next_back(&mut self) -> Option<(IdxType, <I as Iterator>::Item)> {
        let a = self.iter.next_back()?;
        let len = IdxType::from_usize(self.iter.len()).unwrap();
        // Can safely add, `ExactSizeIterator` promises that the number of
        // elements fits into a `usize`.
        Some((self.count + len, a))
    }

    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<(IdxType, <I as Iterator>::Item)> {
        let a = self.iter.nth_back(n)?;
        let len = IdxType::from_usize(self.iter.len()).unwrap();
        // Can safely add, `ExactSizeIterator` promises that the number of
        // elements fits into a `usize`.
        Some((self.count + len, a))
    }
}

impl<I, IdxType> ExactSizeIterator for EnumerateIdx<I, IdxType>
where
    I: ExactSizeIterator,
    IdxType: std::ops::Add<Output = IdxType> + FromPrimitive + std::ops::AddAssign + One + Copy,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

pub trait EnumerateIdxTrait: Iterator {
    fn enumerate_idx(self) -> EnumerateIdx<Self, IdxSize>
    where
        Self: Sized,
    {
        EnumerateIdx {
            iter: self,
            count: 0,
        }
    }

    fn enumerate_u32(self) -> EnumerateIdx<Self, u32>
    where
        Self: Sized,
    {
        EnumerateIdx {
            iter: self,
            count: 0,
        }
    }
}

impl<T: ?Sized> EnumerateIdxTrait for T where T: Iterator {}