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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Some iterator that produces tuples

use std::iter::Cycle;
use std::iter::Fuse;
use std::iter::FusedIterator;
use std::marker::PhantomData;

use crate::size_hint;

// `HomogeneousTuple` is a public facade for `TupleCollect`, allowing
// tuple-related methods to be used by clients in generic contexts, while
// hiding the implementation details of `TupleCollect`.
// See https://github.com/rust-itertools/itertools/issues/387

/// Implemented for homogeneous tuples of size up to 12.
pub trait HomogeneousTuple: TupleCollect {}

impl<T: TupleCollect> HomogeneousTuple for T {}

/// An iterator over a incomplete tuple.
///
/// See [`.tuples()`](crate::Itertools::tuples) and
/// [`Tuples::into_buffer()`].
#[derive(Clone, Debug)]
pub struct TupleBuffer<T>
where
    T: HomogeneousTuple,
{
    cur: usize,
    buf: T::Buffer,
}

impl<T> TupleBuffer<T>
where
    T: HomogeneousTuple,
{
    fn new(buf: T::Buffer) -> Self {
        TupleBuffer { cur: 0, buf }
    }
}

impl<T> Iterator for TupleBuffer<T>
where
    T: HomogeneousTuple,
{
    type Item = T::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let s = self.buf.as_mut();
        if let Some(ref mut item) = s.get_mut(self.cur) {
            self.cur += 1;
            item.take()
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let buffer = &self.buf.as_ref()[self.cur..];
        let len = if buffer.is_empty() {
            0
        } else {
            buffer
                .iter()
                .position(|x| x.is_none())
                .unwrap_or_else(|| buffer.len())
        };
        (len, Some(len))
    }
}

impl<T> ExactSizeIterator for TupleBuffer<T> where T: HomogeneousTuple {}

/// An iterator that groups the items in tuples of a specific size.
///
/// See [`.tuples()`](crate::Itertools::tuples) for more information.
#[derive(Clone, Debug)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct Tuples<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
{
    iter: Fuse<I>,
    buf: T::Buffer,
}

/// Create a new tuples iterator.
pub fn tuples<I, T>(iter: I) -> Tuples<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
{
    Tuples {
        iter: iter.fuse(),
        buf: Default::default(),
    }
}

impl<I, T> Iterator for Tuples<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        T::collect_from_iter(&mut self.iter, &mut self.buf)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        // The number of elts we've drawn from the underlying iterator, but have
        // not yet produced as a tuple.
        let buffered = T::buffer_len(&self.buf);
        // To that, we must add the size estimates of the underlying iterator.
        let (unbuffered_lo, unbuffered_hi) = self.iter.size_hint();
        // The total low estimate is the sum of the already-buffered elements,
        // plus the low estimate of remaining unbuffered elements, divided by
        // the tuple size.
        let total_lo = add_then_div(unbuffered_lo, buffered, T::num_items()).unwrap_or(usize::MAX);
        // And likewise for the total high estimate, but using the high estimate
        // of the remaining unbuffered elements.
        let total_hi = unbuffered_hi.and_then(|hi| add_then_div(hi, buffered, T::num_items()));
        (total_lo, total_hi)
    }
}

/// `(n + a) / d` avoiding overflow when possible, returns `None` if it overflows.
fn add_then_div(n: usize, a: usize, d: usize) -> Option<usize> {
    debug_assert_ne!(d, 0);
    (n / d).checked_add(a / d)?.checked_add((n % d + a % d) / d)
}

impl<I, T> ExactSizeIterator for Tuples<I, T>
where
    I: ExactSizeIterator<Item = T::Item>,
    T: HomogeneousTuple,
{
}

impl<I, T> Tuples<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
{
    /// Return a buffer with the produced items that was not enough to be grouped in a tuple.
    ///
    /// ```
    /// use itertools::Itertools;
    ///
    /// let mut iter = (0..5).tuples();
    /// assert_eq!(Some((0, 1, 2)), iter.next());
    /// assert_eq!(None, iter.next());
    /// itertools::assert_equal(vec![3, 4], iter.into_buffer());
    /// ```
    pub fn into_buffer(self) -> TupleBuffer<T> {
        TupleBuffer::new(self.buf)
    }
}

/// An iterator over all contiguous windows that produces tuples of a specific size.
///
/// See [`.tuple_windows()`](crate::Itertools::tuple_windows) for more
/// information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[derive(Clone, Debug)]
pub struct TupleWindows<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
{
    iter: I,
    last: Option<T>,
}

/// Create a new tuple windows iterator.
pub fn tuple_windows<I, T>(iter: I) -> TupleWindows<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple,
    T::Item: Clone,
{
    TupleWindows { last: None, iter }
}

impl<I, T> Iterator for TupleWindows<I, T>
where
    I: Iterator<Item = T::Item>,
    T: HomogeneousTuple + Clone,
    T::Item: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if T::num_items() == 1 {
            return T::collect_from_iter_no_buf(&mut self.iter);
        }
        if let Some(new) = self.iter.next() {
            if let Some(ref mut last) = self.last {
                last.left_shift_push(new);
                Some(last.clone())
            } else {
                use std::iter::once;
                let iter = once(new).chain(&mut self.iter);
                self.last = T::collect_from_iter_no_buf(iter);
                self.last.clone()
            }
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let mut sh = self.iter.size_hint();
        // Adjust the size hint at the beginning
        // OR when `num_items == 1` (but it does not change the size hint).
        if self.last.is_none() {
            sh = size_hint::sub_scalar(sh, T::num_items() - 1);
        }
        sh
    }
}

impl<I, T> ExactSizeIterator for TupleWindows<I, T>
where
    I: ExactSizeIterator<Item = T::Item>,
    T: HomogeneousTuple + Clone,
    T::Item: Clone,
{
}

impl<I, T> FusedIterator for TupleWindows<I, T>
where
    I: FusedIterator<Item = T::Item>,
    T: HomogeneousTuple + Clone,
    T::Item: Clone,
{
}

/// An iterator over all windows, wrapping back to the first elements when the
/// window would otherwise exceed the length of the iterator, producing tuples
/// of a specific size.
///
/// See [`.circular_tuple_windows()`](crate::Itertools::circular_tuple_windows) for more
/// information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[derive(Debug, Clone)]
pub struct CircularTupleWindows<I, T: Clone>
where
    I: Iterator<Item = T::Item> + Clone,
    T: TupleCollect + Clone,
{
    iter: TupleWindows<Cycle<I>, T>,
    len: usize,
    phantom_data: PhantomData<T>,
}

pub fn circular_tuple_windows<I, T>(iter: I) -> CircularTupleWindows<I, T>
where
    I: Iterator<Item = T::Item> + Clone + ExactSizeIterator,
    T: TupleCollect + Clone,
    T::Item: Clone,
{
    let len = iter.len();
    let iter = tuple_windows(iter.cycle());

    CircularTupleWindows {
        iter,
        len,
        phantom_data: PhantomData {},
    }
}

impl<I, T> Iterator for CircularTupleWindows<I, T>
where
    I: Iterator<Item = T::Item> + Clone,
    T: TupleCollect + Clone,
    T::Item: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.len != 0 {
            self.len -= 1;
            self.iter.next()
        } else {
            None
        }
    }

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

impl<I, T> ExactSizeIterator for CircularTupleWindows<I, T>
where
    I: Iterator<Item = T::Item> + Clone,
    T: TupleCollect + Clone,
    T::Item: Clone,
{
}

impl<I, T> FusedIterator for CircularTupleWindows<I, T>
where
    I: Iterator<Item = T::Item> + Clone,
    T: TupleCollect + Clone,
    T::Item: Clone,
{
}

pub trait TupleCollect: Sized {
    type Item;
    type Buffer: Default + AsRef<[Option<Self::Item>]> + AsMut<[Option<Self::Item>]>;

    fn buffer_len(buf: &Self::Buffer) -> usize {
        let s = buf.as_ref();
        s.iter().position(Option::is_none).unwrap_or(s.len())
    }

    fn collect_from_iter<I>(iter: I, buf: &mut Self::Buffer) -> Option<Self>
    where
        I: IntoIterator<Item = Self::Item>;

    fn collect_from_iter_no_buf<I>(iter: I) -> Option<Self>
    where
        I: IntoIterator<Item = Self::Item>;

    fn num_items() -> usize;

    fn left_shift_push(&mut self, item: Self::Item);
}

macro_rules! rev_for_each_ident{
    ($m:ident, ) => {};
    ($m:ident, $i0:ident, $($i:ident,)*) => {
        rev_for_each_ident!($m, $($i,)*);
        $m!($i0);
    };
}

macro_rules! impl_tuple_collect {
    ($dummy:ident,) => {}; // stop
    ($dummy:ident, $($Y:ident,)*) => (
        impl_tuple_collect!($($Y,)*);
        impl<A> TupleCollect for ($(ignore_ident!($Y, A),)*) {
            type Item = A;
            type Buffer = [Option<A>; count_ident!($($Y)*) - 1];

            #[allow(unused_assignments, unused_mut)]
            fn collect_from_iter<I>(iter: I, buf: &mut Self::Buffer) -> Option<Self>
                where I: IntoIterator<Item = A>
            {
                let mut iter = iter.into_iter();
                $(
                    let mut $Y = None;
                )*

                loop {
                    $(
                        $Y = iter.next();
                        if $Y.is_none() {
                            break
                        }
                    )*
                    return Some(($($Y.unwrap()),*,))
                }

                let mut i = 0;
                let mut s = buf.as_mut();
                $(
                    if i < s.len() {
                        s[i] = $Y;
                        i += 1;
                    }
                )*
                return None;
            }

            fn collect_from_iter_no_buf<I>(iter: I) -> Option<Self>
                where I: IntoIterator<Item = A>
            {
                let mut iter = iter.into_iter();

                Some(($(
                    { let $Y = iter.next()?; $Y },
                )*))
            }

            fn num_items() -> usize {
                count_ident!($($Y)*)
            }

            fn left_shift_push(&mut self, mut item: A) {
                use std::mem::replace;

                let &mut ($(ref mut $Y),*,) = self;
                macro_rules! replace_item{($i:ident) => {
                    item = replace($i, item);
                }}
                rev_for_each_ident!(replace_item, $($Y,)*);
                drop(item);
            }
        }
    )
}
impl_tuple_collect!(dummy, a, b, c, d, e, f, g, h, i, j, k, l,);