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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/// An iterator to maintain state while iterating another iterator.
///
/// `Accumulate` is created by the [`accumulate`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`accumulate`]: trait.Accumulator.html#method.accumulate
/// [`Iterator`]: ../../std/iter/trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Accumulate<I, F>
where
    I: Iterator,
    F: Fn(I::Item, I::Item) -> I::Item,
{
    accum: Option<I::Item>,
    underlying: I,
    acc_fn: F,
}

impl<I, F> Iterator for Accumulate<I, F>
where
    I: Iterator,
    I::Item: Copy,
    F: Fn(I::Item, I::Item) -> I::Item,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        match self.underlying.next() {
            Some(x) => {
                let new_accum = match self.accum {
                    // Apply function to item-so-far and current item
                    Some(accum) => (self.acc_fn)(accum, x),

                    // This is the first item
                    None => x,
                };
                self.accum = Some(new_accum);
                Some(new_accum)
            }
            None => None,
        }
    }
}

/// An iterator to maintain state while iterating another iterator.
///
/// `Accumulate` is created by the [`accumulate`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`accumulate`]: trait.Accumulator.html#method.accumulate
/// [`Iterator`]: ../../std/iter/trait.Iterator.html
pub trait Accumulator: Iterator {
    /// An iterator adaptor that yields the computation of the closure `F` over the
    /// accumulated value and the next element of the preceding iterator.
    ///
    /// `accumulate()` takes a function or closure with two arguments,
    /// the first being the previous yielded value and the second an element from the preceding iterator.
    /// The iterator maintains the state of the last yielded value.
    ///
    /// The first element of the preceding iterator is yielded as-is.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use rs3cache::utils::adapters::Accumulator;
    ///
    /// let mut iter = (1..6).accumulate(|x, y| x + y);
    ///
    /// assert_eq!(iter.next(), Some(1));  // 1
    /// assert_eq!(iter.next(), Some(3));  // 1+2
    /// assert_eq!(iter.next(), Some(6));  // (1+2) + 3
    /// assert_eq!(iter.next(), Some(10)); // (1+2+3) + 4
    /// assert_eq!(iter.next(), Some(15)); // (1+2+3+4) + 5
    /// assert_eq!(iter.next(), None);
    /// ```
    fn accumulate<F>(self, f: F) -> Accumulate<Self, F>
    where
        F: Fn(Self::Item, Self::Item) -> Self::Item,
        Self::Item: Copy,
        Self: Sized,
        Self: Iterator,
    {
        Accumulate {
            accum: None,
            underlying: self,
            acc_fn: f,
        }
    }
}

impl<I: Iterator> Accumulator for I {}

/// An iterator that returns pair values ofn the preceding iterator.
///
/// `Pairwise` is created by the [`pairwise`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`pairwise`]: trait.Pairwisor.html#method.pairwise
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Pairwise<I>
where
    I: Iterator,
{
    state: Option<I::Item>,
    underlying_iterator: I,
}

impl<I> Iterator for Pairwise<I>
where
    I: Iterator,
    I::Item: Copy,
{
    type Item = (I::Item, I::Item);

    fn next(&mut self) -> Option<Self::Item> {
        match self.underlying_iterator.next() {
            Some(x) => match self.state {
                Some(y) => {
                    self.state = Some(x);
                    Some((y, x))
                }
                None => match self.underlying_iterator.next() {
                    Some(y) => {
                        self.state = Some(y);
                        Some((x, y))
                    }
                    None => None,
                },
            },
            None => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.underlying_iterator.size_hint()
    }
}

/// An iterator that returns pair values of the preceding iterator.
///
/// `Pairwise` is created by the [`pairwise`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`pairwise`]: trait.Pairwisor.html#method.pairwise
/// [`Iterator`]: trait.Iterator.html
pub trait Pairwisor: Iterator {
    /// An iterator adaptor that yields the preceding iterator in pairs.
    ///
    /// Similar to the [`windows`] method on [`slices`], but with owned elements.
    ///
    /// The first element of the preceding iterator is yielded unchanged.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use rs3cache::utils::adapters::Pairwisor;
    ///
    /// let mut iter = (0..6).pairwise();
    ///
    /// assert_eq!(iter.next(), Some((0, 1)));
    /// assert_eq!(iter.next(), Some((1, 2)));
    /// assert_eq!(iter.next(), Some((2, 3)));
    /// assert_eq!(iter.next(), Some((3, 4)));
    /// assert_eq!(iter.next(), Some((4, 5)));
    /// assert_eq!(iter.next(), None);
    /// ```
    ///
    /// [`windows`]: ../../std/primitive.slice.html#method.windows
    /// [`slices`]: ../../std/primitive.slice.html
    fn pairwise(self) -> Pairwise<Self>
    where
        Self::Item: Copy,
        Self: Sized,
        Self: Iterator,
    {
        Pairwise {
            state: None,
            underlying_iterator: self,
        }
    }
}

impl<I: Iterator> Pairwisor for I {}

#[cfg(test)]
mod accumulator_tests {
    use super::Accumulator;

    #[test]
    fn test_accumulator_cumulative() {
        let result: Vec<i32> = (1..6).accumulate(|x, y| x + y).collect();
        let expected_result: Vec<i32> = vec![1, 3, 6, 10, 15];
        assert!(result == expected_result)
    }

    #[test]
    fn test_accumulator_rolling_factorial() {
        let result: Vec<i32> = (1..6).accumulate(|x, y| x * y).collect();
        let expected_result: Vec<i32> = vec![1, 2, 6, 24, 120];
        assert!(result == expected_result)
    }
}

#[cfg(test)]
mod pairwise_tests {
    use super::Pairwisor;

    #[test]
    fn test_pairwise() {
        let result: Vec<(i32, i32)> = (0..6).pairwise().collect();
        let expected_result: Vec<(i32, i32)> = vec![(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)];
        assert_eq!(result, expected_result)
    }

    #[test]
    fn test_empty_pairwise() {
        let result: Vec<(i32, i32)> = Vec::new().into_iter().pairwise().collect();
        let expected_result: Vec<(i32, i32)> = Vec::new();
        assert_eq!(result, expected_result)
    }

    #[test]
    fn test_single_pairwise() {
        let result: Vec<(i32, i32)> = (0..1).pairwise().collect();
        let expected_result: Vec<(i32, i32)> = Vec::new();
        assert_eq!(result, expected_result)
    }

    #[test]
    fn test_double_pairwise() {
        let result: Vec<(i32, i32)> = (0..2).pairwise().collect();
        let expected_result: Vec<(i32, i32)> = vec![(0, 1)];
        assert_eq!(result, expected_result)
    }
}