Coverage Report

Created: 2025-12-05 07:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/itertools-0.14.0/src/lib.rs
Line
Count
Source
1
#![warn(missing_docs, clippy::default_numeric_fallback)]
2
#![crate_name = "itertools"]
3
#![cfg_attr(not(feature = "use_std"), no_std)]
4
#![doc(test(attr(deny(warnings), allow(deprecated, unstable_name_collisions))))]
5
6
//! Extra iterator adaptors, functions and macros.
7
//!
8
//! To extend [`Iterator`] with methods in this crate, import
9
//! the [`Itertools`] trait:
10
//!
11
//! ```
12
//! # #[allow(unused_imports)]
13
//! use itertools::Itertools;
14
//! ```
15
//!
16
//! Now, new methods like [`interleave`](Itertools::interleave)
17
//! are available on all iterators:
18
//!
19
//! ```
20
//! use itertools::Itertools;
21
//!
22
//! let it = (1..3).interleave(vec![-1, -2]);
23
//! itertools::assert_equal(it, vec![1, -1, 2, -2]);
24
//! ```
25
//!
26
//! Most iterator methods are also provided as functions (with the benefit
27
//! that they convert parameters using [`IntoIterator`]):
28
//!
29
//! ```
30
//! use itertools::interleave;
31
//!
32
//! for elt in interleave(&[1, 2, 3], &[2, 3, 4]) {
33
//!     /* loop body */
34
//!     # let _ = elt;
35
//! }
36
//! ```
37
//!
38
//! ## Crate Features
39
//!
40
//! - `use_std`
41
//!   - Enabled by default.
42
//!   - Disable to compile itertools using `#![no_std]`. This disables
43
//!     any item that depend on allocations (see the `use_alloc` feature)
44
//!     and hash maps (like `unique`, `counts`, `into_grouping_map` and more).
45
//! - `use_alloc`
46
//!   - Enabled by default.
47
//!   - Enables any item that depend on allocations (like `chunk_by`,
48
//!     `kmerge`, `join` and many more).
49
//!
50
//! ## Rust Version
51
//!
52
//! This version of itertools requires Rust 1.63.0 or later.
53
54
#[cfg(not(feature = "use_std"))]
55
extern crate core as std;
56
57
#[cfg(feature = "use_alloc")]
58
extern crate alloc;
59
60
#[cfg(feature = "use_alloc")]
61
use alloc::{collections::VecDeque, string::String, vec::Vec};
62
63
pub use either::Either;
64
65
use core::borrow::Borrow;
66
use std::cmp::Ordering;
67
#[cfg(feature = "use_std")]
68
use std::collections::HashMap;
69
#[cfg(feature = "use_std")]
70
use std::collections::HashSet;
71
use std::fmt;
72
#[cfg(feature = "use_alloc")]
73
use std::fmt::Write;
74
#[cfg(feature = "use_std")]
75
use std::hash::Hash;
76
use std::iter::{once, IntoIterator};
77
#[cfg(feature = "use_alloc")]
78
type VecDequeIntoIter<T> = alloc::collections::vec_deque::IntoIter<T>;
79
#[cfg(feature = "use_alloc")]
80
type VecIntoIter<T> = alloc::vec::IntoIter<T>;
81
use std::iter::FromIterator;
82
83
#[macro_use]
84
mod impl_macros;
85
86
// for compatibility with no std and macros
87
#[doc(hidden)]
88
pub use std::iter as __std_iter;
89
90
/// The concrete iterator types.
91
pub mod structs {
92
    #[cfg(feature = "use_alloc")]
93
    pub use crate::adaptors::MultiProduct;
94
    pub use crate::adaptors::{
95
        Batching, Coalesce, Dedup, DedupBy, DedupByWithCount, DedupWithCount, FilterMapOk,
96
        FilterOk, Interleave, InterleaveShortest, MapInto, MapOk, Positions, Product, PutBack,
97
        TakeWhileRef, TupleCombinations, Update, WhileSome,
98
    };
99
    #[cfg(feature = "use_alloc")]
100
    pub use crate::combinations::{ArrayCombinations, Combinations};
101
    #[cfg(feature = "use_alloc")]
102
    pub use crate::combinations_with_replacement::CombinationsWithReplacement;
103
    pub use crate::cons_tuples_impl::ConsTuples;
104
    #[cfg(feature = "use_std")]
105
    pub use crate::duplicates_impl::{Duplicates, DuplicatesBy};
106
    pub use crate::exactly_one_err::ExactlyOneError;
107
    pub use crate::flatten_ok::FlattenOk;
108
    pub use crate::format::{Format, FormatWith};
109
    #[allow(deprecated)]
110
    #[cfg(feature = "use_alloc")]
111
    pub use crate::groupbylazy::GroupBy;
112
    #[cfg(feature = "use_alloc")]
113
    pub use crate::groupbylazy::{Chunk, ChunkBy, Chunks, Group, Groups, IntoChunks};
114
    #[cfg(feature = "use_std")]
115
    pub use crate::grouping_map::{GroupingMap, GroupingMapBy};
116
    pub use crate::intersperse::{Intersperse, IntersperseWith};
117
    #[cfg(feature = "use_alloc")]
118
    pub use crate::kmerge_impl::{KMerge, KMergeBy};
119
    pub use crate::merge_join::{Merge, MergeBy, MergeJoinBy};
120
    #[cfg(feature = "use_alloc")]
121
    pub use crate::multipeek_impl::MultiPeek;
122
    pub use crate::pad_tail::PadUsing;
123
    #[cfg(feature = "use_alloc")]
124
    pub use crate::peek_nth::PeekNth;
125
    pub use crate::peeking_take_while::PeekingTakeWhile;
126
    #[cfg(feature = "use_alloc")]
127
    pub use crate::permutations::Permutations;
128
    #[cfg(feature = "use_alloc")]
129
    pub use crate::powerset::Powerset;
130
    pub use crate::process_results_impl::ProcessResults;
131
    #[cfg(feature = "use_alloc")]
132
    pub use crate::put_back_n_impl::PutBackN;
133
    #[cfg(feature = "use_alloc")]
134
    pub use crate::rciter_impl::RcIter;
135
    pub use crate::repeatn::RepeatN;
136
    #[allow(deprecated)]
137
    pub use crate::sources::{Iterate, Unfold};
138
    pub use crate::take_while_inclusive::TakeWhileInclusive;
139
    #[cfg(feature = "use_alloc")]
140
    pub use crate::tee::Tee;
141
    pub use crate::tuple_impl::{CircularTupleWindows, TupleBuffer, TupleWindows, Tuples};
142
    #[cfg(feature = "use_std")]
143
    pub use crate::unique_impl::{Unique, UniqueBy};
144
    pub use crate::with_position::WithPosition;
145
    pub use crate::zip_eq_impl::ZipEq;
146
    pub use crate::zip_longest::ZipLongest;
147
    pub use crate::ziptuple::Zip;
148
}
149
150
/// Traits helpful for using certain `Itertools` methods in generic contexts.
151
pub mod traits {
152
    pub use crate::iter_index::IteratorIndex;
153
    pub use crate::tuple_impl::HomogeneousTuple;
154
}
155
156
pub use crate::concat_impl::concat;
157
pub use crate::cons_tuples_impl::cons_tuples;
158
pub use crate::diff::diff_with;
159
pub use crate::diff::Diff;
160
#[cfg(feature = "use_alloc")]
161
pub use crate::kmerge_impl::kmerge_by;
162
pub use crate::minmax::MinMaxResult;
163
pub use crate::peeking_take_while::PeekingNext;
164
pub use crate::process_results_impl::process_results;
165
pub use crate::repeatn::repeat_n;
166
#[allow(deprecated)]
167
pub use crate::sources::{iterate, unfold};
168
#[allow(deprecated)]
169
pub use crate::structs::*;
170
pub use crate::unziptuple::{multiunzip, MultiUnzip};
171
pub use crate::with_position::Position;
172
pub use crate::ziptuple::multizip;
173
mod adaptors;
174
mod either_or_both;
175
pub use crate::either_or_both::EitherOrBoth;
176
#[doc(hidden)]
177
pub mod free;
178
#[doc(inline)]
179
pub use crate::free::*;
180
#[cfg(feature = "use_alloc")]
181
mod combinations;
182
#[cfg(feature = "use_alloc")]
183
mod combinations_with_replacement;
184
mod concat_impl;
185
mod cons_tuples_impl;
186
mod diff;
187
#[cfg(feature = "use_std")]
188
mod duplicates_impl;
189
mod exactly_one_err;
190
#[cfg(feature = "use_alloc")]
191
mod extrema_set;
192
mod flatten_ok;
193
mod format;
194
#[cfg(feature = "use_alloc")]
195
mod group_map;
196
#[cfg(feature = "use_alloc")]
197
mod groupbylazy;
198
#[cfg(feature = "use_std")]
199
mod grouping_map;
200
mod intersperse;
201
mod iter_index;
202
#[cfg(feature = "use_alloc")]
203
mod k_smallest;
204
#[cfg(feature = "use_alloc")]
205
mod kmerge_impl;
206
#[cfg(feature = "use_alloc")]
207
mod lazy_buffer;
208
mod merge_join;
209
mod minmax;
210
#[cfg(feature = "use_alloc")]
211
mod multipeek_impl;
212
mod next_array;
213
mod pad_tail;
214
#[cfg(feature = "use_alloc")]
215
mod peek_nth;
216
mod peeking_take_while;
217
#[cfg(feature = "use_alloc")]
218
mod permutations;
219
#[cfg(feature = "use_alloc")]
220
mod powerset;
221
mod process_results_impl;
222
#[cfg(feature = "use_alloc")]
223
mod put_back_n_impl;
224
#[cfg(feature = "use_alloc")]
225
mod rciter_impl;
226
mod repeatn;
227
mod size_hint;
228
mod sources;
229
mod take_while_inclusive;
230
#[cfg(feature = "use_alloc")]
231
mod tee;
232
mod tuple_impl;
233
#[cfg(feature = "use_std")]
234
mod unique_impl;
235
mod unziptuple;
236
mod with_position;
237
mod zip_eq_impl;
238
mod zip_longest;
239
mod ziptuple;
240
241
#[macro_export]
242
/// Create an iterator over the “cartesian product” of iterators.
243
///
244
/// Iterator element type is like `(A, B, ..., E)` if formed
245
/// from iterators `(I, J, ..., M)` with element types `I::Item = A`, `J::Item = B`, etc.
246
///
247
/// ```
248
/// # use itertools::iproduct;
249
/// #
250
/// # fn main() {
251
/// // Iterate over the coordinates of a 4 x 4 x 4 grid
252
/// // from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
253
/// for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
254
///    // ..
255
///    # let _ = (i, j, k);
256
/// }
257
/// # }
258
/// ```
259
macro_rules! iproduct {
260
    (@flatten $I:expr,) => (
261
        $I
262
    );
263
    (@flatten $I:expr, $J:expr, $($K:expr,)*) => (
264
        $crate::iproduct!(@flatten $crate::cons_tuples($crate::iproduct!($I, $J)), $($K,)*)
265
    );
266
    () => (
267
        $crate::__std_iter::once(())
268
    );
269
    ($I:expr $(,)?) => (
270
        $crate::__std_iter::Iterator::map(
271
            $crate::__std_iter::IntoIterator::into_iter($I),
272
            |elt| (elt,)
273
        )
274
    );
275
    ($I:expr, $J:expr $(,)?) => (
276
        $crate::Itertools::cartesian_product(
277
            $crate::__std_iter::IntoIterator::into_iter($I),
278
            $crate::__std_iter::IntoIterator::into_iter($J),
279
        )
280
    );
281
    ($I:expr, $J:expr, $($K:expr),+ $(,)?) => (
282
        $crate::iproduct!(@flatten $crate::iproduct!($I, $J), $($K,)+)
283
    );
284
}
285
286
#[macro_export]
287
/// Create an iterator running multiple iterators in lockstep.
288
///
289
/// The `izip!` iterator yields elements until any subiterator
290
/// returns `None`.
291
///
292
/// This is a version of the standard ``.zip()`` that's supporting more than
293
/// two iterators. The iterator element type is a tuple with one element
294
/// from each of the input iterators. Just like ``.zip()``, the iteration stops
295
/// when the shortest of the inputs reaches its end.
296
///
297
/// **Note:** The result of this macro is in the general case an iterator
298
/// composed of repeated `.zip()` and a `.map()`; it has an anonymous type.
299
/// The special cases of one and two arguments produce the equivalent of
300
/// `$a.into_iter()` and `$a.into_iter().zip($b)` respectively.
301
///
302
/// Prefer this macro `izip!()` over [`multizip`] for the performance benefits
303
/// of using the standard library `.zip()`.
304
///
305
/// ```
306
/// # use itertools::izip;
307
/// #
308
/// # fn main() {
309
///
310
/// // iterate over three sequences side-by-side
311
/// let mut results = [0, 0, 0, 0];
312
/// let inputs = [3, 7, 9, 6];
313
///
314
/// for (r, index, input) in izip!(&mut results, 0..10, &inputs) {
315
///     *r = index * 10 + input;
316
/// }
317
///
318
/// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]);
319
/// # }
320
/// ```
321
macro_rules! izip {
322
    // @closure creates a tuple-flattening closure for .map() call. usage:
323
    // @closure partial_pattern => partial_tuple , rest , of , iterators
324
    // eg. izip!( @closure ((a, b), c) => (a, b, c) , dd , ee )
325
    ( @closure $p:pat => $tup:expr ) => {
326
        |$p| $tup
327
    };
328
329
    // The "b" identifier is a different identifier on each recursion level thanks to hygiene.
330
    ( @closure $p:pat => ( $($tup:tt)* ) , $_iter:expr $( , $tail:expr )* ) => {
331
0
        $crate::izip!(@closure ($p, b) => ( $($tup)*, b ) $( , $tail )*)
Unexecuted instantiation: rav1e::activity::variance_8x8::<u16>::{closure#0}
Unexecuted instantiation: rav1e::rdo::inter_frame_rdo_mode_decision::<u16>::{closure#4}
Unexecuted instantiation: rav1e::rdo::inter_frame_rdo_mode_decision::<u8>::{closure#4}
Unexecuted instantiation: rav1e::activity::variance_8x8::<u8>::{closure#0}
332
    };
333
334
    // unary
335
    ($first:expr $(,)*) => {
336
        $crate::__std_iter::IntoIterator::into_iter($first)
337
    };
338
339
    // binary
340
    ($first:expr, $second:expr $(,)*) => {
341
        $crate::__std_iter::Iterator::zip(
342
            $crate::__std_iter::IntoIterator::into_iter($first),
343
            $second,
344
        )
345
    };
346
347
    // n-ary where n > 2
348
    ( $first:expr $( , $rest:expr )* $(,)* ) => {
349
        {
350
            let iter = $crate::__std_iter::IntoIterator::into_iter($first);
351
            $(
352
                let iter = $crate::__std_iter::Iterator::zip(iter, $rest);
353
            )*
354
            $crate::__std_iter::Iterator::map(
355
                iter,
356
                $crate::izip!(@closure a => (a) $( , $rest )*)
357
            )
358
        }
359
    };
360
}
361
362
#[macro_export]
363
/// [Chain][`chain`] zero or more iterators together into one sequence.
364
///
365
/// The comma-separated arguments must implement [`IntoIterator`].
366
/// The final argument may be followed by a trailing comma.
367
///
368
/// [`chain`]: Iterator::chain
369
///
370
/// # Examples
371
///
372
/// Empty invocations of `chain!` expand to an invocation of [`std::iter::empty`]:
373
/// ```
374
/// use std::iter;
375
/// use itertools::chain;
376
///
377
/// let _: iter::Empty<()> = chain!();
378
/// let _: iter::Empty<i8> = chain!();
379
/// ```
380
///
381
/// Invocations of `chain!` with one argument expand to [`arg.into_iter()`](IntoIterator):
382
/// ```
383
/// use std::ops::Range;
384
/// use itertools::chain;
385
/// let _: <Range<_> as IntoIterator>::IntoIter = chain!(2..6,); // trailing comma optional!
386
/// let _:     <&[_] as IntoIterator>::IntoIter = chain!(&[2, 3, 4]);
387
/// ```
388
///
389
/// Invocations of `chain!` with multiple arguments [`.into_iter()`](IntoIterator) each
390
/// argument, and then [`chain`] them together:
391
/// ```
392
/// use std::{iter::*, slice};
393
/// use itertools::{assert_equal, chain};
394
///
395
/// // e.g., this:
396
/// let with_macro:  Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
397
///     chain![once(&0), repeat(&1).take(2), &[2, 3, 5],];
398
///
399
/// // ...is equivalent to this:
400
/// let with_method: Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
401
///     once(&0)
402
///         .chain(repeat(&1).take(2))
403
///         .chain(&[2, 3, 5]);
404
///
405
/// assert_equal(with_macro, with_method);
406
/// ```
407
macro_rules! chain {
408
    () => {
409
        $crate::__std_iter::empty()
410
    };
411
    ($first:expr $(, $rest:expr )* $(,)?) => {
412
        {
413
            let iter = $crate::__std_iter::IntoIterator::into_iter($first);
414
            $(
415
                let iter =
416
                    $crate::__std_iter::Iterator::chain(
417
                        iter,
418
                        $crate::__std_iter::IntoIterator::into_iter($rest));
419
            )*
420
            iter
421
        }
422
    };
423
}
424
425
/// An [`Iterator`] blanket implementation that provides extra adaptors and
426
/// methods.
427
///
428
/// This trait defines a number of methods. They are divided into two groups:
429
///
430
/// * *Adaptors* take an iterator and parameter as input, and return
431
///   a new iterator value. These are listed first in the trait. An example
432
///   of an adaptor is [`.interleave()`](Itertools::interleave)
433
///
434
/// * *Regular methods* are those that don't return iterators and instead
435
///   return a regular value of some other kind.
436
///   [`.next_tuple()`](Itertools::next_tuple) is an example and the first regular
437
///   method in the list.
438
pub trait Itertools: Iterator {
439
    // adaptors
440
441
    /// Alternate elements from two iterators until both have run out.
442
    ///
443
    /// Iterator element type is `Self::Item`.
444
    ///
445
    /// This iterator is *fused*.
446
    ///
447
    /// ```
448
    /// use itertools::Itertools;
449
    ///
450
    /// let it = (1..7).interleave(vec![-1, -2]);
451
    /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
452
    /// ```
453
0
    fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter>
454
0
    where
455
0
        J: IntoIterator<Item = Self::Item>,
456
0
        Self: Sized,
457
    {
458
0
        interleave(self, other)
459
0
    }
460
461
    /// Alternate elements from two iterators until at least one of them has run
462
    /// out.
463
    ///
464
    /// Iterator element type is `Self::Item`.
465
    ///
466
    /// ```
467
    /// use itertools::Itertools;
468
    ///
469
    /// let it = (1..7).interleave_shortest(vec![-1, -2]);
470
    /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]);
471
    /// ```
472
0
    fn interleave_shortest<J>(self, other: J) -> InterleaveShortest<Self, J::IntoIter>
473
0
    where
474
0
        J: IntoIterator<Item = Self::Item>,
475
0
        Self: Sized,
476
    {
477
0
        adaptors::interleave_shortest(self, other.into_iter())
478
0
    }
479
480
    /// An iterator adaptor to insert a particular value
481
    /// between each element of the adapted iterator.
482
    ///
483
    /// Iterator element type is `Self::Item`.
484
    ///
485
    /// This iterator is *fused*.
486
    ///
487
    /// ```
488
    /// use itertools::Itertools;
489
    ///
490
    /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]);
491
    /// ```
492
0
    fn intersperse(self, element: Self::Item) -> Intersperse<Self>
493
0
    where
494
0
        Self: Sized,
495
0
        Self::Item: Clone,
496
    {
497
0
        intersperse::intersperse(self, element)
498
0
    }
499
500
    /// An iterator adaptor to insert a particular value created by a function
501
    /// between each element of the adapted iterator.
502
    ///
503
    /// Iterator element type is `Self::Item`.
504
    ///
505
    /// This iterator is *fused*.
506
    ///
507
    /// ```
508
    /// use itertools::Itertools;
509
    ///
510
    /// let mut i = 10;
511
    /// itertools::assert_equal((0..3).intersperse_with(|| { i -= 1; i }), vec![0, 9, 1, 8, 2]);
512
    /// assert_eq!(i, 8);
513
    /// ```
514
0
    fn intersperse_with<F>(self, element: F) -> IntersperseWith<Self, F>
515
0
    where
516
0
        Self: Sized,
517
0
        F: FnMut() -> Self::Item,
518
    {
519
0
        intersperse::intersperse_with(self, element)
520
0
    }
521
522
    /// Returns an iterator over a subsection of the iterator.
523
    ///
524
    /// Works similarly to [`slice::get`](https://doc.rust-lang.org/std/primitive.slice.html#method.get).
525
    ///
526
    /// **Panics** for ranges `..=usize::MAX` and `0..=usize::MAX`.
527
    ///
528
    /// It's a generalisation of [`Iterator::take`] and [`Iterator::skip`],
529
    /// and uses these under the hood.
530
    /// Therefore, the resulting iterator is:
531
    /// - [`ExactSizeIterator`] if the adapted iterator is [`ExactSizeIterator`].
532
    /// - [`DoubleEndedIterator`] if the adapted iterator is [`DoubleEndedIterator`] and [`ExactSizeIterator`].
533
    ///
534
    /// # Unspecified Behavior
535
    /// The result of indexing with an exhausted [`core::ops::RangeInclusive`] is unspecified.
536
    ///
537
    /// # Examples
538
    ///
539
    /// ```
540
    /// use itertools::Itertools;
541
    ///
542
    /// let vec = vec![3, 1, 4, 1, 5];
543
    ///
544
    /// let mut range: Vec<_> =
545
    ///         vec.iter().get(1..=3).copied().collect();
546
    /// assert_eq!(&range, &[1, 4, 1]);
547
    ///
548
    /// // It works with other types of ranges, too
549
    /// range = vec.iter().get(..2).copied().collect();
550
    /// assert_eq!(&range, &[3, 1]);
551
    ///
552
    /// range = vec.iter().get(0..1).copied().collect();
553
    /// assert_eq!(&range, &[3]);
554
    ///
555
    /// range = vec.iter().get(2..).copied().collect();
556
    /// assert_eq!(&range, &[4, 1, 5]);
557
    ///
558
    /// range = vec.iter().get(..=2).copied().collect();
559
    /// assert_eq!(&range, &[3, 1, 4]);
560
    ///
561
    /// range = vec.iter().get(..).copied().collect();
562
    /// assert_eq!(range, vec);
563
    /// ```
564
0
    fn get<R>(self, index: R) -> R::Output
565
0
    where
566
0
        Self: Sized,
567
0
        R: traits::IteratorIndex<Self>,
568
    {
569
0
        iter_index::get(self, index)
570
0
    }
571
572
    /// Create an iterator which iterates over both this and the specified
573
    /// iterator simultaneously, yielding pairs of two optional elements.
574
    ///
575
    /// This iterator is *fused*.
576
    ///
577
    /// As long as neither input iterator is exhausted yet, it yields two values
578
    /// via `EitherOrBoth::Both`.
579
    ///
580
    /// When the parameter iterator is exhausted, it only yields a value from the
581
    /// `self` iterator via `EitherOrBoth::Left`.
582
    ///
583
    /// When the `self` iterator is exhausted, it only yields a value from the
584
    /// parameter iterator via `EitherOrBoth::Right`.
585
    ///
586
    /// When both iterators return `None`, all further invocations of `.next()`
587
    /// will return `None`.
588
    ///
589
    /// Iterator element type is
590
    /// [`EitherOrBoth<Self::Item, J::Item>`](EitherOrBoth).
591
    ///
592
    /// ```rust
593
    /// use itertools::EitherOrBoth::{Both, Right};
594
    /// use itertools::Itertools;
595
    /// let it = (0..1).zip_longest(1..3);
596
    /// itertools::assert_equal(it, vec![Both(0, 1), Right(2)]);
597
    /// ```
598
    #[inline]
599
0
    fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter>
600
0
    where
601
0
        J: IntoIterator,
602
0
        Self: Sized,
603
    {
604
0
        zip_longest::zip_longest(self, other.into_iter())
605
0
    }
606
607
    /// Create an iterator which iterates over both this and the specified
608
    /// iterator simultaneously, yielding pairs of elements.
609
    ///
610
    /// **Panics** if the iterators reach an end and they are not of equal
611
    /// lengths.
612
    #[inline]
613
0
    fn zip_eq<J>(self, other: J) -> ZipEq<Self, J::IntoIter>
614
0
    where
615
0
        J: IntoIterator,
616
0
        Self: Sized,
617
    {
618
0
        zip_eq(self, other)
619
0
    }
620
621
    /// A “meta iterator adaptor”. Its closure receives a reference to the
622
    /// iterator and may pick off as many elements as it likes, to produce the
623
    /// next iterator element.
624
    ///
625
    /// Iterator element type is `B`.
626
    ///
627
    /// ```
628
    /// use itertools::Itertools;
629
    ///
630
    /// // An adaptor that gathers elements in pairs
631
    /// let pit = (0..4).batching(|it| {
632
    ///            match it.next() {
633
    ///                None => None,
634
    ///                Some(x) => match it.next() {
635
    ///                    None => None,
636
    ///                    Some(y) => Some((x, y)),
637
    ///                }
638
    ///            }
639
    ///        });
640
    ///
641
    /// itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
642
    /// ```
643
    ///
644
0
    fn batching<B, F>(self, f: F) -> Batching<Self, F>
645
0
    where
646
0
        F: FnMut(&mut Self) -> Option<B>,
647
0
        Self: Sized,
648
    {
649
0
        adaptors::batching(self, f)
650
0
    }
651
652
    /// Return an *iterable* that can group iterator elements.
653
    /// Consecutive elements that map to the same key (“runs”), are assigned
654
    /// to the same group.
655
    ///
656
    /// `ChunkBy` is the storage for the lazy grouping operation.
657
    ///
658
    /// If the groups are consumed in order, or if each group's iterator is
659
    /// dropped without keeping it around, then `ChunkBy` uses no
660
    /// allocations.  It needs allocations only if several group iterators
661
    /// are alive at the same time.
662
    ///
663
    /// This type implements [`IntoIterator`] (it is **not** an iterator
664
    /// itself), because the group iterators need to borrow from this
665
    /// value. It should be stored in a local variable or temporary and
666
    /// iterated.
667
    ///
668
    /// Iterator element type is `(K, Group)`: the group's key and the
669
    /// group iterator.
670
    ///
671
    /// ```
672
    /// use itertools::Itertools;
673
    ///
674
    /// // chunk data into runs of larger than zero or not.
675
    /// let data = vec![1, 3, -2, -2, 1, 0, 1, 2];
676
    /// // chunks:     |---->|------>|--------->|
677
    ///
678
    /// // Note: The `&` is significant here, `ChunkBy` is iterable
679
    /// // only by reference. You can also call `.into_iter()` explicitly.
680
    /// let mut data_grouped = Vec::new();
681
    /// for (key, chunk) in &data.into_iter().chunk_by(|elt| *elt >= 0) {
682
    ///     data_grouped.push((key, chunk.collect()));
683
    /// }
684
    /// assert_eq!(data_grouped, vec![(true, vec![1, 3]), (false, vec![-2, -2]), (true, vec![1, 0, 1, 2])]);
685
    /// ```
686
    #[cfg(feature = "use_alloc")]
687
0
    fn chunk_by<K, F>(self, key: F) -> ChunkBy<K, Self, F>
688
0
    where
689
0
        Self: Sized,
690
0
        F: FnMut(&Self::Item) -> K,
691
0
        K: PartialEq,
692
    {
693
0
        groupbylazy::new(self, key)
694
0
    }
695
696
    /// See [`.chunk_by()`](Itertools::chunk_by).
697
    #[deprecated(note = "Use .chunk_by() instead", since = "0.13.0")]
698
    #[cfg(feature = "use_alloc")]
699
0
    fn group_by<K, F>(self, key: F) -> ChunkBy<K, Self, F>
700
0
    where
701
0
        Self: Sized,
702
0
        F: FnMut(&Self::Item) -> K,
703
0
        K: PartialEq,
704
    {
705
0
        self.chunk_by(key)
706
0
    }
707
708
    /// Return an *iterable* that can chunk the iterator.
709
    ///
710
    /// Yield subiterators (chunks) that each yield a fixed number elements,
711
    /// determined by `size`. The last chunk will be shorter if there aren't
712
    /// enough elements.
713
    ///
714
    /// `IntoChunks` is based on `ChunkBy`: it is iterable (implements
715
    /// `IntoIterator`, **not** `Iterator`), and it only buffers if several
716
    /// chunk iterators are alive at the same time.
717
    ///
718
    /// Iterator element type is `Chunk`, each chunk's iterator.
719
    ///
720
    /// **Panics** if `size` is 0.
721
    ///
722
    /// ```
723
    /// use itertools::Itertools;
724
    ///
725
    /// let data = vec![1, 1, 2, -2, 6, 0, 3, 1];
726
    /// //chunk size=3 |------->|-------->|--->|
727
    ///
728
    /// // Note: The `&` is significant here, `IntoChunks` is iterable
729
    /// // only by reference. You can also call `.into_iter()` explicitly.
730
    /// for chunk in &data.into_iter().chunks(3) {
731
    ///     // Check that the sum of each chunk is 4.
732
    ///     assert_eq!(4, chunk.sum());
733
    /// }
734
    /// ```
735
    #[cfg(feature = "use_alloc")]
736
0
    fn chunks(self, size: usize) -> IntoChunks<Self>
737
0
    where
738
0
        Self: Sized,
739
    {
740
0
        assert!(size != 0);
741
0
        groupbylazy::new_chunks(self, size)
742
0
    }
743
744
    /// Return an iterator over all contiguous windows producing tuples of
745
    /// a specific size (up to 12).
746
    ///
747
    /// `tuple_windows` clones the iterator elements so that they can be
748
    /// part of successive windows, this makes it most suited for iterators
749
    /// of references and other values that are cheap to copy.
750
    ///
751
    /// ```
752
    /// use itertools::Itertools;
753
    /// let mut v = Vec::new();
754
    ///
755
    /// // pairwise iteration
756
    /// for (a, b) in (1..5).tuple_windows() {
757
    ///     v.push((a, b));
758
    /// }
759
    /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4)]);
760
    ///
761
    /// let mut it = (1..5).tuple_windows();
762
    /// assert_eq!(Some((1, 2, 3)), it.next());
763
    /// assert_eq!(Some((2, 3, 4)), it.next());
764
    /// assert_eq!(None, it.next());
765
    ///
766
    /// // this requires a type hint
767
    /// let it = (1..5).tuple_windows::<(_, _, _)>();
768
    /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
769
    ///
770
    /// // you can also specify the complete type
771
    /// use itertools::TupleWindows;
772
    /// use std::ops::Range;
773
    ///
774
    /// let it: TupleWindows<Range<u32>, (u32, u32, u32)> = (1..5).tuple_windows();
775
    /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
776
    /// ```
777
0
    fn tuple_windows<T>(self) -> TupleWindows<Self, T>
778
0
    where
779
0
        Self: Sized + Iterator<Item = T::Item>,
780
0
        T: traits::HomogeneousTuple,
781
0
        T::Item: Clone,
782
    {
783
0
        tuple_impl::tuple_windows(self)
784
0
    }
785
786
    /// Return an iterator over all windows, wrapping back to the first
787
    /// elements when the window would otherwise exceed the length of the
788
    /// iterator, producing tuples of a specific size (up to 12).
789
    ///
790
    /// `circular_tuple_windows` clones the iterator elements so that they can be
791
    /// part of successive windows, this makes it most suited for iterators
792
    /// of references and other values that are cheap to copy.
793
    ///
794
    /// ```
795
    /// use itertools::Itertools;
796
    /// let mut v = Vec::new();
797
    /// for (a, b) in (1..5).circular_tuple_windows() {
798
    ///     v.push((a, b));
799
    /// }
800
    /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4), (4, 1)]);
801
    ///
802
    /// let mut it = (1..5).circular_tuple_windows();
803
    /// assert_eq!(Some((1, 2, 3)), it.next());
804
    /// assert_eq!(Some((2, 3, 4)), it.next());
805
    /// assert_eq!(Some((3, 4, 1)), it.next());
806
    /// assert_eq!(Some((4, 1, 2)), it.next());
807
    /// assert_eq!(None, it.next());
808
    ///
809
    /// // this requires a type hint
810
    /// let it = (1..5).circular_tuple_windows::<(_, _, _)>();
811
    /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)]);
812
    /// ```
813
0
    fn circular_tuple_windows<T>(self) -> CircularTupleWindows<Self, T>
814
0
    where
815
0
        Self: Sized + Clone + Iterator<Item = T::Item> + ExactSizeIterator,
816
0
        T: tuple_impl::TupleCollect + Clone,
817
0
        T::Item: Clone,
818
    {
819
0
        tuple_impl::circular_tuple_windows(self)
820
0
    }
821
    /// Return an iterator that groups the items in tuples of a specific size
822
    /// (up to 12).
823
    ///
824
    /// See also the method [`.next_tuple()`](Itertools::next_tuple).
825
    ///
826
    /// ```
827
    /// use itertools::Itertools;
828
    /// let mut v = Vec::new();
829
    /// for (a, b) in (1..5).tuples() {
830
    ///     v.push((a, b));
831
    /// }
832
    /// assert_eq!(v, vec![(1, 2), (3, 4)]);
833
    ///
834
    /// let mut it = (1..7).tuples();
835
    /// assert_eq!(Some((1, 2, 3)), it.next());
836
    /// assert_eq!(Some((4, 5, 6)), it.next());
837
    /// assert_eq!(None, it.next());
838
    ///
839
    /// // this requires a type hint
840
    /// let it = (1..7).tuples::<(_, _, _)>();
841
    /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
842
    ///
843
    /// // you can also specify the complete type
844
    /// use itertools::Tuples;
845
    /// use std::ops::Range;
846
    ///
847
    /// let it: Tuples<Range<u32>, (u32, u32, u32)> = (1..7).tuples();
848
    /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
849
    /// ```
850
    ///
851
    /// See also [`Tuples::into_buffer`].
852
0
    fn tuples<T>(self) -> Tuples<Self, T>
853
0
    where
854
0
        Self: Sized + Iterator<Item = T::Item>,
855
0
        T: traits::HomogeneousTuple,
856
    {
857
0
        tuple_impl::tuples(self)
858
0
    }
859
860
    /// Split into an iterator pair that both yield all elements from
861
    /// the original iterator.
862
    ///
863
    /// **Note:** If the iterator is clonable, prefer using that instead
864
    /// of using this method. Cloning is likely to be more efficient.
865
    ///
866
    /// Iterator element type is `Self::Item`.
867
    ///
868
    /// ```
869
    /// use itertools::Itertools;
870
    /// let xs = vec![0, 1, 2, 3];
871
    ///
872
    /// let (mut t1, t2) = xs.into_iter().tee();
873
    /// itertools::assert_equal(t1.next(), Some(0));
874
    /// itertools::assert_equal(t2, 0..4);
875
    /// itertools::assert_equal(t1, 1..4);
876
    /// ```
877
    #[cfg(feature = "use_alloc")]
878
0
    fn tee(self) -> (Tee<Self>, Tee<Self>)
879
0
    where
880
0
        Self: Sized,
881
0
        Self::Item: Clone,
882
    {
883
0
        tee::new(self)
884
0
    }
885
886
    /// Convert each item of the iterator using the [`Into`] trait.
887
    ///
888
    /// ```rust
889
    /// use itertools::Itertools;
890
    ///
891
    /// (1i32..42i32).map_into::<f64>().collect_vec();
892
    /// ```
893
0
    fn map_into<R>(self) -> MapInto<Self, R>
894
0
    where
895
0
        Self: Sized,
896
0
        Self::Item: Into<R>,
897
    {
898
0
        adaptors::map_into(self)
899
0
    }
900
901
    /// Return an iterator adaptor that applies the provided closure
902
    /// to every `Result::Ok` value. `Result::Err` values are
903
    /// unchanged.
904
    ///
905
    /// ```
906
    /// use itertools::Itertools;
907
    ///
908
    /// let input = vec![Ok(41), Err(false), Ok(11)];
909
    /// let it = input.into_iter().map_ok(|i| i + 1);
910
    /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
911
    /// ```
912
0
    fn map_ok<F, T, U, E>(self, f: F) -> MapOk<Self, F>
913
0
    where
914
0
        Self: Iterator<Item = Result<T, E>> + Sized,
915
0
        F: FnMut(T) -> U,
916
    {
917
0
        adaptors::map_ok(self, f)
918
0
    }
919
920
    /// Return an iterator adaptor that filters every `Result::Ok`
921
    /// value with the provided closure. `Result::Err` values are
922
    /// unchanged.
923
    ///
924
    /// ```
925
    /// use itertools::Itertools;
926
    ///
927
    /// let input = vec![Ok(22), Err(false), Ok(11)];
928
    /// let it = input.into_iter().filter_ok(|&i| i > 20);
929
    /// itertools::assert_equal(it, vec![Ok(22), Err(false)]);
930
    /// ```
931
0
    fn filter_ok<F, T, E>(self, f: F) -> FilterOk<Self, F>
932
0
    where
933
0
        Self: Iterator<Item = Result<T, E>> + Sized,
934
0
        F: FnMut(&T) -> bool,
935
    {
936
0
        adaptors::filter_ok(self, f)
937
0
    }
938
939
    /// Return an iterator adaptor that filters and transforms every
940
    /// `Result::Ok` value with the provided closure. `Result::Err`
941
    /// values are unchanged.
942
    ///
943
    /// ```
944
    /// use itertools::Itertools;
945
    ///
946
    /// let input = vec![Ok(22), Err(false), Ok(11)];
947
    /// let it = input.into_iter().filter_map_ok(|i| if i > 20 { Some(i * 2) } else { None });
948
    /// itertools::assert_equal(it, vec![Ok(44), Err(false)]);
949
    /// ```
950
0
    fn filter_map_ok<F, T, U, E>(self, f: F) -> FilterMapOk<Self, F>
951
0
    where
952
0
        Self: Iterator<Item = Result<T, E>> + Sized,
953
0
        F: FnMut(T) -> Option<U>,
954
    {
955
0
        adaptors::filter_map_ok(self, f)
956
0
    }
957
958
    /// Return an iterator adaptor that flattens every `Result::Ok` value into
959
    /// a series of `Result::Ok` values. `Result::Err` values are unchanged.
960
    ///
961
    /// This is useful when you have some common error type for your crate and
962
    /// need to propagate it upwards, but the `Result::Ok` case needs to be flattened.
963
    ///
964
    /// ```
965
    /// use itertools::Itertools;
966
    ///
967
    /// let input = vec![Ok(0..2), Err(false), Ok(2..4)];
968
    /// let it = input.iter().cloned().flatten_ok();
969
    /// itertools::assert_equal(it.clone(), vec![Ok(0), Ok(1), Err(false), Ok(2), Ok(3)]);
970
    ///
971
    /// // This can also be used to propagate errors when collecting.
972
    /// let output_result: Result<Vec<i32>, bool> = it.collect();
973
    /// assert_eq!(output_result, Err(false));
974
    /// ```
975
0
    fn flatten_ok<T, E>(self) -> FlattenOk<Self, T, E>
976
0
    where
977
0
        Self: Iterator<Item = Result<T, E>> + Sized,
978
0
        T: IntoIterator,
979
    {
980
0
        flatten_ok::flatten_ok(self)
981
0
    }
982
983
    /// “Lift” a function of the values of the current iterator so as to process
984
    /// an iterator of `Result` values instead.
985
    ///
986
    /// `processor` is a closure that receives an adapted version of the iterator
987
    /// as the only argument — the adapted iterator produces elements of type `T`,
988
    /// as long as the original iterator produces `Ok` values.
989
    ///
990
    /// If the original iterable produces an error at any point, the adapted
991
    /// iterator ends and it will return the error iself.
992
    ///
993
    /// Otherwise, the return value from the closure is returned wrapped
994
    /// inside `Ok`.
995
    ///
996
    /// # Example
997
    ///
998
    /// ```
999
    /// use itertools::Itertools;
1000
    ///
1001
    /// type Item = Result<i32, &'static str>;
1002
    ///
1003
    /// let first_values: Vec<Item> = vec![Ok(1), Ok(0), Ok(3)];
1004
    /// let second_values: Vec<Item> = vec![Ok(2), Ok(1), Err("overflow")];
1005
    ///
1006
    /// // “Lift” the iterator .max() method to work on the Ok-values.
1007
    /// let first_max = first_values.into_iter().process_results(|iter| iter.max().unwrap_or(0));
1008
    /// let second_max = second_values.into_iter().process_results(|iter| iter.max().unwrap_or(0));
1009
    ///
1010
    /// assert_eq!(first_max, Ok(3));
1011
    /// assert!(second_max.is_err());
1012
    /// ```
1013
0
    fn process_results<F, T, E, R>(self, processor: F) -> Result<R, E>
1014
0
    where
1015
0
        Self: Iterator<Item = Result<T, E>> + Sized,
1016
0
        F: FnOnce(ProcessResults<Self, E>) -> R,
1017
    {
1018
0
        process_results(self, processor)
1019
0
    }
1020
1021
    /// Return an iterator adaptor that merges the two base iterators in
1022
    /// ascending order.  If both base iterators are sorted (ascending), the
1023
    /// result is sorted.
1024
    ///
1025
    /// Iterator element type is `Self::Item`.
1026
    ///
1027
    /// ```
1028
    /// use itertools::Itertools;
1029
    ///
1030
    /// let a = (0..11).step_by(3);
1031
    /// let b = (0..11).step_by(5);
1032
    /// let it = a.merge(b);
1033
    /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]);
1034
    /// ```
1035
0
    fn merge<J>(self, other: J) -> Merge<Self, J::IntoIter>
1036
0
    where
1037
0
        Self: Sized,
1038
0
        Self::Item: PartialOrd,
1039
0
        J: IntoIterator<Item = Self::Item>,
1040
    {
1041
0
        merge(self, other)
1042
0
    }
1043
1044
    /// Return an iterator adaptor that merges the two base iterators in order.
1045
    /// This is much like [`.merge()`](Itertools::merge) but allows for a custom ordering.
1046
    ///
1047
    /// This can be especially useful for sequences of tuples.
1048
    ///
1049
    /// Iterator element type is `Self::Item`.
1050
    ///
1051
    /// ```
1052
    /// use itertools::Itertools;
1053
    ///
1054
    /// let a = (0..).zip("bc".chars());
1055
    /// let b = (0..).zip("ad".chars());
1056
    /// let it = a.merge_by(b, |x, y| x.1 <= y.1);
1057
    /// itertools::assert_equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]);
1058
    /// ```
1059
0
    fn merge_by<J, F>(self, other: J, is_first: F) -> MergeBy<Self, J::IntoIter, F>
1060
0
    where
1061
0
        Self: Sized,
1062
0
        J: IntoIterator<Item = Self::Item>,
1063
0
        F: FnMut(&Self::Item, &Self::Item) -> bool,
1064
    {
1065
0
        merge_join::merge_by_new(self, other, is_first)
1066
0
    }
1067
1068
    /// Create an iterator that merges items from both this and the specified
1069
    /// iterator in ascending order.
1070
    ///
1071
    /// The function can either return an `Ordering` variant or a boolean.
1072
    ///
1073
    /// If `cmp_fn` returns `Ordering`,
1074
    /// it chooses whether to pair elements based on the `Ordering` returned by the
1075
    /// specified compare function. At any point, inspecting the tip of the
1076
    /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
1077
    /// `J::Item` respectively, the resulting iterator will:
1078
    ///
1079
    /// - Emit `EitherOrBoth::Left(i)` when `i < j`,
1080
    ///   and remove `i` from its source iterator
1081
    /// - Emit `EitherOrBoth::Right(j)` when `i > j`,
1082
    ///   and remove `j` from its source iterator
1083
    /// - Emit `EitherOrBoth::Both(i, j)` when  `i == j`,
1084
    ///   and remove both `i` and `j` from their respective source iterators
1085
    ///
1086
    /// ```
1087
    /// use itertools::Itertools;
1088
    /// use itertools::EitherOrBoth::{Left, Right, Both};
1089
    ///
1090
    /// let a = vec![0, 2, 4, 6, 1].into_iter();
1091
    /// let b = (0..10).step_by(3);
1092
    ///
1093
    /// itertools::assert_equal(
1094
    ///     // This performs a diff in the style of the Unix command comm(1),
1095
    ///     // generalized to arbitrary types rather than text.
1096
    ///     a.merge_join_by(b, Ord::cmp),
1097
    ///     vec![Both(0, 0), Left(2), Right(3), Left(4), Both(6, 6), Left(1), Right(9)]
1098
    /// );
1099
    /// ```
1100
    ///
1101
    /// If `cmp_fn` returns `bool`,
1102
    /// it chooses whether to pair elements based on the boolean returned by the
1103
    /// specified function. At any point, inspecting the tip of the
1104
    /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
1105
    /// `J::Item` respectively, the resulting iterator will:
1106
    ///
1107
    /// - Emit `Either::Left(i)` when `true`,
1108
    ///   and remove `i` from its source iterator
1109
    /// - Emit `Either::Right(j)` when `false`,
1110
    ///   and remove `j` from its source iterator
1111
    ///
1112
    /// It is similar to the `Ordering` case if the first argument is considered
1113
    /// "less" than the second argument.
1114
    ///
1115
    /// ```
1116
    /// use itertools::Itertools;
1117
    /// use itertools::Either::{Left, Right};
1118
    ///
1119
    /// let a = vec![0, 2, 4, 6, 1].into_iter();
1120
    /// let b = (0..10).step_by(3);
1121
    ///
1122
    /// itertools::assert_equal(
1123
    ///     a.merge_join_by(b, |i, j| i <= j),
1124
    ///     vec![Left(0), Right(0), Left(2), Right(3), Left(4), Left(6), Left(1), Right(6), Right(9)]
1125
    /// );
1126
    /// ```
1127
    #[inline]
1128
    #[doc(alias = "comm")]
1129
0
    fn merge_join_by<J, F, T>(self, other: J, cmp_fn: F) -> MergeJoinBy<Self, J::IntoIter, F>
1130
0
    where
1131
0
        J: IntoIterator,
1132
0
        F: FnMut(&Self::Item, &J::Item) -> T,
1133
0
        Self: Sized,
1134
    {
1135
0
        merge_join_by(self, other, cmp_fn)
1136
0
    }
1137
1138
    /// Return an iterator adaptor that flattens an iterator of iterators by
1139
    /// merging them in ascending order.
1140
    ///
1141
    /// If all base iterators are sorted (ascending), the result is sorted.
1142
    ///
1143
    /// Iterator element type is `Self::Item`.
1144
    ///
1145
    /// ```
1146
    /// use itertools::Itertools;
1147
    ///
1148
    /// let a = (0..6).step_by(3);
1149
    /// let b = (1..6).step_by(3);
1150
    /// let c = (2..6).step_by(3);
1151
    /// let it = vec![a, b, c].into_iter().kmerge();
1152
    /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5]);
1153
    /// ```
1154
    #[cfg(feature = "use_alloc")]
1155
0
    fn kmerge(self) -> KMerge<<Self::Item as IntoIterator>::IntoIter>
1156
0
    where
1157
0
        Self: Sized,
1158
0
        Self::Item: IntoIterator,
1159
0
        <Self::Item as IntoIterator>::Item: PartialOrd,
1160
    {
1161
0
        kmerge(self)
1162
0
    }
1163
1164
    /// Return an iterator adaptor that flattens an iterator of iterators by
1165
    /// merging them according to the given closure.
1166
    ///
1167
    /// The closure `first` is called with two elements *a*, *b* and should
1168
    /// return `true` if *a* is ordered before *b*.
1169
    ///
1170
    /// If all base iterators are sorted according to `first`, the result is
1171
    /// sorted.
1172
    ///
1173
    /// Iterator element type is `Self::Item`.
1174
    ///
1175
    /// ```
1176
    /// use itertools::Itertools;
1177
    ///
1178
    /// let a = vec![-1f64, 2., 3., -5., 6., -7.];
1179
    /// let b = vec![0., 2., -4.];
1180
    /// let mut it = vec![a, b].into_iter().kmerge_by(|a, b| a.abs() < b.abs());
1181
    /// assert_eq!(it.next(), Some(0.));
1182
    /// assert_eq!(it.last(), Some(-7.));
1183
    /// ```
1184
    #[cfg(feature = "use_alloc")]
1185
0
    fn kmerge_by<F>(self, first: F) -> KMergeBy<<Self::Item as IntoIterator>::IntoIter, F>
1186
0
    where
1187
0
        Self: Sized,
1188
0
        Self::Item: IntoIterator,
1189
0
        F: FnMut(&<Self::Item as IntoIterator>::Item, &<Self::Item as IntoIterator>::Item) -> bool,
1190
    {
1191
0
        kmerge_by(self, first)
1192
0
    }
1193
1194
    /// Return an iterator adaptor that iterates over the cartesian product of
1195
    /// the element sets of two iterators `self` and `J`.
1196
    ///
1197
    /// Iterator element type is `(Self::Item, J::Item)`.
1198
    ///
1199
    /// ```
1200
    /// use itertools::Itertools;
1201
    ///
1202
    /// let it = (0..2).cartesian_product("αβ".chars());
1203
    /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]);
1204
    /// ```
1205
0
    fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter>
1206
0
    where
1207
0
        Self: Sized,
1208
0
        Self::Item: Clone,
1209
0
        J: IntoIterator,
1210
0
        J::IntoIter: Clone,
1211
    {
1212
0
        adaptors::cartesian_product(self, other.into_iter())
1213
0
    }
1214
1215
    /// Return an iterator adaptor that iterates over the cartesian product of
1216
    /// all subiterators returned by meta-iterator `self`.
1217
    ///
1218
    /// All provided iterators must yield the same `Item` type. To generate
1219
    /// the product of iterators yielding multiple types, use the
1220
    /// [`iproduct`] macro instead.
1221
    ///
1222
    /// The iterator element type is `Vec<T>`, where `T` is the iterator element
1223
    /// of the subiterators.
1224
    ///
1225
    /// Note that the iterator is fused.
1226
    ///
1227
    /// ```
1228
    /// use itertools::Itertools;
1229
    /// let mut multi_prod = (0..3).map(|i| (i * 2)..(i * 2 + 2))
1230
    ///     .multi_cartesian_product();
1231
    /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 4]));
1232
    /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 5]));
1233
    /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 4]));
1234
    /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 5]));
1235
    /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 4]));
1236
    /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 5]));
1237
    /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 4]));
1238
    /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 5]));
1239
    /// assert_eq!(multi_prod.next(), None);
1240
    /// ```
1241
    ///
1242
    /// If the adapted iterator is empty, the result is an iterator yielding a single empty vector.
1243
    /// This is known as the [nullary cartesian product](https://en.wikipedia.org/wiki/Empty_product#Nullary_Cartesian_product).
1244
    ///
1245
    /// ```
1246
    /// use itertools::Itertools;
1247
    /// let mut nullary_cartesian_product = (0..0).map(|i| (i * 2)..(i * 2 + 2)).multi_cartesian_product();
1248
    /// assert_eq!(nullary_cartesian_product.next(), Some(vec![]));
1249
    /// assert_eq!(nullary_cartesian_product.next(), None);
1250
    /// ```
1251
    #[cfg(feature = "use_alloc")]
1252
0
    fn multi_cartesian_product(self) -> MultiProduct<<Self::Item as IntoIterator>::IntoIter>
1253
0
    where
1254
0
        Self: Sized,
1255
0
        Self::Item: IntoIterator,
1256
0
        <Self::Item as IntoIterator>::IntoIter: Clone,
1257
0
        <Self::Item as IntoIterator>::Item: Clone,
1258
    {
1259
0
        adaptors::multi_cartesian_product(self)
1260
0
    }
1261
1262
    /// Return an iterator adaptor that uses the passed-in closure to
1263
    /// optionally merge together consecutive elements.
1264
    ///
1265
    /// The closure `f` is passed two elements, `previous` and `current` and may
1266
    /// return either (1) `Ok(combined)` to merge the two values or
1267
    /// (2) `Err((previous', current'))` to indicate they can't be merged.
1268
    /// In (2), the value `previous'` is emitted by the iterator.
1269
    /// Either (1) `combined` or (2) `current'` becomes the previous value
1270
    /// when coalesce continues with the next pair of elements to merge. The
1271
    /// value that remains at the end is also emitted by the iterator.
1272
    ///
1273
    /// Iterator element type is `Self::Item`.
1274
    ///
1275
    /// This iterator is *fused*.
1276
    ///
1277
    /// ```
1278
    /// use itertools::Itertools;
1279
    ///
1280
    /// // sum same-sign runs together
1281
    /// let data = vec![-1., -2., -3., 3., 1., 0., -1.];
1282
    /// itertools::assert_equal(data.into_iter().coalesce(|x, y|
1283
    ///         if (x >= 0.) == (y >= 0.) {
1284
    ///             Ok(x + y)
1285
    ///         } else {
1286
    ///             Err((x, y))
1287
    ///         }),
1288
    ///         vec![-6., 4., -1.]);
1289
    /// ```
1290
0
    fn coalesce<F>(self, f: F) -> Coalesce<Self, F>
1291
0
    where
1292
0
        Self: Sized,
1293
0
        F: FnMut(Self::Item, Self::Item) -> Result<Self::Item, (Self::Item, Self::Item)>,
1294
    {
1295
0
        adaptors::coalesce(self, f)
1296
0
    }
1297
1298
    /// Remove duplicates from sections of consecutive identical elements.
1299
    /// If the iterator is sorted, all elements will be unique.
1300
    ///
1301
    /// Iterator element type is `Self::Item`.
1302
    ///
1303
    /// This iterator is *fused*.
1304
    ///
1305
    /// ```
1306
    /// use itertools::Itertools;
1307
    ///
1308
    /// let data = vec![1., 1., 2., 3., 3., 2., 2.];
1309
    /// itertools::assert_equal(data.into_iter().dedup(),
1310
    ///                         vec![1., 2., 3., 2.]);
1311
    /// ```
1312
0
    fn dedup(self) -> Dedup<Self>
1313
0
    where
1314
0
        Self: Sized,
1315
0
        Self::Item: PartialEq,
1316
    {
1317
0
        adaptors::dedup(self)
1318
0
    }
1319
1320
    /// Remove duplicates from sections of consecutive identical elements,
1321
    /// determining equality using a comparison function.
1322
    /// If the iterator is sorted, all elements will be unique.
1323
    ///
1324
    /// Iterator element type is `Self::Item`.
1325
    ///
1326
    /// This iterator is *fused*.
1327
    ///
1328
    /// ```
1329
    /// use itertools::Itertools;
1330
    ///
1331
    /// let data = vec![(0, 1.), (1, 1.), (0, 2.), (0, 3.), (1, 3.), (1, 2.), (2, 2.)];
1332
    /// itertools::assert_equal(data.into_iter().dedup_by(|x, y| x.1 == y.1),
1333
    ///                         vec![(0, 1.), (0, 2.), (0, 3.), (1, 2.)]);
1334
    /// ```
1335
0
    fn dedup_by<Cmp>(self, cmp: Cmp) -> DedupBy<Self, Cmp>
1336
0
    where
1337
0
        Self: Sized,
1338
0
        Cmp: FnMut(&Self::Item, &Self::Item) -> bool,
1339
    {
1340
0
        adaptors::dedup_by(self, cmp)
1341
0
    }
1342
1343
    /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1344
    /// how many repeated elements were present.
1345
    /// If the iterator is sorted, all elements will be unique.
1346
    ///
1347
    /// Iterator element type is `(usize, Self::Item)`.
1348
    ///
1349
    /// This iterator is *fused*.
1350
    ///
1351
    /// ```
1352
    /// use itertools::Itertools;
1353
    ///
1354
    /// let data = vec!['a', 'a', 'b', 'c', 'c', 'b', 'b'];
1355
    /// itertools::assert_equal(data.into_iter().dedup_with_count(),
1356
    ///                         vec![(2, 'a'), (1, 'b'), (2, 'c'), (2, 'b')]);
1357
    /// ```
1358
0
    fn dedup_with_count(self) -> DedupWithCount<Self>
1359
0
    where
1360
0
        Self: Sized,
1361
    {
1362
0
        adaptors::dedup_with_count(self)
1363
0
    }
1364
1365
    /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1366
    /// how many repeated elements were present.
1367
    /// This will determine equality using a comparison function.
1368
    /// If the iterator is sorted, all elements will be unique.
1369
    ///
1370
    /// Iterator element type is `(usize, Self::Item)`.
1371
    ///
1372
    /// This iterator is *fused*.
1373
    ///
1374
    /// ```
1375
    /// use itertools::Itertools;
1376
    ///
1377
    /// let data = vec![(0, 'a'), (1, 'a'), (0, 'b'), (0, 'c'), (1, 'c'), (1, 'b'), (2, 'b')];
1378
    /// itertools::assert_equal(data.into_iter().dedup_by_with_count(|x, y| x.1 == y.1),
1379
    ///                         vec![(2, (0, 'a')), (1, (0, 'b')), (2, (0, 'c')), (2, (1, 'b'))]);
1380
    /// ```
1381
0
    fn dedup_by_with_count<Cmp>(self, cmp: Cmp) -> DedupByWithCount<Self, Cmp>
1382
0
    where
1383
0
        Self: Sized,
1384
0
        Cmp: FnMut(&Self::Item, &Self::Item) -> bool,
1385
    {
1386
0
        adaptors::dedup_by_with_count(self, cmp)
1387
0
    }
1388
1389
    /// Return an iterator adaptor that produces elements that appear more than once during the
1390
    /// iteration. Duplicates are detected using hash and equality.
1391
    ///
1392
    /// The iterator is stable, returning the duplicate items in the order in which they occur in
1393
    /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1394
    /// than twice, the second item is the item retained and the rest are discarded.
1395
    ///
1396
    /// ```
1397
    /// use itertools::Itertools;
1398
    ///
1399
    /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1400
    /// itertools::assert_equal(data.into_iter().duplicates(),
1401
    ///                         vec![20, 10]);
1402
    /// ```
1403
    #[cfg(feature = "use_std")]
1404
0
    fn duplicates(self) -> Duplicates<Self>
1405
0
    where
1406
0
        Self: Sized,
1407
0
        Self::Item: Eq + Hash,
1408
    {
1409
0
        duplicates_impl::duplicates(self)
1410
0
    }
1411
1412
    /// Return an iterator adaptor that produces elements that appear more than once during the
1413
    /// iteration. Duplicates are detected using hash and equality.
1414
    ///
1415
    /// Duplicates are detected by comparing the key they map to with the keying function `f` by
1416
    /// hash and equality. The keys are stored in a hash map in the iterator.
1417
    ///
1418
    /// The iterator is stable, returning the duplicate items in the order in which they occur in
1419
    /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1420
    /// than twice, the second item is the item retained and the rest are discarded.
1421
    ///
1422
    /// ```
1423
    /// use itertools::Itertools;
1424
    ///
1425
    /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1426
    /// itertools::assert_equal(data.into_iter().duplicates_by(|s| s.len()),
1427
    ///                         vec!["aa", "c"]);
1428
    /// ```
1429
    #[cfg(feature = "use_std")]
1430
0
    fn duplicates_by<V, F>(self, f: F) -> DuplicatesBy<Self, V, F>
1431
0
    where
1432
0
        Self: Sized,
1433
0
        V: Eq + Hash,
1434
0
        F: FnMut(&Self::Item) -> V,
1435
    {
1436
0
        duplicates_impl::duplicates_by(self, f)
1437
0
    }
1438
1439
    /// Return an iterator adaptor that filters out elements that have
1440
    /// already been produced once during the iteration. Duplicates
1441
    /// are detected using hash and equality.
1442
    ///
1443
    /// Clones of visited elements are stored in a hash set in the
1444
    /// iterator.
1445
    ///
1446
    /// The iterator is stable, returning the non-duplicate items in the order
1447
    /// in which they occur in the adapted iterator. In a set of duplicate
1448
    /// items, the first item encountered is the item retained.
1449
    ///
1450
    /// ```
1451
    /// use itertools::Itertools;
1452
    ///
1453
    /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1454
    /// itertools::assert_equal(data.into_iter().unique(),
1455
    ///                         vec![10, 20, 30, 40, 50]);
1456
    /// ```
1457
    #[cfg(feature = "use_std")]
1458
0
    fn unique(self) -> Unique<Self>
1459
0
    where
1460
0
        Self: Sized,
1461
0
        Self::Item: Clone + Eq + Hash,
1462
    {
1463
0
        unique_impl::unique(self)
1464
0
    }
1465
1466
    /// Return an iterator adaptor that filters out elements that have
1467
    /// already been produced once during the iteration.
1468
    ///
1469
    /// Duplicates are detected by comparing the key they map to
1470
    /// with the keying function `f` by hash and equality.
1471
    /// The keys are stored in a hash set in the iterator.
1472
    ///
1473
    /// The iterator is stable, returning the non-duplicate items in the order
1474
    /// in which they occur in the adapted iterator. In a set of duplicate
1475
    /// items, the first item encountered is the item retained.
1476
    ///
1477
    /// ```
1478
    /// use itertools::Itertools;
1479
    ///
1480
    /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1481
    /// itertools::assert_equal(data.into_iter().unique_by(|s| s.len()),
1482
    ///                         vec!["a", "bb", "ccc"]);
1483
    /// ```
1484
    #[cfg(feature = "use_std")]
1485
0
    fn unique_by<V, F>(self, f: F) -> UniqueBy<Self, V, F>
1486
0
    where
1487
0
        Self: Sized,
1488
0
        V: Eq + Hash,
1489
0
        F: FnMut(&Self::Item) -> V,
1490
    {
1491
0
        unique_impl::unique_by(self, f)
1492
0
    }
1493
1494
    /// Return an iterator adaptor that borrows from this iterator and
1495
    /// takes items while the closure `accept` returns `true`.
1496
    ///
1497
    /// This adaptor can only be used on iterators that implement `PeekingNext`
1498
    /// like `.peekable()`, `put_back` and a few other collection iterators.
1499
    ///
1500
    /// The last and rejected element (first `false`) is still available when
1501
    /// `peeking_take_while` is done.
1502
    ///
1503
    ///
1504
    /// See also [`.take_while_ref()`](Itertools::take_while_ref)
1505
    /// which is a similar adaptor.
1506
0
    fn peeking_take_while<F>(&mut self, accept: F) -> PeekingTakeWhile<Self, F>
1507
0
    where
1508
0
        Self: Sized + PeekingNext,
1509
0
        F: FnMut(&Self::Item) -> bool,
1510
    {
1511
0
        peeking_take_while::peeking_take_while(self, accept)
1512
0
    }
1513
1514
    /// Return an iterator adaptor that borrows from a `Clone`-able iterator
1515
    /// to only pick off elements while the predicate `accept` returns `true`.
1516
    ///
1517
    /// It uses the `Clone` trait to restore the original iterator so that the
1518
    /// last and rejected element (first `false`) is still available when
1519
    /// `take_while_ref` is done.
1520
    ///
1521
    /// ```
1522
    /// use itertools::Itertools;
1523
    ///
1524
    /// let mut hexadecimals = "0123456789abcdef".chars();
1525
    ///
1526
    /// let decimals = hexadecimals.take_while_ref(|c| c.is_numeric())
1527
    ///                            .collect::<String>();
1528
    /// assert_eq!(decimals, "0123456789");
1529
    /// assert_eq!(hexadecimals.next(), Some('a'));
1530
    ///
1531
    /// ```
1532
0
    fn take_while_ref<F>(&mut self, accept: F) -> TakeWhileRef<Self, F>
1533
0
    where
1534
0
        Self: Clone,
1535
0
        F: FnMut(&Self::Item) -> bool,
1536
    {
1537
0
        adaptors::take_while_ref(self, accept)
1538
0
    }
1539
1540
    /// Returns an iterator adaptor that consumes elements while the given
1541
    /// predicate is `true`, *including* the element for which the predicate
1542
    /// first returned `false`.
1543
    ///
1544
    /// The [`.take_while()`][std::iter::Iterator::take_while] adaptor is useful
1545
    /// when you want items satisfying a predicate, but to know when to stop
1546
    /// taking elements, we have to consume that first element that doesn't
1547
    /// satisfy the predicate. This adaptor includes that element where
1548
    /// [`.take_while()`][std::iter::Iterator::take_while] would drop it.
1549
    ///
1550
    /// The [`.take_while_ref()`][crate::Itertools::take_while_ref] adaptor
1551
    /// serves a similar purpose, but this adaptor doesn't require [`Clone`]ing
1552
    /// the underlying elements.
1553
    ///
1554
    /// ```rust
1555
    /// # use itertools::Itertools;
1556
    /// let items = vec![1, 2, 3, 4, 5];
1557
    /// let filtered: Vec<_> = items
1558
    ///     .into_iter()
1559
    ///     .take_while_inclusive(|&n| n % 3 != 0)
1560
    ///     .collect();
1561
    ///
1562
    /// assert_eq!(filtered, vec![1, 2, 3]);
1563
    /// ```
1564
    ///
1565
    /// ```rust
1566
    /// # use itertools::Itertools;
1567
    /// let items = vec![1, 2, 3, 4, 5];
1568
    ///
1569
    /// let take_while_inclusive_result: Vec<_> = items
1570
    ///     .iter()
1571
    ///     .copied()
1572
    ///     .take_while_inclusive(|&n| n % 3 != 0)
1573
    ///     .collect();
1574
    /// let take_while_result: Vec<_> = items
1575
    ///     .into_iter()
1576
    ///     .take_while(|&n| n % 3 != 0)
1577
    ///     .collect();
1578
    ///
1579
    /// assert_eq!(take_while_inclusive_result, vec![1, 2, 3]);
1580
    /// assert_eq!(take_while_result, vec![1, 2]);
1581
    /// // both iterators have the same items remaining at this point---the 3
1582
    /// // is lost from the `take_while` vec
1583
    /// ```
1584
    ///
1585
    /// ```rust
1586
    /// # use itertools::Itertools;
1587
    /// #[derive(Debug, PartialEq)]
1588
    /// struct NoCloneImpl(i32);
1589
    ///
1590
    /// let non_clonable_items: Vec<_> = vec![1, 2, 3, 4, 5]
1591
    ///     .into_iter()
1592
    ///     .map(NoCloneImpl)
1593
    ///     .collect();
1594
    /// let filtered: Vec<_> = non_clonable_items
1595
    ///     .into_iter()
1596
    ///     .take_while_inclusive(|n| n.0 % 3 != 0)
1597
    ///     .collect();
1598
    /// let expected: Vec<_> = vec![1, 2, 3].into_iter().map(NoCloneImpl).collect();
1599
    /// assert_eq!(filtered, expected);
1600
    #[doc(alias = "take_until")]
1601
0
    fn take_while_inclusive<F>(self, accept: F) -> TakeWhileInclusive<Self, F>
1602
0
    where
1603
0
        Self: Sized,
1604
0
        F: FnMut(&Self::Item) -> bool,
1605
    {
1606
0
        take_while_inclusive::TakeWhileInclusive::new(self, accept)
1607
0
    }
1608
1609
    /// Return an iterator adaptor that filters `Option<A>` iterator elements
1610
    /// and produces `A`. Stops on the first `None` encountered.
1611
    ///
1612
    /// Iterator element type is `A`, the unwrapped element.
1613
    ///
1614
    /// ```
1615
    /// use itertools::Itertools;
1616
    ///
1617
    /// // List all hexadecimal digits
1618
    /// itertools::assert_equal(
1619
    ///     (0..).map(|i| std::char::from_digit(i, 16)).while_some(),
1620
    ///     "0123456789abcdef".chars());
1621
    ///
1622
    /// ```
1623
0
    fn while_some<A>(self) -> WhileSome<Self>
1624
0
    where
1625
0
        Self: Sized + Iterator<Item = Option<A>>,
1626
    {
1627
0
        adaptors::while_some(self)
1628
0
    }
1629
1630
    /// Return an iterator adaptor that iterates over the combinations of the
1631
    /// elements from an iterator.
1632
    ///
1633
    /// Iterator element can be any homogeneous tuple of type `Self::Item` with
1634
    /// size up to 12.
1635
    ///
1636
    /// # Guarantees
1637
    ///
1638
    /// If the adapted iterator is deterministic,
1639
    /// this iterator adapter yields items in a reliable order.
1640
    ///
1641
    /// ```
1642
    /// use itertools::Itertools;
1643
    ///
1644
    /// let mut v = Vec::new();
1645
    /// for (a, b) in (1..5).tuple_combinations() {
1646
    ///     v.push((a, b));
1647
    /// }
1648
    /// assert_eq!(v, vec![(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]);
1649
    ///
1650
    /// let mut it = (1..5).tuple_combinations();
1651
    /// assert_eq!(Some((1, 2, 3)), it.next());
1652
    /// assert_eq!(Some((1, 2, 4)), it.next());
1653
    /// assert_eq!(Some((1, 3, 4)), it.next());
1654
    /// assert_eq!(Some((2, 3, 4)), it.next());
1655
    /// assert_eq!(None, it.next());
1656
    ///
1657
    /// // this requires a type hint
1658
    /// let it = (1..5).tuple_combinations::<(_, _, _)>();
1659
    /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1660
    ///
1661
    /// // you can also specify the complete type
1662
    /// use itertools::TupleCombinations;
1663
    /// use std::ops::Range;
1664
    ///
1665
    /// let it: TupleCombinations<Range<u32>, (u32, u32, u32)> = (1..5).tuple_combinations();
1666
    /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1667
    /// ```
1668
0
    fn tuple_combinations<T>(self) -> TupleCombinations<Self, T>
1669
0
    where
1670
0
        Self: Sized + Clone,
1671
0
        Self::Item: Clone,
1672
0
        T: adaptors::HasCombination<Self>,
1673
    {
1674
0
        adaptors::tuple_combinations(self)
1675
0
    }
1676
1677
    /// Return an iterator adaptor that iterates over the combinations of the
1678
    /// elements from an iterator.
1679
    ///
1680
    /// Iterator element type is [Self::Item; K]. The iterator produces a new
1681
    /// array per iteration, and clones the iterator elements.
1682
    ///
1683
    /// # Guarantees
1684
    ///
1685
    /// If the adapted iterator is deterministic,
1686
    /// this iterator adapter yields items in a reliable order.
1687
    ///
1688
    /// ```
1689
    /// use itertools::Itertools;
1690
    ///
1691
    /// let mut v = Vec::new();
1692
    /// for [a, b] in (1..5).array_combinations() {
1693
    ///     v.push([a, b]);
1694
    /// }
1695
    /// assert_eq!(v, vec![[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]);
1696
    ///
1697
    /// let mut it = (1..5).array_combinations();
1698
    /// assert_eq!(Some([1, 2, 3]), it.next());
1699
    /// assert_eq!(Some([1, 2, 4]), it.next());
1700
    /// assert_eq!(Some([1, 3, 4]), it.next());
1701
    /// assert_eq!(Some([2, 3, 4]), it.next());
1702
    /// assert_eq!(None, it.next());
1703
    ///
1704
    /// // this requires a type hint
1705
    /// let it = (1..5).array_combinations::<3>();
1706
    /// itertools::assert_equal(it, vec![[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]);
1707
    ///
1708
    /// // you can also specify the complete type
1709
    /// use itertools::ArrayCombinations;
1710
    /// use std::ops::Range;
1711
    ///
1712
    /// let it: ArrayCombinations<Range<u32>, 3> = (1..5).array_combinations();
1713
    /// itertools::assert_equal(it, vec![[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]);
1714
    /// ```
1715
    #[cfg(feature = "use_alloc")]
1716
0
    fn array_combinations<const K: usize>(self) -> ArrayCombinations<Self, K>
1717
0
    where
1718
0
        Self: Sized + Clone,
1719
0
        Self::Item: Clone,
1720
    {
1721
0
        combinations::array_combinations(self)
1722
0
    }
1723
1724
    /// Return an iterator adaptor that iterates over the `k`-length combinations of
1725
    /// the elements from an iterator.
1726
    ///
1727
    /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new `Vec` per iteration,
1728
    /// and clones the iterator elements.
1729
    ///
1730
    /// # Guarantees
1731
    ///
1732
    /// If the adapted iterator is deterministic,
1733
    /// this iterator adapter yields items in a reliable order.
1734
    ///
1735
    /// ```
1736
    /// use itertools::Itertools;
1737
    ///
1738
    /// let it = (1..5).combinations(3);
1739
    /// itertools::assert_equal(it, vec![
1740
    ///     vec![1, 2, 3],
1741
    ///     vec![1, 2, 4],
1742
    ///     vec![1, 3, 4],
1743
    ///     vec![2, 3, 4],
1744
    /// ]);
1745
    /// ```
1746
    ///
1747
    /// Note: Combinations does not take into account the equality of the iterated values.
1748
    /// ```
1749
    /// use itertools::Itertools;
1750
    ///
1751
    /// let it = vec![1, 2, 2].into_iter().combinations(2);
1752
    /// itertools::assert_equal(it, vec![
1753
    ///     vec![1, 2], // Note: these are the same
1754
    ///     vec![1, 2], // Note: these are the same
1755
    ///     vec![2, 2],
1756
    /// ]);
1757
    /// ```
1758
    #[cfg(feature = "use_alloc")]
1759
0
    fn combinations(self, k: usize) -> Combinations<Self>
1760
0
    where
1761
0
        Self: Sized,
1762
0
        Self::Item: Clone,
1763
    {
1764
0
        combinations::combinations(self, k)
1765
0
    }
1766
1767
    /// Return an iterator that iterates over the `k`-length combinations of
1768
    /// the elements from an iterator, with replacement.
1769
    ///
1770
    /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new `Vec` per iteration,
1771
    /// and clones the iterator elements.
1772
    ///
1773
    /// ```
1774
    /// use itertools::Itertools;
1775
    ///
1776
    /// let it = (1..4).combinations_with_replacement(2);
1777
    /// itertools::assert_equal(it, vec![
1778
    ///     vec![1, 1],
1779
    ///     vec![1, 2],
1780
    ///     vec![1, 3],
1781
    ///     vec![2, 2],
1782
    ///     vec![2, 3],
1783
    ///     vec![3, 3],
1784
    /// ]);
1785
    /// ```
1786
    #[cfg(feature = "use_alloc")]
1787
0
    fn combinations_with_replacement(self, k: usize) -> CombinationsWithReplacement<Self>
1788
0
    where
1789
0
        Self: Sized,
1790
0
        Self::Item: Clone,
1791
    {
1792
0
        combinations_with_replacement::combinations_with_replacement(self, k)
1793
0
    }
1794
1795
    /// Return an iterator adaptor that iterates over all k-permutations of the
1796
    /// elements from an iterator.
1797
    ///
1798
    /// Iterator element type is `Vec<Self::Item>` with length `k`. The iterator
1799
    /// produces a new `Vec` per iteration, and clones the iterator elements.
1800
    ///
1801
    /// If `k` is greater than the length of the input iterator, the resultant
1802
    /// iterator adaptor will be empty.
1803
    ///
1804
    /// If you are looking for permutations with replacements,
1805
    /// use `repeat_n(iter, k).multi_cartesian_product()` instead.
1806
    ///
1807
    /// ```
1808
    /// use itertools::Itertools;
1809
    ///
1810
    /// let perms = (5..8).permutations(2);
1811
    /// itertools::assert_equal(perms, vec![
1812
    ///     vec![5, 6],
1813
    ///     vec![5, 7],
1814
    ///     vec![6, 5],
1815
    ///     vec![6, 7],
1816
    ///     vec![7, 5],
1817
    ///     vec![7, 6],
1818
    /// ]);
1819
    /// ```
1820
    ///
1821
    /// Note: Permutations does not take into account the equality of the iterated values.
1822
    ///
1823
    /// ```
1824
    /// use itertools::Itertools;
1825
    ///
1826
    /// let it = vec![2, 2].into_iter().permutations(2);
1827
    /// itertools::assert_equal(it, vec![
1828
    ///     vec![2, 2], // Note: these are the same
1829
    ///     vec![2, 2], // Note: these are the same
1830
    /// ]);
1831
    /// ```
1832
    ///
1833
    /// Note: The source iterator is collected lazily, and will not be
1834
    /// re-iterated if the permutations adaptor is completed and re-iterated.
1835
    #[cfg(feature = "use_alloc")]
1836
0
    fn permutations(self, k: usize) -> Permutations<Self>
1837
0
    where
1838
0
        Self: Sized,
1839
0
        Self::Item: Clone,
1840
    {
1841
0
        permutations::permutations(self, k)
1842
0
    }
1843
1844
    /// Return an iterator that iterates through the powerset of the elements from an
1845
    /// iterator.
1846
    ///
1847
    /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new `Vec`
1848
    /// per iteration, and clones the iterator elements.
1849
    ///
1850
    /// The powerset of a set contains all subsets including the empty set and the full
1851
    /// input set. A powerset has length _2^n_ where _n_ is the length of the input
1852
    /// set.
1853
    ///
1854
    /// Each `Vec` produced by this iterator represents a subset of the elements
1855
    /// produced by the source iterator.
1856
    ///
1857
    /// ```
1858
    /// use itertools::Itertools;
1859
    ///
1860
    /// let sets = (1..4).powerset().collect::<Vec<_>>();
1861
    /// itertools::assert_equal(sets, vec![
1862
    ///     vec![],
1863
    ///     vec![1],
1864
    ///     vec![2],
1865
    ///     vec![3],
1866
    ///     vec![1, 2],
1867
    ///     vec![1, 3],
1868
    ///     vec![2, 3],
1869
    ///     vec![1, 2, 3],
1870
    /// ]);
1871
    /// ```
1872
    #[cfg(feature = "use_alloc")]
1873
0
    fn powerset(self) -> Powerset<Self>
1874
0
    where
1875
0
        Self: Sized,
1876
0
        Self::Item: Clone,
1877
    {
1878
0
        powerset::powerset(self)
1879
0
    }
1880
1881
    /// Return an iterator adaptor that pads the sequence to a minimum length of
1882
    /// `min` by filling missing elements using a closure `f`.
1883
    ///
1884
    /// Iterator element type is `Self::Item`.
1885
    ///
1886
    /// ```
1887
    /// use itertools::Itertools;
1888
    ///
1889
    /// let it = (0..5).pad_using(10, |i| 2*i);
1890
    /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 10, 12, 14, 16, 18]);
1891
    ///
1892
    /// let it = (0..10).pad_using(5, |i| 2*i);
1893
    /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1894
    ///
1895
    /// let it = (0..5).pad_using(10, |i| 2*i).rev();
1896
    /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]);
1897
    /// ```
1898
0
    fn pad_using<F>(self, min: usize, f: F) -> PadUsing<Self, F>
1899
0
    where
1900
0
        Self: Sized,
1901
0
        F: FnMut(usize) -> Self::Item,
1902
    {
1903
0
        pad_tail::pad_using(self, min, f)
1904
0
    }
1905
1906
    /// Return an iterator adaptor that combines each element with a `Position` to
1907
    /// ease special-case handling of the first or last elements.
1908
    ///
1909
    /// Iterator element type is
1910
    /// [`(Position, Self::Item)`](Position)
1911
    ///
1912
    /// ```
1913
    /// use itertools::{Itertools, Position};
1914
    ///
1915
    /// let it = (0..4).with_position();
1916
    /// itertools::assert_equal(it,
1917
    ///                         vec![(Position::First, 0),
1918
    ///                              (Position::Middle, 1),
1919
    ///                              (Position::Middle, 2),
1920
    ///                              (Position::Last, 3)]);
1921
    ///
1922
    /// let it = (0..1).with_position();
1923
    /// itertools::assert_equal(it, vec![(Position::Only, 0)]);
1924
    /// ```
1925
0
    fn with_position(self) -> WithPosition<Self>
1926
0
    where
1927
0
        Self: Sized,
1928
    {
1929
0
        with_position::with_position(self)
1930
0
    }
1931
1932
    /// Return an iterator adaptor that yields the indices of all elements
1933
    /// satisfying a predicate, counted from the start of the iterator.
1934
    ///
1935
    /// Equivalent to `iter.enumerate().filter(|(_, v)| predicate(*v)).map(|(i, _)| i)`.
1936
    ///
1937
    /// ```
1938
    /// use itertools::Itertools;
1939
    ///
1940
    /// let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
1941
    /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 0), vec![1, 4, 5]);
1942
    ///
1943
    /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]);
1944
    /// ```
1945
0
    fn positions<P>(self, predicate: P) -> Positions<Self, P>
1946
0
    where
1947
0
        Self: Sized,
1948
0
        P: FnMut(Self::Item) -> bool,
1949
    {
1950
0
        adaptors::positions(self, predicate)
1951
0
    }
1952
1953
    /// Return an iterator adaptor that applies a mutating function
1954
    /// to each element before yielding it.
1955
    ///
1956
    /// ```
1957
    /// use itertools::Itertools;
1958
    ///
1959
    /// let input = vec![vec![1], vec![3, 2, 1]];
1960
    /// let it = input.into_iter().update(|v| v.push(0));
1961
    /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]);
1962
    /// ```
1963
0
    fn update<F>(self, updater: F) -> Update<Self, F>
1964
0
    where
1965
0
        Self: Sized,
1966
0
        F: FnMut(&mut Self::Item),
1967
    {
1968
0
        adaptors::update(self, updater)
1969
0
    }
1970
1971
    // non-adaptor methods
1972
    /// Advances the iterator and returns the next items grouped in an array of
1973
    /// a specific size.
1974
    ///
1975
    /// If there are enough elements to be grouped in an array, then the array
1976
    /// is returned inside `Some`, otherwise `None` is returned.
1977
    ///
1978
    /// ```
1979
    /// use itertools::Itertools;
1980
    ///
1981
    /// let mut iter = 1..5;
1982
    ///
1983
    /// assert_eq!(Some([1, 2]), iter.next_array());
1984
    /// ```
1985
0
    fn next_array<const N: usize>(&mut self) -> Option<[Self::Item; N]>
1986
0
    where
1987
0
        Self: Sized,
1988
    {
1989
0
        next_array::next_array(self)
1990
0
    }
1991
1992
    /// Collects all items from the iterator into an array of a specific size.
1993
    ///
1994
    /// If the number of elements inside the iterator is **exactly** equal to
1995
    /// the array size, then the array is returned inside `Some`, otherwise
1996
    /// `None` is returned.
1997
    ///
1998
    /// ```
1999
    /// use itertools::Itertools;
2000
    ///
2001
    /// let iter = 1..3;
2002
    ///
2003
    /// if let Some([x, y]) = iter.collect_array() {
2004
    ///     assert_eq!([x, y], [1, 2])
2005
    /// } else {
2006
    ///     panic!("Expected two elements")
2007
    /// }
2008
    /// ```
2009
0
    fn collect_array<const N: usize>(mut self) -> Option<[Self::Item; N]>
2010
0
    where
2011
0
        Self: Sized,
2012
    {
2013
0
        self.next_array().filter(|_| self.next().is_none())
2014
0
    }
2015
2016
    /// Advances the iterator and returns the next items grouped in a tuple of
2017
    /// a specific size (up to 12).
2018
    ///
2019
    /// If there are enough elements to be grouped in a tuple, then the tuple is
2020
    /// returned inside `Some`, otherwise `None` is returned.
2021
    ///
2022
    /// ```
2023
    /// use itertools::Itertools;
2024
    ///
2025
    /// let mut iter = 1..5;
2026
    ///
2027
    /// assert_eq!(Some((1, 2)), iter.next_tuple());
2028
    /// ```
2029
0
    fn next_tuple<T>(&mut self) -> Option<T>
2030
0
    where
2031
0
        Self: Sized + Iterator<Item = T::Item>,
2032
0
        T: traits::HomogeneousTuple,
2033
    {
2034
0
        T::collect_from_iter_no_buf(self)
2035
0
    }
2036
2037
    /// Collects all items from the iterator into a tuple of a specific size
2038
    /// (up to 12).
2039
    ///
2040
    /// If the number of elements inside the iterator is **exactly** equal to
2041
    /// the tuple size, then the tuple is returned inside `Some`, otherwise
2042
    /// `None` is returned.
2043
    ///
2044
    /// ```
2045
    /// use itertools::Itertools;
2046
    ///
2047
    /// let iter = 1..3;
2048
    ///
2049
    /// if let Some((x, y)) = iter.collect_tuple() {
2050
    ///     assert_eq!((x, y), (1, 2))
2051
    /// } else {
2052
    ///     panic!("Expected two elements")
2053
    /// }
2054
    /// ```
2055
0
    fn collect_tuple<T>(mut self) -> Option<T>
2056
0
    where
2057
0
        Self: Sized + Iterator<Item = T::Item>,
2058
0
        T: traits::HomogeneousTuple,
2059
    {
2060
0
        match self.next_tuple() {
2061
0
            elt @ Some(_) => match self.next() {
2062
0
                Some(_) => None,
2063
0
                None => elt,
2064
            },
2065
0
            _ => None,
2066
        }
2067
0
    }
2068
2069
    /// Find the position and value of the first element satisfying a predicate.
2070
    ///
2071
    /// The iterator is not advanced past the first element found.
2072
    ///
2073
    /// ```
2074
    /// use itertools::Itertools;
2075
    ///
2076
    /// let text = "Hα";
2077
    /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α')));
2078
    /// ```
2079
0
    fn find_position<P>(&mut self, mut pred: P) -> Option<(usize, Self::Item)>
2080
0
    where
2081
0
        P: FnMut(&Self::Item) -> bool,
2082
    {
2083
0
        self.enumerate().find(|(_, elt)| pred(elt))
2084
0
    }
2085
    /// Find the value of the first element satisfying a predicate or return the last element, if any.
2086
    ///
2087
    /// The iterator is not advanced past the first element found.
2088
    ///
2089
    /// ```
2090
    /// use itertools::Itertools;
2091
    ///
2092
    /// let numbers = [1, 2, 3, 4];
2093
    /// assert_eq!(numbers.iter().find_or_last(|&&x| x > 5), Some(&4));
2094
    /// assert_eq!(numbers.iter().find_or_last(|&&x| x > 2), Some(&3));
2095
    /// assert_eq!(std::iter::empty::<i32>().find_or_last(|&x| x > 5), None);
2096
    ///
2097
    /// // An iterator of Results can return the first Ok or the last Err:
2098
    /// let input = vec![Err(()), Ok(11), Err(()), Ok(22)];
2099
    /// assert_eq!(input.into_iter().find_or_last(Result::is_ok), Some(Ok(11)));
2100
    ///
2101
    /// let input: Vec<Result<(), i32>> = vec![Err(11), Err(22)];
2102
    /// assert_eq!(input.into_iter().find_or_last(Result::is_ok), Some(Err(22)));
2103
    ///
2104
    /// assert_eq!(std::iter::empty::<Result<(), i32>>().find_or_last(Result::is_ok), None);
2105
    /// ```
2106
0
    fn find_or_last<P>(mut self, mut predicate: P) -> Option<Self::Item>
2107
0
    where
2108
0
        Self: Sized,
2109
0
        P: FnMut(&Self::Item) -> bool,
2110
    {
2111
0
        let mut prev = None;
2112
0
        self.find_map(|x| {
2113
0
            if predicate(&x) {
2114
0
                Some(x)
2115
            } else {
2116
0
                prev = Some(x);
2117
0
                None
2118
            }
2119
0
        })
2120
0
        .or(prev)
2121
0
    }
2122
    /// Find the value of the first element satisfying a predicate or return the first element, if any.
2123
    ///
2124
    /// The iterator is not advanced past the first element found.
2125
    ///
2126
    /// ```
2127
    /// use itertools::Itertools;
2128
    ///
2129
    /// let numbers = [1, 2, 3, 4];
2130
    /// assert_eq!(numbers.iter().find_or_first(|&&x| x > 5), Some(&1));
2131
    /// assert_eq!(numbers.iter().find_or_first(|&&x| x > 2), Some(&3));
2132
    /// assert_eq!(std::iter::empty::<i32>().find_or_first(|&x| x > 5), None);
2133
    ///
2134
    /// // An iterator of Results can return the first Ok or the first Err:
2135
    /// let input = vec![Err(()), Ok(11), Err(()), Ok(22)];
2136
    /// assert_eq!(input.into_iter().find_or_first(Result::is_ok), Some(Ok(11)));
2137
    ///
2138
    /// let input: Vec<Result<(), i32>> = vec![Err(11), Err(22)];
2139
    /// assert_eq!(input.into_iter().find_or_first(Result::is_ok), Some(Err(11)));
2140
    ///
2141
    /// assert_eq!(std::iter::empty::<Result<(), i32>>().find_or_first(Result::is_ok), None);
2142
    /// ```
2143
0
    fn find_or_first<P>(mut self, mut predicate: P) -> Option<Self::Item>
2144
0
    where
2145
0
        Self: Sized,
2146
0
        P: FnMut(&Self::Item) -> bool,
2147
    {
2148
0
        let first = self.next()?;
2149
0
        Some(if predicate(&first) {
2150
0
            first
2151
        } else {
2152
0
            self.find(|x| predicate(x)).unwrap_or(first)
2153
        })
2154
0
    }
2155
    /// Returns `true` if the given item is present in this iterator.
2156
    ///
2157
    /// This method is short-circuiting. If the given item is present in this
2158
    /// iterator, this method will consume the iterator up-to-and-including
2159
    /// the item. If the given item is not present in this iterator, the
2160
    /// iterator will be exhausted.
2161
    ///
2162
    /// ```
2163
    /// use itertools::Itertools;
2164
    ///
2165
    /// #[derive(PartialEq, Debug)]
2166
    /// enum Enum { A, B, C, D, E, }
2167
    ///
2168
    /// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter();
2169
    ///
2170
    /// // search `iter` for `B`
2171
    /// assert_eq!(iter.contains(&Enum::B), true);
2172
    /// // `B` was found, so the iterator now rests at the item after `B` (i.e, `C`).
2173
    /// assert_eq!(iter.next(), Some(Enum::C));
2174
    ///
2175
    /// // search `iter` for `E`
2176
    /// assert_eq!(iter.contains(&Enum::E), false);
2177
    /// // `E` wasn't found, so `iter` is now exhausted
2178
    /// assert_eq!(iter.next(), None);
2179
    /// ```
2180
0
    fn contains<Q>(&mut self, query: &Q) -> bool
2181
0
    where
2182
0
        Self: Sized,
2183
0
        Self::Item: Borrow<Q>,
2184
0
        Q: PartialEq + ?Sized,
2185
    {
2186
0
        self.any(|x| x.borrow() == query)
2187
0
    }
2188
2189
    /// Check whether all elements compare equal.
2190
    ///
2191
    /// Empty iterators are considered to have equal elements:
2192
    ///
2193
    /// ```
2194
    /// use itertools::Itertools;
2195
    ///
2196
    /// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
2197
    /// assert!(!data.iter().all_equal());
2198
    /// assert!(data[0..3].iter().all_equal());
2199
    /// assert!(data[3..5].iter().all_equal());
2200
    /// assert!(data[5..8].iter().all_equal());
2201
    ///
2202
    /// let data : Option<usize> = None;
2203
    /// assert!(data.into_iter().all_equal());
2204
    /// ```
2205
0
    fn all_equal(&mut self) -> bool
2206
0
    where
2207
0
        Self: Sized,
2208
0
        Self::Item: PartialEq,
2209
    {
2210
0
        match self.next() {
2211
0
            None => true,
2212
0
            Some(a) => self.all(|x| a == x),
2213
        }
2214
0
    }
2215
2216
    /// If there are elements and they are all equal, return a single copy of that element.
2217
    /// If there are no elements, return an Error containing None.
2218
    /// If there are elements and they are not all equal, return a tuple containing the first
2219
    /// two non-equal elements found.
2220
    ///
2221
    /// ```
2222
    /// use itertools::Itertools;
2223
    ///
2224
    /// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
2225
    /// assert_eq!(data.iter().all_equal_value(), Err(Some((&1, &2))));
2226
    /// assert_eq!(data[0..3].iter().all_equal_value(), Ok(&1));
2227
    /// assert_eq!(data[3..5].iter().all_equal_value(), Ok(&2));
2228
    /// assert_eq!(data[5..8].iter().all_equal_value(), Ok(&3));
2229
    ///
2230
    /// let data : Option<usize> = None;
2231
    /// assert_eq!(data.into_iter().all_equal_value(), Err(None));
2232
    /// ```
2233
    #[allow(clippy::type_complexity)]
2234
0
    fn all_equal_value(&mut self) -> Result<Self::Item, Option<(Self::Item, Self::Item)>>
2235
0
    where
2236
0
        Self: Sized,
2237
0
        Self::Item: PartialEq,
2238
    {
2239
0
        let first = self.next().ok_or(None)?;
2240
0
        let other = self.find(|x| x != &first);
2241
0
        if let Some(other) = other {
2242
0
            Err(Some((first, other)))
2243
        } else {
2244
0
            Ok(first)
2245
        }
2246
0
    }
2247
2248
    /// Check whether all elements are unique (non equal).
2249
    ///
2250
    /// Empty iterators are considered to have unique elements:
2251
    ///
2252
    /// ```
2253
    /// use itertools::Itertools;
2254
    ///
2255
    /// let data = vec![1, 2, 3, 4, 1, 5];
2256
    /// assert!(!data.iter().all_unique());
2257
    /// assert!(data[0..4].iter().all_unique());
2258
    /// assert!(data[1..6].iter().all_unique());
2259
    ///
2260
    /// let data : Option<usize> = None;
2261
    /// assert!(data.into_iter().all_unique());
2262
    /// ```
2263
    #[cfg(feature = "use_std")]
2264
0
    fn all_unique(&mut self) -> bool
2265
0
    where
2266
0
        Self: Sized,
2267
0
        Self::Item: Eq + Hash,
2268
    {
2269
0
        let mut used = HashSet::new();
2270
0
        self.all(move |elt| used.insert(elt))
2271
0
    }
2272
2273
    /// Consume the first `n` elements from the iterator eagerly,
2274
    /// and return the same iterator again.
2275
    ///
2276
    /// It works similarly to `.skip(n)` except it is eager and
2277
    /// preserves the iterator type.
2278
    ///
2279
    /// ```
2280
    /// use itertools::Itertools;
2281
    ///
2282
    /// let iter = "αβγ".chars().dropping(2);
2283
    /// itertools::assert_equal(iter, "γ".chars());
2284
    /// ```
2285
    ///
2286
    /// *Fusing notes: if the iterator is exhausted by dropping,
2287
    /// the result of calling `.next()` again depends on the iterator implementation.*
2288
0
    fn dropping(mut self, n: usize) -> Self
2289
0
    where
2290
0
        Self: Sized,
2291
    {
2292
0
        if n > 0 {
2293
0
            self.nth(n - 1);
2294
0
        }
2295
0
        self
2296
0
    }
2297
2298
    /// Consume the last `n` elements from the iterator eagerly,
2299
    /// and return the same iterator again.
2300
    ///
2301
    /// This is only possible on double ended iterators. `n` may be
2302
    /// larger than the number of elements.
2303
    ///
2304
    /// Note: This method is eager, dropping the back elements immediately and
2305
    /// preserves the iterator type.
2306
    ///
2307
    /// ```
2308
    /// use itertools::Itertools;
2309
    ///
2310
    /// let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
2311
    /// itertools::assert_equal(init, vec![0, 3, 6]);
2312
    /// ```
2313
0
    fn dropping_back(mut self, n: usize) -> Self
2314
0
    where
2315
0
        Self: Sized + DoubleEndedIterator,
2316
    {
2317
0
        if n > 0 {
2318
0
            (&mut self).rev().nth(n - 1);
2319
0
        }
2320
0
        self
2321
0
    }
2322
2323
    /// Combine all an iterator's elements into one element by using [`Extend`].
2324
    ///
2325
    /// This combinator will extend the first item with each of the rest of the
2326
    /// items of the iterator. If the iterator is empty, the default value of
2327
    /// `I::Item` is returned.
2328
    ///
2329
    /// ```rust
2330
    /// use itertools::Itertools;
2331
    ///
2332
    /// let input = vec![vec![1], vec![2, 3], vec![4, 5, 6]];
2333
    /// assert_eq!(input.into_iter().concat(),
2334
    ///            vec![1, 2, 3, 4, 5, 6]);
2335
    /// ```
2336
0
    fn concat(self) -> Self::Item
2337
0
    where
2338
0
        Self: Sized,
2339
0
        Self::Item:
2340
0
            Extend<<<Self as Iterator>::Item as IntoIterator>::Item> + IntoIterator + Default,
2341
    {
2342
0
        concat(self)
2343
0
    }
2344
2345
    /// `.collect_vec()` is simply a type specialization of [`Iterator::collect`],
2346
    /// for convenience.
2347
    #[cfg(feature = "use_alloc")]
2348
0
    fn collect_vec(self) -> Vec<Self::Item>
2349
0
    where
2350
0
        Self: Sized,
2351
    {
2352
0
        self.collect()
2353
0
    }
2354
2355
    /// `.try_collect()` is more convenient way of writing
2356
    /// `.collect::<Result<_, _>>()`
2357
    ///
2358
    /// # Example
2359
    ///
2360
    /// ```
2361
    /// use std::{fs, io};
2362
    /// use itertools::Itertools;
2363
    ///
2364
    /// fn process_dir_entries(entries: &[fs::DirEntry]) {
2365
    ///     // ...
2366
    ///     # let _ = entries;
2367
    /// }
2368
    ///
2369
    /// fn do_stuff() -> io::Result<()> {
2370
    ///     let entries: Vec<_> = fs::read_dir(".")?.try_collect()?;
2371
    ///     process_dir_entries(&entries);
2372
    ///
2373
    ///     Ok(())
2374
    /// }
2375
    ///
2376
    /// # let _ = do_stuff;
2377
    /// ```
2378
0
    fn try_collect<T, U, E>(self) -> Result<U, E>
2379
0
    where
2380
0
        Self: Sized + Iterator<Item = Result<T, E>>,
2381
0
        Result<U, E>: FromIterator<Result<T, E>>,
2382
    {
2383
0
        self.collect()
2384
0
    }
2385
2386
    /// Assign to each reference in `self` from the `from` iterator,
2387
    /// stopping at the shortest of the two iterators.
2388
    ///
2389
    /// The `from` iterator is queried for its next element before the `self`
2390
    /// iterator, and if either is exhausted the method is done.
2391
    ///
2392
    /// Return the number of elements written.
2393
    ///
2394
    /// ```
2395
    /// use itertools::Itertools;
2396
    ///
2397
    /// let mut xs = [0; 4];
2398
    /// xs.iter_mut().set_from(1..);
2399
    /// assert_eq!(xs, [1, 2, 3, 4]);
2400
    /// ```
2401
    #[inline]
2402
0
    fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize
2403
0
    where
2404
0
        Self: Iterator<Item = &'a mut A>,
2405
0
        J: IntoIterator<Item = A>,
2406
    {
2407
0
        from.into_iter()
2408
0
            .zip(self)
2409
0
            .map(|(new, old)| *old = new)
2410
0
            .count()
2411
0
    }
2412
2413
    /// Combine all iterator elements into one `String`, separated by `sep`.
2414
    ///
2415
    /// Use the `Display` implementation of each element.
2416
    ///
2417
    /// ```
2418
    /// use itertools::Itertools;
2419
    ///
2420
    /// assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
2421
    /// assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");
2422
    /// ```
2423
    #[cfg(feature = "use_alloc")]
2424
0
    fn join(&mut self, sep: &str) -> String
2425
0
    where
2426
0
        Self::Item: std::fmt::Display,
2427
    {
2428
0
        match self.next() {
2429
0
            None => String::new(),
2430
0
            Some(first_elt) => {
2431
                // estimate lower bound of capacity needed
2432
0
                let (lower, _) = self.size_hint();
2433
0
                let mut result = String::with_capacity(sep.len() * lower);
2434
0
                write!(&mut result, "{}", first_elt).unwrap();
2435
0
                self.for_each(|elt| {
2436
0
                    result.push_str(sep);
2437
0
                    write!(&mut result, "{}", elt).unwrap();
2438
0
                });
Unexecuted instantiation: <core::iter::adapters::map::Map<core::slice::iter::Iter<(&str, alloc::string::String)>, <rav1e::api::config::encoder::EncoderConfig as core::fmt::Display>::fmt::{closure#0}> as itertools::Itertools>::join::{closure#0}
Unexecuted instantiation: <_ as itertools::Itertools>::join::{closure#0}
2439
0
                result
2440
            }
2441
        }
2442
0
    }
Unexecuted instantiation: <core::iter::adapters::map::Map<core::slice::iter::Iter<(&str, alloc::string::String)>, <rav1e::api::config::encoder::EncoderConfig as core::fmt::Display>::fmt::{closure#0}> as itertools::Itertools>::join
Unexecuted instantiation: <_ as itertools::Itertools>::join
2443
2444
    /// Format all iterator elements, separated by `sep`.
2445
    ///
2446
    /// All elements are formatted (any formatting trait)
2447
    /// with `sep` inserted between each element.
2448
    ///
2449
    /// **Panics** if the formatter helper is formatted more than once.
2450
    ///
2451
    /// ```
2452
    /// use itertools::Itertools;
2453
    ///
2454
    /// let data = [1.1, 2.71828, -3.];
2455
    /// assert_eq!(
2456
    ///     format!("{:.2}", data.iter().format(", ")),
2457
    ///            "1.10, 2.72, -3.00");
2458
    /// ```
2459
0
    fn format(self, sep: &str) -> Format<Self>
2460
0
    where
2461
0
        Self: Sized,
2462
    {
2463
0
        format::new_format_default(self, sep)
2464
0
    }
2465
2466
    /// Format all iterator elements, separated by `sep`.
2467
    ///
2468
    /// This is a customizable version of [`.format()`](Itertools::format).
2469
    ///
2470
    /// The supplied closure `format` is called once per iterator element,
2471
    /// with two arguments: the element and a callback that takes a
2472
    /// `&Display` value, i.e. any reference to type that implements `Display`.
2473
    ///
2474
    /// Using `&format_args!(...)` is the most versatile way to apply custom
2475
    /// element formatting. The callback can be called multiple times if needed.
2476
    ///
2477
    /// **Panics** if the formatter helper is formatted more than once.
2478
    ///
2479
    /// ```
2480
    /// use itertools::Itertools;
2481
    ///
2482
    /// let data = [1.1, 2.71828, -3.];
2483
    /// let data_formatter = data.iter().format_with(", ", |elt, f| f(&format_args!("{:.2}", elt)));
2484
    /// assert_eq!(format!("{}", data_formatter),
2485
    ///            "1.10, 2.72, -3.00");
2486
    ///
2487
    /// // .format_with() is recursively composable
2488
    /// let matrix = [[1., 2., 3.],
2489
    ///               [4., 5., 6.]];
2490
    /// let matrix_formatter = matrix.iter().format_with("\n", |row, f| {
2491
    ///                                 f(&row.iter().format_with(", ", |elt, g| g(&elt)))
2492
    ///                              });
2493
    /// assert_eq!(format!("{}", matrix_formatter),
2494
    ///            "1, 2, 3\n4, 5, 6");
2495
    ///
2496
    ///
2497
    /// ```
2498
0
    fn format_with<F>(self, sep: &str, format: F) -> FormatWith<Self, F>
2499
0
    where
2500
0
        Self: Sized,
2501
0
        F: FnMut(Self::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result,
2502
    {
2503
0
        format::new_format(self, sep, format)
2504
0
    }
2505
2506
    /// Fold `Result` values from an iterator.
2507
    ///
2508
    /// Only `Ok` values are folded. If no error is encountered, the folded
2509
    /// value is returned inside `Ok`. Otherwise, the operation terminates
2510
    /// and returns the first `Err` value it encounters. No iterator elements are
2511
    /// consumed after the first error.
2512
    ///
2513
    /// The first accumulator value is the `start` parameter.
2514
    /// Each iteration passes the accumulator value and the next value inside `Ok`
2515
    /// to the fold function `f` and its return value becomes the new accumulator value.
2516
    ///
2517
    /// For example the sequence *Ok(1), Ok(2), Ok(3)* will result in a
2518
    /// computation like this:
2519
    ///
2520
    /// ```no_run
2521
    /// # let start = 0;
2522
    /// # let f = |x, y| x + y;
2523
    /// let mut accum = start;
2524
    /// accum = f(accum, 1);
2525
    /// accum = f(accum, 2);
2526
    /// accum = f(accum, 3);
2527
    /// # let _ = accum;
2528
    /// ```
2529
    ///
2530
    /// With a `start` value of 0 and an addition as folding function,
2531
    /// this effectively results in *((0 + 1) + 2) + 3*
2532
    ///
2533
    /// ```
2534
    /// use std::ops::Add;
2535
    /// use itertools::Itertools;
2536
    ///
2537
    /// let values = [1, 2, -2, -1, 2, 1];
2538
    /// assert_eq!(
2539
    ///     values.iter()
2540
    ///           .map(Ok::<_, ()>)
2541
    ///           .fold_ok(0, Add::add),
2542
    ///     Ok(3)
2543
    /// );
2544
    /// assert!(
2545
    ///     values.iter()
2546
    ///           .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
2547
    ///           .fold_ok(0, Add::add)
2548
    ///           .is_err()
2549
    /// );
2550
    /// ```
2551
0
    fn fold_ok<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
2552
0
    where
2553
0
        Self: Iterator<Item = Result<A, E>>,
2554
0
        F: FnMut(B, A) -> B,
2555
    {
2556
0
        for elt in self {
2557
0
            match elt {
2558
0
                Ok(v) => start = f(start, v),
2559
0
                Err(u) => return Err(u),
2560
            }
2561
        }
2562
0
        Ok(start)
2563
0
    }
2564
2565
    /// Fold `Option` values from an iterator.
2566
    ///
2567
    /// Only `Some` values are folded. If no `None` is encountered, the folded
2568
    /// value is returned inside `Some`. Otherwise, the operation terminates
2569
    /// and returns `None`. No iterator elements are consumed after the `None`.
2570
    ///
2571
    /// This is the `Option` equivalent to [`fold_ok`](Itertools::fold_ok).
2572
    ///
2573
    /// ```
2574
    /// use std::ops::Add;
2575
    /// use itertools::Itertools;
2576
    ///
2577
    /// let mut values = vec![Some(1), Some(2), Some(-2)].into_iter();
2578
    /// assert_eq!(values.fold_options(5, Add::add), Some(5 + 1 + 2 - 2));
2579
    ///
2580
    /// let mut more_values = vec![Some(2), None, Some(0)].into_iter();
2581
    /// assert!(more_values.fold_options(0, Add::add).is_none());
2582
    /// assert_eq!(more_values.next().unwrap(), Some(0));
2583
    /// ```
2584
0
    fn fold_options<A, B, F>(&mut self, mut start: B, mut f: F) -> Option<B>
2585
0
    where
2586
0
        Self: Iterator<Item = Option<A>>,
2587
0
        F: FnMut(B, A) -> B,
2588
    {
2589
0
        for elt in self {
2590
0
            match elt {
2591
0
                Some(v) => start = f(start, v),
2592
0
                None => return None,
2593
            }
2594
        }
2595
0
        Some(start)
2596
0
    }
2597
2598
    /// Accumulator of the elements in the iterator.
2599
    ///
2600
    /// Like `.fold()`, without a base case. If the iterator is
2601
    /// empty, return `None`. With just one element, return it.
2602
    /// Otherwise elements are accumulated in sequence using the closure `f`.
2603
    ///
2604
    /// ```
2605
    /// use itertools::Itertools;
2606
    ///
2607
    /// assert_eq!((0..10).fold1(|x, y| x + y).unwrap_or(0), 45);
2608
    /// assert_eq!((0..0).fold1(|x, y| x * y), None);
2609
    /// ```
2610
    #[deprecated(
2611
        note = "Use [`Iterator::reduce`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.reduce) instead",
2612
        since = "0.10.2"
2613
    )]
2614
0
    fn fold1<F>(mut self, f: F) -> Option<Self::Item>
2615
0
    where
2616
0
        F: FnMut(Self::Item, Self::Item) -> Self::Item,
2617
0
        Self: Sized,
2618
    {
2619
0
        self.next().map(move |x| self.fold(x, f))
2620
0
    }
2621
2622
    /// Accumulate the elements in the iterator in a tree-like manner.
2623
    ///
2624
    /// You can think of it as, while there's more than one item, repeatedly
2625
    /// combining adjacent items.  It does so in bottom-up-merge-sort order,
2626
    /// however, so that it needs only logarithmic stack space.
2627
    ///
2628
    /// This produces a call tree like the following (where the calls under
2629
    /// an item are done after reading that item):
2630
    ///
2631
    /// ```text
2632
    /// 1 2 3 4 5 6 7
2633
    /// │ │ │ │ │ │ │
2634
    /// └─f └─f └─f │
2635
    ///   │   │   │ │
2636
    ///   └───f   └─f
2637
    ///       │     │
2638
    ///       └─────f
2639
    /// ```
2640
    ///
2641
    /// Which, for non-associative functions, will typically produce a different
2642
    /// result than the linear call tree used by [`Iterator::reduce`]:
2643
    ///
2644
    /// ```text
2645
    /// 1 2 3 4 5 6 7
2646
    /// │ │ │ │ │ │ │
2647
    /// └─f─f─f─f─f─f
2648
    /// ```
2649
    ///
2650
    /// If `f` is associative you should also decide carefully:
2651
    ///
2652
    /// For an iterator producing `n` elements, both [`Iterator::reduce`] and `tree_reduce` will
2653
    /// call `f` `n - 1` times. However, `tree_reduce` will call `f` on earlier intermediate
2654
    /// results, which is beneficial for `f` that allocate and produce longer results for longer
2655
    /// arguments. For example if `f` combines arguments using `format!`, then `tree_reduce` will
2656
    /// operate on average on shorter arguments resulting in less bytes being allocated overall.
2657
    ///
2658
    /// Moreover, the output of `tree_reduce` is preferable to that of [`Iterator::reduce`] in
2659
    /// certain cases. For example, building a binary search tree using `tree_reduce` will result in
2660
    /// a balanced tree with height `O(ln(n))`, while [`Iterator::reduce`] will output a tree with
2661
    /// height `O(n)`, essentially a linked list.
2662
    ///
2663
    /// If `f` does not benefit from such a reordering, like `u32::wrapping_add`, prefer the
2664
    /// normal [`Iterator::reduce`] instead since it will most likely result in the generation of
2665
    /// simpler code because the compiler is able to optimize it.
2666
    ///
2667
    /// ```
2668
    /// use itertools::Itertools;
2669
    ///
2670
    /// let f = |a: String, b: String| {
2671
    ///     format!("f({a}, {b})")
2672
    /// };
2673
    ///
2674
    /// // The same tree as above
2675
    /// assert_eq!((1..8).map(|x| x.to_string()).tree_reduce(f),
2676
    ///            Some(String::from("f(f(f(1, 2), f(3, 4)), f(f(5, 6), 7))")));
2677
    ///
2678
    /// // Like reduce, an empty iterator produces None
2679
    /// assert_eq!((0..0).tree_reduce(|x, y| x * y), None);
2680
    ///
2681
    /// // tree_reduce matches reduce for associative operations...
2682
    /// assert_eq!((0..10).tree_reduce(|x, y| x + y),
2683
    ///     (0..10).reduce(|x, y| x + y));
2684
    ///
2685
    /// // ...but not for non-associative ones
2686
    /// assert_ne!((0..10).tree_reduce(|x, y| x - y),
2687
    ///     (0..10).reduce(|x, y| x - y));
2688
    ///
2689
    /// let mut total_len_reduce = 0;
2690
    /// let reduce_res = (1..100).map(|x| x.to_string())
2691
    ///     .reduce(|a, b| {
2692
    ///         let r = f(a, b);
2693
    ///         total_len_reduce += r.len();
2694
    ///         r
2695
    ///     })
2696
    ///     .unwrap();
2697
    ///
2698
    /// let mut total_len_tree_reduce = 0;
2699
    /// let tree_reduce_res = (1..100).map(|x| x.to_string())
2700
    ///     .tree_reduce(|a, b| {
2701
    ///         let r = f(a, b);
2702
    ///         total_len_tree_reduce += r.len();
2703
    ///         r
2704
    ///     })
2705
    ///     .unwrap();
2706
    ///
2707
    /// assert_eq!(total_len_reduce, 33299);
2708
    /// assert_eq!(total_len_tree_reduce, 4228);
2709
    /// assert_eq!(reduce_res.len(), tree_reduce_res.len());
2710
    /// ```
2711
0
    fn tree_reduce<F>(mut self, mut f: F) -> Option<Self::Item>
2712
0
    where
2713
0
        F: FnMut(Self::Item, Self::Item) -> Self::Item,
2714
0
        Self: Sized,
2715
    {
2716
        type State<T> = Result<T, Option<T>>;
2717
2718
0
        fn inner0<T, II, FF>(it: &mut II, f: &mut FF) -> State<T>
2719
0
        where
2720
0
            II: Iterator<Item = T>,
2721
0
            FF: FnMut(T, T) -> T,
2722
        {
2723
            // This function could be replaced with `it.next().ok_or(None)`,
2724
            // but half the useful tree_reduce work is combining adjacent items,
2725
            // so put that in a form that LLVM is more likely to optimize well.
2726
2727
0
            let a = if let Some(v) = it.next() {
2728
0
                v
2729
            } else {
2730
0
                return Err(None);
2731
            };
2732
0
            let b = if let Some(v) = it.next() {
2733
0
                v
2734
            } else {
2735
0
                return Err(Some(a));
2736
            };
2737
0
            Ok(f(a, b))
2738
0
        }
2739
2740
0
        fn inner<T, II, FF>(stop: usize, it: &mut II, f: &mut FF) -> State<T>
2741
0
        where
2742
0
            II: Iterator<Item = T>,
2743
0
            FF: FnMut(T, T) -> T,
2744
        {
2745
0
            let mut x = inner0(it, f)?;
2746
0
            for height in 0..stop {
2747
                // Try to get another tree the same size with which to combine it,
2748
                // creating a new tree that's twice as big for next time around.
2749
0
                let next = if height == 0 {
2750
0
                    inner0(it, f)
2751
                } else {
2752
0
                    inner(height, it, f)
2753
                };
2754
0
                match next {
2755
0
                    Ok(y) => x = f(x, y),
2756
2757
                    // If we ran out of items, combine whatever we did manage
2758
                    // to get.  It's better combined with the current value
2759
                    // than something in a parent frame, because the tree in
2760
                    // the parent is always as least as big as this one.
2761
0
                    Err(None) => return Err(Some(x)),
2762
0
                    Err(Some(y)) => return Err(Some(f(x, y))),
2763
                }
2764
            }
2765
0
            Ok(x)
2766
0
        }
2767
2768
0
        match inner(usize::MAX, &mut self, &mut f) {
2769
0
            Err(x) => x,
2770
0
            _ => unreachable!(),
2771
        }
2772
0
    }
2773
2774
    /// See [`.tree_reduce()`](Itertools::tree_reduce).
2775
    #[deprecated(note = "Use .tree_reduce() instead", since = "0.13.0")]
2776
0
    fn tree_fold1<F>(self, f: F) -> Option<Self::Item>
2777
0
    where
2778
0
        F: FnMut(Self::Item, Self::Item) -> Self::Item,
2779
0
        Self: Sized,
2780
    {
2781
0
        self.tree_reduce(f)
2782
0
    }
2783
2784
    /// An iterator method that applies a function, producing a single, final value.
2785
    ///
2786
    /// `fold_while()` is basically equivalent to [`Iterator::fold`] but with additional support for
2787
    /// early exit via short-circuiting.
2788
    ///
2789
    /// ```
2790
    /// use itertools::Itertools;
2791
    /// use itertools::FoldWhile::{Continue, Done};
2792
    ///
2793
    /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2794
    ///
2795
    /// let mut result = 0;
2796
    ///
2797
    /// // for loop:
2798
    /// for i in &numbers {
2799
    ///     if *i > 5 {
2800
    ///         break;
2801
    ///     }
2802
    ///     result = result + i;
2803
    /// }
2804
    ///
2805
    /// // fold:
2806
    /// let result2 = numbers.iter().fold(0, |acc, x| {
2807
    ///     if *x > 5 { acc } else { acc + x }
2808
    /// });
2809
    ///
2810
    /// // fold_while:
2811
    /// let result3 = numbers.iter().fold_while(0, |acc, x| {
2812
    ///     if *x > 5 { Done(acc) } else { Continue(acc + x) }
2813
    /// }).into_inner();
2814
    ///
2815
    /// // they're the same
2816
    /// assert_eq!(result, result2);
2817
    /// assert_eq!(result2, result3);
2818
    /// ```
2819
    ///
2820
    /// The big difference between the computations of `result2` and `result3` is that while
2821
    /// `fold()` called the provided closure for every item of the callee iterator,
2822
    /// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`.
2823
0
    fn fold_while<B, F>(&mut self, init: B, mut f: F) -> FoldWhile<B>
2824
0
    where
2825
0
        Self: Sized,
2826
0
        F: FnMut(B, Self::Item) -> FoldWhile<B>,
2827
    {
2828
        use Result::{Err as Break, Ok as Continue};
2829
2830
0
        let result = self.try_fold(
2831
0
            init,
2832
            #[inline(always)]
2833
0
            |acc, v| match f(acc, v) {
2834
0
                FoldWhile::Continue(acc) => Continue(acc),
2835
0
                FoldWhile::Done(acc) => Break(acc),
2836
0
            },
2837
        );
2838
2839
0
        match result {
2840
0
            Continue(acc) => FoldWhile::Continue(acc),
2841
0
            Break(acc) => FoldWhile::Done(acc),
2842
        }
2843
0
    }
2844
2845
    /// Iterate over the entire iterator and add all the elements.
2846
    ///
2847
    /// An empty iterator returns `None`, otherwise `Some(sum)`.
2848
    ///
2849
    /// # Panics
2850
    ///
2851
    /// When calling `sum1()` and a primitive integer type is being returned, this
2852
    /// method will panic if the computation overflows and debug assertions are
2853
    /// enabled.
2854
    ///
2855
    /// # Examples
2856
    ///
2857
    /// ```
2858
    /// use itertools::Itertools;
2859
    ///
2860
    /// let empty_sum = (1..1).sum1::<i32>();
2861
    /// assert_eq!(empty_sum, None);
2862
    ///
2863
    /// let nonempty_sum = (1..11).sum1::<i32>();
2864
    /// assert_eq!(nonempty_sum, Some(55));
2865
    /// ```
2866
0
    fn sum1<S>(mut self) -> Option<S>
2867
0
    where
2868
0
        Self: Sized,
2869
0
        S: std::iter::Sum<Self::Item>,
2870
    {
2871
0
        self.next().map(|first| once(first).chain(self).sum())
2872
0
    }
2873
2874
    /// Iterate over the entire iterator and multiply all the elements.
2875
    ///
2876
    /// An empty iterator returns `None`, otherwise `Some(product)`.
2877
    ///
2878
    /// # Panics
2879
    ///
2880
    /// When calling `product1()` and a primitive integer type is being returned,
2881
    /// method will panic if the computation overflows and debug assertions are
2882
    /// enabled.
2883
    ///
2884
    /// # Examples
2885
    /// ```
2886
    /// use itertools::Itertools;
2887
    ///
2888
    /// let empty_product = (1..1).product1::<i32>();
2889
    /// assert_eq!(empty_product, None);
2890
    ///
2891
    /// let nonempty_product = (1..11).product1::<i32>();
2892
    /// assert_eq!(nonempty_product, Some(3628800));
2893
    /// ```
2894
0
    fn product1<P>(mut self) -> Option<P>
2895
0
    where
2896
0
        Self: Sized,
2897
0
        P: std::iter::Product<Self::Item>,
2898
    {
2899
0
        self.next().map(|first| once(first).chain(self).product())
2900
0
    }
2901
2902
    /// Sort all iterator elements into a new iterator in ascending order.
2903
    ///
2904
    /// **Note:** This consumes the entire iterator, uses the
2905
    /// [`slice::sort_unstable`] method and returns the result as a new
2906
    /// iterator that owns its elements.
2907
    ///
2908
    /// This sort is unstable (i.e., may reorder equal elements).
2909
    ///
2910
    /// The sorted iterator, if directly collected to a `Vec`, is converted
2911
    /// without any extra copying or allocation cost.
2912
    ///
2913
    /// ```
2914
    /// use itertools::Itertools;
2915
    ///
2916
    /// // sort the letters of the text in ascending order
2917
    /// let text = "bdacfe";
2918
    /// itertools::assert_equal(text.chars().sorted_unstable(),
2919
    ///                         "abcdef".chars());
2920
    /// ```
2921
    #[cfg(feature = "use_alloc")]
2922
0
    fn sorted_unstable(self) -> VecIntoIter<Self::Item>
2923
0
    where
2924
0
        Self: Sized,
2925
0
        Self::Item: Ord,
2926
    {
2927
        // Use .sort_unstable() directly since it is not quite identical with
2928
        // .sort_by(Ord::cmp)
2929
0
        let mut v = Vec::from_iter(self);
2930
0
        v.sort_unstable();
2931
0
        v.into_iter()
2932
0
    }
2933
2934
    /// Sort all iterator elements into a new iterator in ascending order.
2935
    ///
2936
    /// **Note:** This consumes the entire iterator, uses the
2937
    /// [`slice::sort_unstable_by`] method and returns the result as a new
2938
    /// iterator that owns its elements.
2939
    ///
2940
    /// This sort is unstable (i.e., may reorder equal elements).
2941
    ///
2942
    /// The sorted iterator, if directly collected to a `Vec`, is converted
2943
    /// without any extra copying or allocation cost.
2944
    ///
2945
    /// ```
2946
    /// use itertools::Itertools;
2947
    ///
2948
    /// // sort people in descending order by age
2949
    /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2950
    ///
2951
    /// let oldest_people_first = people
2952
    ///     .into_iter()
2953
    ///     .sorted_unstable_by(|a, b| Ord::cmp(&b.1, &a.1))
2954
    ///     .map(|(person, _age)| person);
2955
    ///
2956
    /// itertools::assert_equal(oldest_people_first,
2957
    ///                         vec!["Jill", "Jack", "Jane", "John"]);
2958
    /// ```
2959
    #[cfg(feature = "use_alloc")]
2960
0
    fn sorted_unstable_by<F>(self, cmp: F) -> VecIntoIter<Self::Item>
2961
0
    where
2962
0
        Self: Sized,
2963
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2964
    {
2965
0
        let mut v = Vec::from_iter(self);
2966
0
        v.sort_unstable_by(cmp);
2967
0
        v.into_iter()
2968
0
    }
2969
2970
    /// Sort all iterator elements into a new iterator in ascending order.
2971
    ///
2972
    /// **Note:** This consumes the entire iterator, uses the
2973
    /// [`slice::sort_unstable_by_key`] method and returns the result as a new
2974
    /// iterator that owns its elements.
2975
    ///
2976
    /// This sort is unstable (i.e., may reorder equal elements).
2977
    ///
2978
    /// The sorted iterator, if directly collected to a `Vec`, is converted
2979
    /// without any extra copying or allocation cost.
2980
    ///
2981
    /// ```
2982
    /// use itertools::Itertools;
2983
    ///
2984
    /// // sort people in descending order by age
2985
    /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2986
    ///
2987
    /// let oldest_people_first = people
2988
    ///     .into_iter()
2989
    ///     .sorted_unstable_by_key(|x| -x.1)
2990
    ///     .map(|(person, _age)| person);
2991
    ///
2992
    /// itertools::assert_equal(oldest_people_first,
2993
    ///                         vec!["Jill", "Jack", "Jane", "John"]);
2994
    /// ```
2995
    #[cfg(feature = "use_alloc")]
2996
0
    fn sorted_unstable_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item>
2997
0
    where
2998
0
        Self: Sized,
2999
0
        K: Ord,
3000
0
        F: FnMut(&Self::Item) -> K,
3001
    {
3002
0
        let mut v = Vec::from_iter(self);
3003
0
        v.sort_unstable_by_key(f);
3004
0
        v.into_iter()
3005
0
    }
3006
3007
    /// Sort all iterator elements into a new iterator in ascending order.
3008
    ///
3009
    /// **Note:** This consumes the entire iterator, uses the
3010
    /// [`slice::sort`] method and returns the result as a new
3011
    /// iterator that owns its elements.
3012
    ///
3013
    /// This sort is stable (i.e., does not reorder equal elements).
3014
    ///
3015
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3016
    /// without any extra copying or allocation cost.
3017
    ///
3018
    /// ```
3019
    /// use itertools::Itertools;
3020
    ///
3021
    /// // sort the letters of the text in ascending order
3022
    /// let text = "bdacfe";
3023
    /// itertools::assert_equal(text.chars().sorted(),
3024
    ///                         "abcdef".chars());
3025
    /// ```
3026
    #[cfg(feature = "use_alloc")]
3027
0
    fn sorted(self) -> VecIntoIter<Self::Item>
3028
0
    where
3029
0
        Self: Sized,
3030
0
        Self::Item: Ord,
3031
    {
3032
        // Use .sort() directly since it is not quite identical with
3033
        // .sort_by(Ord::cmp)
3034
0
        let mut v = Vec::from_iter(self);
3035
0
        v.sort();
3036
0
        v.into_iter()
3037
0
    }
3038
3039
    /// Sort all iterator elements into a new iterator in ascending order.
3040
    ///
3041
    /// **Note:** This consumes the entire iterator, uses the
3042
    /// [`slice::sort_by`] method and returns the result as a new
3043
    /// iterator that owns its elements.
3044
    ///
3045
    /// This sort is stable (i.e., does not reorder equal elements).
3046
    ///
3047
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3048
    /// without any extra copying or allocation cost.
3049
    ///
3050
    /// ```
3051
    /// use itertools::Itertools;
3052
    ///
3053
    /// // sort people in descending order by age
3054
    /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 30)];
3055
    ///
3056
    /// let oldest_people_first = people
3057
    ///     .into_iter()
3058
    ///     .sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
3059
    ///     .map(|(person, _age)| person);
3060
    ///
3061
    /// itertools::assert_equal(oldest_people_first,
3062
    ///                         vec!["Jill", "Jack", "Jane", "John"]);
3063
    /// ```
3064
    #[cfg(feature = "use_alloc")]
3065
0
    fn sorted_by<F>(self, cmp: F) -> VecIntoIter<Self::Item>
3066
0
    where
3067
0
        Self: Sized,
3068
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3069
    {
3070
0
        let mut v = Vec::from_iter(self);
3071
0
        v.sort_by(cmp);
3072
0
        v.into_iter()
3073
0
    }
3074
3075
    /// Sort all iterator elements into a new iterator in ascending order.
3076
    ///
3077
    /// **Note:** This consumes the entire iterator, uses the
3078
    /// [`slice::sort_by_key`] method and returns the result as a new
3079
    /// iterator that owns its elements.
3080
    ///
3081
    /// This sort is stable (i.e., does not reorder equal elements).
3082
    ///
3083
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3084
    /// without any extra copying or allocation cost.
3085
    ///
3086
    /// ```
3087
    /// use itertools::Itertools;
3088
    ///
3089
    /// // sort people in descending order by age
3090
    /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 30)];
3091
    ///
3092
    /// let oldest_people_first = people
3093
    ///     .into_iter()
3094
    ///     .sorted_by_key(|x| -x.1)
3095
    ///     .map(|(person, _age)| person);
3096
    ///
3097
    /// itertools::assert_equal(oldest_people_first,
3098
    ///                         vec!["Jill", "Jack", "Jane", "John"]);
3099
    /// ```
3100
    #[cfg(feature = "use_alloc")]
3101
0
    fn sorted_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item>
3102
0
    where
3103
0
        Self: Sized,
3104
0
        K: Ord,
3105
0
        F: FnMut(&Self::Item) -> K,
3106
    {
3107
0
        let mut v = Vec::from_iter(self);
3108
0
        v.sort_by_key(f);
3109
0
        v.into_iter()
3110
0
    }
3111
3112
    /// Sort all iterator elements into a new iterator in ascending order. The key function is
3113
    /// called exactly once per key.
3114
    ///
3115
    /// **Note:** This consumes the entire iterator, uses the
3116
    /// [`slice::sort_by_cached_key`] method and returns the result as a new
3117
    /// iterator that owns its elements.
3118
    ///
3119
    /// This sort is stable (i.e., does not reorder equal elements).
3120
    ///
3121
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3122
    /// without any extra copying or allocation cost.
3123
    ///
3124
    /// ```
3125
    /// use itertools::Itertools;
3126
    ///
3127
    /// // sort people in descending order by age
3128
    /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 30)];
3129
    ///
3130
    /// let oldest_people_first = people
3131
    ///     .into_iter()
3132
    ///     .sorted_by_cached_key(|x| -x.1)
3133
    ///     .map(|(person, _age)| person);
3134
    ///
3135
    /// itertools::assert_equal(oldest_people_first,
3136
    ///                         vec!["Jill", "Jack", "Jane", "John"]);
3137
    /// ```
3138
    #[cfg(feature = "use_alloc")]
3139
0
    fn sorted_by_cached_key<K, F>(self, f: F) -> VecIntoIter<Self::Item>
3140
0
    where
3141
0
        Self: Sized,
3142
0
        K: Ord,
3143
0
        F: FnMut(&Self::Item) -> K,
3144
    {
3145
0
        let mut v = Vec::from_iter(self);
3146
0
        v.sort_by_cached_key(f);
3147
0
        v.into_iter()
3148
0
    }
3149
3150
    /// Sort the k smallest elements into a new iterator, in ascending order.
3151
    ///
3152
    /// **Note:** This consumes the entire iterator, and returns the result
3153
    /// as a new iterator that owns its elements.  If the input contains
3154
    /// less than k elements, the result is equivalent to `self.sorted()`.
3155
    ///
3156
    /// This is guaranteed to use `k * sizeof(Self::Item) + O(1)` memory
3157
    /// and `O(n log k)` time, with `n` the number of elements in the input.
3158
    ///
3159
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3160
    /// without any extra copying or allocation cost.
3161
    ///
3162
    /// **Note:** This is functionally-equivalent to `self.sorted().take(k)`
3163
    /// but much more efficient.
3164
    ///
3165
    /// ```
3166
    /// use itertools::Itertools;
3167
    ///
3168
    /// // A random permutation of 0..15
3169
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3170
    ///
3171
    /// let five_smallest = numbers
3172
    ///     .into_iter()
3173
    ///     .k_smallest(5);
3174
    ///
3175
    /// itertools::assert_equal(five_smallest, 0..5);
3176
    /// ```
3177
    #[cfg(feature = "use_alloc")]
3178
0
    fn k_smallest(self, k: usize) -> VecIntoIter<Self::Item>
3179
0
    where
3180
0
        Self: Sized,
3181
0
        Self::Item: Ord,
3182
    {
3183
        // The stdlib heap has optimised handling of "holes", which is not included in our heap implementation in k_smallest_general.
3184
        // While the difference is unlikely to have practical impact unless `Self::Item` is very large, this method uses the stdlib structure
3185
        // to maintain performance compared to previous versions of the crate.
3186
        use alloc::collections::BinaryHeap;
3187
3188
0
        if k == 0 {
3189
0
            self.last();
3190
0
            return Vec::new().into_iter();
3191
0
        }
3192
0
        if k == 1 {
3193
0
            return self.min().into_iter().collect_vec().into_iter();
3194
0
        }
3195
3196
0
        let mut iter = self.fuse();
3197
0
        let mut heap: BinaryHeap<_> = iter.by_ref().take(k).collect();
3198
3199
0
        iter.for_each(|i| {
3200
0
            debug_assert_eq!(heap.len(), k);
3201
            // Equivalent to heap.push(min(i, heap.pop())) but more efficient.
3202
            // This should be done with a single `.peek_mut().unwrap()` but
3203
            //  `PeekMut` sifts-down unconditionally on Rust 1.46.0 and prior.
3204
0
            if *heap.peek().unwrap() > i {
3205
0
                *heap.peek_mut().unwrap() = i;
3206
0
            }
3207
0
        });
3208
3209
0
        heap.into_sorted_vec().into_iter()
3210
0
    }
3211
3212
    /// Sort the k smallest elements into a new iterator using the provided comparison.
3213
    ///
3214
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3215
    /// without any extra copying or allocation cost.
3216
    ///
3217
    /// This corresponds to `self.sorted_by(cmp).take(k)` in the same way that
3218
    /// [`k_smallest`](Itertools::k_smallest) corresponds to `self.sorted().take(k)`,
3219
    /// in both semantics and complexity.
3220
    ///
3221
    /// Particularly, a custom heap implementation ensures the comparison is not cloned.
3222
    ///
3223
    /// ```
3224
    /// use itertools::Itertools;
3225
    ///
3226
    /// // A random permutation of 0..15
3227
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3228
    ///
3229
    /// let five_smallest = numbers
3230
    ///     .into_iter()
3231
    ///     .k_smallest_by(5, |a, b| (a % 7).cmp(&(b % 7)).then(a.cmp(b)));
3232
    ///
3233
    /// itertools::assert_equal(five_smallest, vec![0, 7, 14, 1, 8]);
3234
    /// ```
3235
    #[cfg(feature = "use_alloc")]
3236
0
    fn k_smallest_by<F>(self, k: usize, cmp: F) -> VecIntoIter<Self::Item>
3237
0
    where
3238
0
        Self: Sized,
3239
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3240
    {
3241
0
        k_smallest::k_smallest_general(self, k, cmp).into_iter()
3242
0
    }
3243
3244
    /// Return the elements producing the k smallest outputs of the provided function.
3245
    ///
3246
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3247
    /// without any extra copying or allocation cost.
3248
    ///
3249
    /// This corresponds to `self.sorted_by_key(key).take(k)` in the same way that
3250
    /// [`k_smallest`](Itertools::k_smallest) corresponds to `self.sorted().take(k)`,
3251
    /// in both semantics and complexity.
3252
    ///
3253
    /// Particularly, a custom heap implementation ensures the comparison is not cloned.
3254
    ///
3255
    /// ```
3256
    /// use itertools::Itertools;
3257
    ///
3258
    /// // A random permutation of 0..15
3259
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3260
    ///
3261
    /// let five_smallest = numbers
3262
    ///     .into_iter()
3263
    ///     .k_smallest_by_key(5, |n| (n % 7, *n));
3264
    ///
3265
    /// itertools::assert_equal(five_smallest, vec![0, 7, 14, 1, 8]);
3266
    /// ```
3267
    #[cfg(feature = "use_alloc")]
3268
0
    fn k_smallest_by_key<F, K>(self, k: usize, key: F) -> VecIntoIter<Self::Item>
3269
0
    where
3270
0
        Self: Sized,
3271
0
        F: FnMut(&Self::Item) -> K,
3272
0
        K: Ord,
3273
    {
3274
0
        self.k_smallest_by(k, k_smallest::key_to_cmp(key))
3275
0
    }
3276
3277
    /// Sort the k smallest elements into a new iterator, in ascending order, relaxing the amount of memory required.
3278
    ///
3279
    /// **Note:** This consumes the entire iterator, and returns the result
3280
    /// as a new iterator that owns its elements.  If the input contains
3281
    /// less than k elements, the result is equivalent to `self.sorted()`.
3282
    ///
3283
    /// This is guaranteed to use `2 * k * sizeof(Self::Item) + O(1)` memory
3284
    /// and `O(n + k log k)` time, with `n` the number of elements in the input,
3285
    /// meaning it uses more memory than the minimum obtained by [`k_smallest`](Itertools::k_smallest)
3286
    /// but achieves linear time in the number of elements.
3287
    ///
3288
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3289
    /// without any extra copying or allocation cost.
3290
    ///
3291
    /// **Note:** This is functionally-equivalent to `self.sorted().take(k)`
3292
    /// but much more efficient.
3293
    ///
3294
    /// ```
3295
    /// use itertools::Itertools;
3296
    ///
3297
    /// // A random permutation of 0..15
3298
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3299
    ///
3300
    /// let five_smallest = numbers
3301
    ///     .into_iter()
3302
    ///     .k_smallest_relaxed(5);
3303
    ///
3304
    /// itertools::assert_equal(five_smallest, 0..5);
3305
    /// ```
3306
    #[cfg(feature = "use_alloc")]
3307
0
    fn k_smallest_relaxed(self, k: usize) -> VecIntoIter<Self::Item>
3308
0
    where
3309
0
        Self: Sized,
3310
0
        Self::Item: Ord,
3311
    {
3312
0
        self.k_smallest_relaxed_by(k, Ord::cmp)
3313
0
    }
3314
3315
    /// Sort the k smallest elements into a new iterator using the provided comparison, relaxing the amount of memory required.
3316
    ///
3317
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3318
    /// without any extra copying or allocation cost.
3319
    ///
3320
    /// This corresponds to `self.sorted_by(cmp).take(k)` in the same way that
3321
    /// [`k_smallest_relaxed`](Itertools::k_smallest_relaxed) corresponds to `self.sorted().take(k)`,
3322
    /// in both semantics and complexity.
3323
    ///
3324
    /// ```
3325
    /// use itertools::Itertools;
3326
    ///
3327
    /// // A random permutation of 0..15
3328
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3329
    ///
3330
    /// let five_smallest = numbers
3331
    ///     .into_iter()
3332
    ///     .k_smallest_relaxed_by(5, |a, b| (a % 7).cmp(&(b % 7)).then(a.cmp(b)));
3333
    ///
3334
    /// itertools::assert_equal(five_smallest, vec![0, 7, 14, 1, 8]);
3335
    /// ```
3336
    #[cfg(feature = "use_alloc")]
3337
0
    fn k_smallest_relaxed_by<F>(self, k: usize, cmp: F) -> VecIntoIter<Self::Item>
3338
0
    where
3339
0
        Self: Sized,
3340
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3341
    {
3342
0
        k_smallest::k_smallest_relaxed_general(self, k, cmp).into_iter()
3343
0
    }
3344
3345
    /// Return the elements producing the k smallest outputs of the provided function, relaxing the amount of memory required.
3346
    ///
3347
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3348
    /// without any extra copying or allocation cost.
3349
    ///
3350
    /// This corresponds to `self.sorted_by_key(key).take(k)` in the same way that
3351
    /// [`k_smallest_relaxed`](Itertools::k_smallest_relaxed) corresponds to `self.sorted().take(k)`,
3352
    /// in both semantics and complexity.
3353
    ///
3354
    /// ```
3355
    /// use itertools::Itertools;
3356
    ///
3357
    /// // A random permutation of 0..15
3358
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3359
    ///
3360
    /// let five_smallest = numbers
3361
    ///     .into_iter()
3362
    ///     .k_smallest_relaxed_by_key(5, |n| (n % 7, *n));
3363
    ///
3364
    /// itertools::assert_equal(five_smallest, vec![0, 7, 14, 1, 8]);
3365
    /// ```
3366
    #[cfg(feature = "use_alloc")]
3367
0
    fn k_smallest_relaxed_by_key<F, K>(self, k: usize, key: F) -> VecIntoIter<Self::Item>
3368
0
    where
3369
0
        Self: Sized,
3370
0
        F: FnMut(&Self::Item) -> K,
3371
0
        K: Ord,
3372
    {
3373
0
        self.k_smallest_relaxed_by(k, k_smallest::key_to_cmp(key))
3374
0
    }
3375
3376
    /// Sort the k largest elements into a new iterator, in descending order.
3377
    ///
3378
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3379
    /// without any extra copying or allocation cost.
3380
    ///
3381
    /// It is semantically equivalent to [`k_smallest`](Itertools::k_smallest)
3382
    /// with a reversed `Ord`.
3383
    /// However, this is implemented with a custom binary heap which does not
3384
    /// have the same performance characteristics for very large `Self::Item`.
3385
    ///
3386
    /// ```
3387
    /// use itertools::Itertools;
3388
    ///
3389
    /// // A random permutation of 0..15
3390
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3391
    ///
3392
    /// let five_largest = numbers
3393
    ///     .into_iter()
3394
    ///     .k_largest(5);
3395
    ///
3396
    /// itertools::assert_equal(five_largest, vec![14, 13, 12, 11, 10]);
3397
    /// ```
3398
    #[cfg(feature = "use_alloc")]
3399
0
    fn k_largest(self, k: usize) -> VecIntoIter<Self::Item>
3400
0
    where
3401
0
        Self: Sized,
3402
0
        Self::Item: Ord,
3403
    {
3404
0
        self.k_largest_by(k, Self::Item::cmp)
3405
0
    }
3406
3407
    /// Sort the k largest elements into a new iterator using the provided comparison.
3408
    ///
3409
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3410
    /// without any extra copying or allocation cost.
3411
    ///
3412
    /// Functionally equivalent to [`k_smallest_by`](Itertools::k_smallest_by)
3413
    /// with a reversed `Ord`.
3414
    ///
3415
    /// ```
3416
    /// use itertools::Itertools;
3417
    ///
3418
    /// // A random permutation of 0..15
3419
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3420
    ///
3421
    /// let five_largest = numbers
3422
    ///     .into_iter()
3423
    ///     .k_largest_by(5, |a, b| (a % 7).cmp(&(b % 7)).then(a.cmp(b)));
3424
    ///
3425
    /// itertools::assert_equal(five_largest, vec![13, 6, 12, 5, 11]);
3426
    /// ```
3427
    #[cfg(feature = "use_alloc")]
3428
0
    fn k_largest_by<F>(self, k: usize, mut cmp: F) -> VecIntoIter<Self::Item>
3429
0
    where
3430
0
        Self: Sized,
3431
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3432
    {
3433
0
        self.k_smallest_by(k, move |a, b| cmp(b, a))
3434
0
    }
3435
3436
    /// Return the elements producing the k largest outputs of the provided function.
3437
    ///
3438
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3439
    /// without any extra copying or allocation cost.
3440
    ///
3441
    /// Functionally equivalent to [`k_smallest_by_key`](Itertools::k_smallest_by_key)
3442
    /// with a reversed `Ord`.
3443
    ///
3444
    /// ```
3445
    /// use itertools::Itertools;
3446
    ///
3447
    /// // A random permutation of 0..15
3448
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3449
    ///
3450
    /// let five_largest = numbers
3451
    ///     .into_iter()
3452
    ///     .k_largest_by_key(5, |n| (n % 7, *n));
3453
    ///
3454
    /// itertools::assert_equal(five_largest, vec![13, 6, 12, 5, 11]);
3455
    /// ```
3456
    #[cfg(feature = "use_alloc")]
3457
0
    fn k_largest_by_key<F, K>(self, k: usize, key: F) -> VecIntoIter<Self::Item>
3458
0
    where
3459
0
        Self: Sized,
3460
0
        F: FnMut(&Self::Item) -> K,
3461
0
        K: Ord,
3462
    {
3463
0
        self.k_largest_by(k, k_smallest::key_to_cmp(key))
3464
0
    }
3465
3466
    /// Sort the k largest elements into a new iterator, in descending order, relaxing the amount of memory required.
3467
    ///
3468
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3469
    /// without any extra copying or allocation cost.
3470
    ///
3471
    /// It is semantically equivalent to [`k_smallest_relaxed`](Itertools::k_smallest_relaxed)
3472
    /// with a reversed `Ord`.
3473
    ///
3474
    /// ```
3475
    /// use itertools::Itertools;
3476
    ///
3477
    /// // A random permutation of 0..15
3478
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3479
    ///
3480
    /// let five_largest = numbers
3481
    ///     .into_iter()
3482
    ///     .k_largest_relaxed(5);
3483
    ///
3484
    /// itertools::assert_equal(five_largest, vec![14, 13, 12, 11, 10]);
3485
    /// ```
3486
    #[cfg(feature = "use_alloc")]
3487
0
    fn k_largest_relaxed(self, k: usize) -> VecIntoIter<Self::Item>
3488
0
    where
3489
0
        Self: Sized,
3490
0
        Self::Item: Ord,
3491
    {
3492
0
        self.k_largest_relaxed_by(k, Self::Item::cmp)
3493
0
    }
3494
3495
    /// Sort the k largest elements into a new iterator using the provided comparison, relaxing the amount of memory required.
3496
    ///
3497
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3498
    /// without any extra copying or allocation cost.
3499
    ///
3500
    /// Functionally equivalent to [`k_smallest_relaxed_by`](Itertools::k_smallest_relaxed_by)
3501
    /// with a reversed `Ord`.
3502
    ///
3503
    /// ```
3504
    /// use itertools::Itertools;
3505
    ///
3506
    /// // A random permutation of 0..15
3507
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3508
    ///
3509
    /// let five_largest = numbers
3510
    ///     .into_iter()
3511
    ///     .k_largest_relaxed_by(5, |a, b| (a % 7).cmp(&(b % 7)).then(a.cmp(b)));
3512
    ///
3513
    /// itertools::assert_equal(five_largest, vec![13, 6, 12, 5, 11]);
3514
    /// ```
3515
    #[cfg(feature = "use_alloc")]
3516
0
    fn k_largest_relaxed_by<F>(self, k: usize, mut cmp: F) -> VecIntoIter<Self::Item>
3517
0
    where
3518
0
        Self: Sized,
3519
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3520
    {
3521
0
        self.k_smallest_relaxed_by(k, move |a, b| cmp(b, a))
3522
0
    }
3523
3524
    /// Return the elements producing the k largest outputs of the provided function, relaxing the amount of memory required.
3525
    ///
3526
    /// The sorted iterator, if directly collected to a `Vec`, is converted
3527
    /// without any extra copying or allocation cost.
3528
    ///
3529
    /// Functionally equivalent to [`k_smallest_relaxed_by_key`](Itertools::k_smallest_relaxed_by_key)
3530
    /// with a reversed `Ord`.
3531
    ///
3532
    /// ```
3533
    /// use itertools::Itertools;
3534
    ///
3535
    /// // A random permutation of 0..15
3536
    /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
3537
    ///
3538
    /// let five_largest = numbers
3539
    ///     .into_iter()
3540
    ///     .k_largest_relaxed_by_key(5, |n| (n % 7, *n));
3541
    ///
3542
    /// itertools::assert_equal(five_largest, vec![13, 6, 12, 5, 11]);
3543
    /// ```
3544
    #[cfg(feature = "use_alloc")]
3545
0
    fn k_largest_relaxed_by_key<F, K>(self, k: usize, key: F) -> VecIntoIter<Self::Item>
3546
0
    where
3547
0
        Self: Sized,
3548
0
        F: FnMut(&Self::Item) -> K,
3549
0
        K: Ord,
3550
    {
3551
0
        self.k_largest_relaxed_by(k, k_smallest::key_to_cmp(key))
3552
0
    }
3553
3554
    /// Consumes the iterator and return an iterator of the last `n` elements.
3555
    ///
3556
    /// The iterator, if directly collected to a `VecDeque`, is converted
3557
    /// without any extra copying or allocation cost.
3558
    /// If directly collected to a `Vec`, it may need some data movement
3559
    /// but no re-allocation.
3560
    ///
3561
    /// ```
3562
    /// use itertools::{assert_equal, Itertools};
3563
    ///
3564
    /// let v = vec![5, 9, 8, 4, 2, 12, 0];
3565
    /// assert_equal(v.iter().tail(3), &[2, 12, 0]);
3566
    /// assert_equal(v.iter().tail(10), &v);
3567
    ///
3568
    /// assert_equal(v.iter().tail(1), v.iter().last());
3569
    ///
3570
    /// assert_equal((0..100).tail(10), 90..100);
3571
    ///
3572
    /// assert_equal((0..100).filter(|x| x % 3 == 0).tail(10), (72..100).step_by(3));
3573
    /// ```
3574
    ///
3575
    /// For double ended iterators without side-effects, you might prefer
3576
    /// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
3577
    /// without consuming the entire iterator.
3578
    #[cfg(feature = "use_alloc")]
3579
0
    fn tail(self, n: usize) -> VecDequeIntoIter<Self::Item>
3580
0
    where
3581
0
        Self: Sized,
3582
    {
3583
0
        match n {
3584
            0 => {
3585
0
                self.last();
3586
0
                VecDeque::new()
3587
            }
3588
0
            1 => self.last().into_iter().collect(),
3589
            _ => {
3590
                // Skip the starting part of the iterator if possible.
3591
0
                let (low, _) = self.size_hint();
3592
0
                let mut iter = self.fuse().skip(low.saturating_sub(n));
3593
                // TODO: If VecDeque has a more efficient method than
3594
                // `.pop_front();.push_back(val)` in the future then maybe revisit this.
3595
0
                let mut data: Vec<_> = iter.by_ref().take(n).collect();
3596
                // Update `data` cyclically.
3597
0
                let idx = iter.fold(0, |i, val| {
3598
0
                    debug_assert_eq!(data.len(), n);
3599
0
                    data[i] = val;
3600
0
                    if i + 1 == n {
3601
0
                        0
3602
                    } else {
3603
0
                        i + 1
3604
                    }
3605
0
                });
3606
                // Respect the insertion order, efficiently.
3607
0
                let mut data = VecDeque::from(data);
3608
0
                data.rotate_left(idx);
3609
0
                data
3610
            }
3611
        }
3612
0
        .into_iter()
3613
0
    }
3614
3615
    /// Collect all iterator elements into one of two
3616
    /// partitions. Unlike [`Iterator::partition`], each partition may
3617
    /// have a distinct type.
3618
    ///
3619
    /// ```
3620
    /// use itertools::{Itertools, Either};
3621
    ///
3622
    /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
3623
    ///
3624
    /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
3625
    ///     .into_iter()
3626
    ///     .partition_map(|r| {
3627
    ///         match r {
3628
    ///             Ok(v) => Either::Left(v),
3629
    ///             Err(v) => Either::Right(v),
3630
    ///         }
3631
    ///     });
3632
    ///
3633
    /// assert_eq!(successes, [1, 2]);
3634
    /// assert_eq!(failures, [false, true]);
3635
    /// ```
3636
0
    fn partition_map<A, B, F, L, R>(self, mut predicate: F) -> (A, B)
3637
0
    where
3638
0
        Self: Sized,
3639
0
        F: FnMut(Self::Item) -> Either<L, R>,
3640
0
        A: Default + Extend<L>,
3641
0
        B: Default + Extend<R>,
3642
    {
3643
0
        let mut left = A::default();
3644
0
        let mut right = B::default();
3645
3646
0
        self.for_each(|val| match predicate(val) {
3647
0
            Either::Left(v) => left.extend(Some(v)),
3648
0
            Either::Right(v) => right.extend(Some(v)),
3649
0
        });
3650
3651
0
        (left, right)
3652
0
    }
3653
3654
    /// Partition a sequence of `Result`s into one list of all the `Ok` elements
3655
    /// and another list of all the `Err` elements.
3656
    ///
3657
    /// ```
3658
    /// use itertools::Itertools;
3659
    ///
3660
    /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
3661
    ///
3662
    /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
3663
    ///     .into_iter()
3664
    ///     .partition_result();
3665
    ///
3666
    /// assert_eq!(successes, [1, 2]);
3667
    /// assert_eq!(failures, [false, true]);
3668
    /// ```
3669
0
    fn partition_result<A, B, T, E>(self) -> (A, B)
3670
0
    where
3671
0
        Self: Iterator<Item = Result<T, E>> + Sized,
3672
0
        A: Default + Extend<T>,
3673
0
        B: Default + Extend<E>,
3674
    {
3675
0
        self.partition_map(|r| match r {
3676
0
            Ok(v) => Either::Left(v),
3677
0
            Err(v) => Either::Right(v),
3678
0
        })
3679
0
    }
3680
3681
    /// Return a `HashMap` of keys mapped to `Vec`s of values. Keys and values
3682
    /// are taken from `(Key, Value)` tuple pairs yielded by the input iterator.
3683
    ///
3684
    /// Essentially a shorthand for `.into_grouping_map().collect::<Vec<_>>()`.
3685
    ///
3686
    /// ```
3687
    /// use itertools::Itertools;
3688
    ///
3689
    /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
3690
    /// let lookup = data.into_iter().into_group_map();
3691
    ///
3692
    /// assert_eq!(lookup[&0], vec![10, 20]);
3693
    /// assert_eq!(lookup.get(&1), None);
3694
    /// assert_eq!(lookup[&2], vec![12, 42]);
3695
    /// assert_eq!(lookup[&3], vec![13, 33]);
3696
    /// ```
3697
    #[cfg(feature = "use_std")]
3698
0
    fn into_group_map<K, V>(self) -> HashMap<K, Vec<V>>
3699
0
    where
3700
0
        Self: Iterator<Item = (K, V)> + Sized,
3701
0
        K: Hash + Eq,
3702
    {
3703
0
        group_map::into_group_map(self)
3704
0
    }
3705
3706
    /// Return a `HashMap` of keys mapped to `Vec`s of values. The key is specified
3707
    /// in the closure. The values are taken from the input iterator.
3708
    ///
3709
    /// Essentially a shorthand for `.into_grouping_map_by(f).collect::<Vec<_>>()`.
3710
    ///
3711
    /// ```
3712
    /// use itertools::Itertools;
3713
    /// use std::collections::HashMap;
3714
    ///
3715
    /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
3716
    /// let lookup: HashMap<u32,Vec<(u32, u32)>> =
3717
    ///     data.clone().into_iter().into_group_map_by(|a| a.0);
3718
    ///
3719
    /// assert_eq!(lookup[&0], vec![(0,10), (0,20)]);
3720
    /// assert_eq!(lookup.get(&1), None);
3721
    /// assert_eq!(lookup[&2], vec![(2,12), (2,42)]);
3722
    /// assert_eq!(lookup[&3], vec![(3,13), (3,33)]);
3723
    ///
3724
    /// assert_eq!(
3725
    ///     data.into_iter()
3726
    ///         .into_group_map_by(|x| x.0)
3727
    ///         .into_iter()
3728
    ///         .map(|(key, values)| (key, values.into_iter().fold(0,|acc, (_,v)| acc + v )))
3729
    ///         .collect::<HashMap<u32,u32>>()[&0],
3730
    ///     30,
3731
    /// );
3732
    /// ```
3733
    #[cfg(feature = "use_std")]
3734
0
    fn into_group_map_by<K, V, F>(self, f: F) -> HashMap<K, Vec<V>>
3735
0
    where
3736
0
        Self: Iterator<Item = V> + Sized,
3737
0
        K: Hash + Eq,
3738
0
        F: FnMut(&V) -> K,
3739
    {
3740
0
        group_map::into_group_map_by(self, f)
3741
0
    }
3742
3743
    /// Constructs a `GroupingMap` to be used later with one of the efficient
3744
    /// group-and-fold operations it allows to perform.
3745
    ///
3746
    /// The input iterator must yield item in the form of `(K, V)` where the
3747
    /// value of type `K` will be used as key to identify the groups and the
3748
    /// value of type `V` as value for the folding operation.
3749
    ///
3750
    /// See [`GroupingMap`] for more informations
3751
    /// on what operations are available.
3752
    #[cfg(feature = "use_std")]
3753
0
    fn into_grouping_map<K, V>(self) -> GroupingMap<Self>
3754
0
    where
3755
0
        Self: Iterator<Item = (K, V)> + Sized,
3756
0
        K: Hash + Eq,
3757
    {
3758
0
        grouping_map::new(self)
3759
0
    }
3760
3761
    /// Constructs a `GroupingMap` to be used later with one of the efficient
3762
    /// group-and-fold operations it allows to perform.
3763
    ///
3764
    /// The values from this iterator will be used as values for the folding operation
3765
    /// while the keys will be obtained from the values by calling `key_mapper`.
3766
    ///
3767
    /// See [`GroupingMap`] for more informations
3768
    /// on what operations are available.
3769
    #[cfg(feature = "use_std")]
3770
0
    fn into_grouping_map_by<K, V, F>(self, key_mapper: F) -> GroupingMapBy<Self, F>
3771
0
    where
3772
0
        Self: Iterator<Item = V> + Sized,
3773
0
        K: Hash + Eq,
3774
0
        F: FnMut(&V) -> K,
3775
    {
3776
0
        grouping_map::new(grouping_map::new_map_for_grouping(self, key_mapper))
3777
0
    }
3778
3779
    /// Return all minimum elements of an iterator.
3780
    ///
3781
    /// # Examples
3782
    ///
3783
    /// ```
3784
    /// use itertools::Itertools;
3785
    ///
3786
    /// let a: [i32; 0] = [];
3787
    /// assert_eq!(a.iter().min_set(), Vec::<&i32>::new());
3788
    ///
3789
    /// let a = [1];
3790
    /// assert_eq!(a.iter().min_set(), vec![&1]);
3791
    ///
3792
    /// let a = [1, 2, 3, 4, 5];
3793
    /// assert_eq!(a.iter().min_set(), vec![&1]);
3794
    ///
3795
    /// let a = [1, 1, 1, 1];
3796
    /// assert_eq!(a.iter().min_set(), vec![&1, &1, &1, &1]);
3797
    /// ```
3798
    ///
3799
    /// The elements can be floats but no particular result is guaranteed
3800
    /// if an element is NaN.
3801
    #[cfg(feature = "use_alloc")]
3802
0
    fn min_set(self) -> Vec<Self::Item>
3803
0
    where
3804
0
        Self: Sized,
3805
0
        Self::Item: Ord,
3806
    {
3807
0
        extrema_set::min_set_impl(self, |_| (), |x, y, _, _| x.cmp(y))
3808
0
    }
3809
3810
    /// Return all minimum elements of an iterator, as determined by
3811
    /// the specified function.
3812
    ///
3813
    /// # Examples
3814
    ///
3815
    /// ```
3816
    /// # use std::cmp::Ordering;
3817
    /// use itertools::Itertools;
3818
    ///
3819
    /// let a: [(i32, i32); 0] = [];
3820
    /// assert_eq!(a.iter().min_set_by(|_, _| Ordering::Equal), Vec::<&(i32, i32)>::new());
3821
    ///
3822
    /// let a = [(1, 2)];
3823
    /// assert_eq!(a.iter().min_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2)]);
3824
    ///
3825
    /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3826
    /// assert_eq!(a.iter().min_set_by(|&&(_,k1), &&(_,k2)| k1.cmp(&k2)), vec![&(1, 2), &(2, 2)]);
3827
    ///
3828
    /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3829
    /// assert_eq!(a.iter().min_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3830
    /// ```
3831
    ///
3832
    /// The elements can be floats but no particular result is guaranteed
3833
    /// if an element is NaN.
3834
    #[cfg(feature = "use_alloc")]
3835
0
    fn min_set_by<F>(self, mut compare: F) -> Vec<Self::Item>
3836
0
    where
3837
0
        Self: Sized,
3838
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3839
    {
3840
0
        extrema_set::min_set_impl(self, |_| (), |x, y, _, _| compare(x, y))
3841
0
    }
3842
3843
    /// Return all minimum elements of an iterator, as determined by
3844
    /// the specified function.
3845
    ///
3846
    /// # Examples
3847
    ///
3848
    /// ```
3849
    /// use itertools::Itertools;
3850
    ///
3851
    /// let a: [(i32, i32); 0] = [];
3852
    /// assert_eq!(a.iter().min_set_by_key(|_| ()), Vec::<&(i32, i32)>::new());
3853
    ///
3854
    /// let a = [(1, 2)];
3855
    /// assert_eq!(a.iter().min_set_by_key(|&&(k,_)| k), vec![&(1, 2)]);
3856
    ///
3857
    /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3858
    /// assert_eq!(a.iter().min_set_by_key(|&&(_, k)| k), vec![&(1, 2), &(2, 2)]);
3859
    ///
3860
    /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3861
    /// assert_eq!(a.iter().min_set_by_key(|&&(k, _)| k), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3862
    /// ```
3863
    ///
3864
    /// The elements can be floats but no particular result is guaranteed
3865
    /// if an element is NaN.
3866
    #[cfg(feature = "use_alloc")]
3867
0
    fn min_set_by_key<K, F>(self, key: F) -> Vec<Self::Item>
3868
0
    where
3869
0
        Self: Sized,
3870
0
        K: Ord,
3871
0
        F: FnMut(&Self::Item) -> K,
3872
    {
3873
0
        extrema_set::min_set_impl(self, key, |_, _, kx, ky| kx.cmp(ky))
3874
0
    }
3875
3876
    /// Return all maximum elements of an iterator.
3877
    ///
3878
    /// # Examples
3879
    ///
3880
    /// ```
3881
    /// use itertools::Itertools;
3882
    ///
3883
    /// let a: [i32; 0] = [];
3884
    /// assert_eq!(a.iter().max_set(), Vec::<&i32>::new());
3885
    ///
3886
    /// let a = [1];
3887
    /// assert_eq!(a.iter().max_set(), vec![&1]);
3888
    ///
3889
    /// let a = [1, 2, 3, 4, 5];
3890
    /// assert_eq!(a.iter().max_set(), vec![&5]);
3891
    ///
3892
    /// let a = [1, 1, 1, 1];
3893
    /// assert_eq!(a.iter().max_set(), vec![&1, &1, &1, &1]);
3894
    /// ```
3895
    ///
3896
    /// The elements can be floats but no particular result is guaranteed
3897
    /// if an element is NaN.
3898
    #[cfg(feature = "use_alloc")]
3899
0
    fn max_set(self) -> Vec<Self::Item>
3900
0
    where
3901
0
        Self: Sized,
3902
0
        Self::Item: Ord,
3903
    {
3904
0
        extrema_set::max_set_impl(self, |_| (), |x, y, _, _| x.cmp(y))
3905
0
    }
3906
3907
    /// Return all maximum elements of an iterator, as determined by
3908
    /// the specified function.
3909
    ///
3910
    /// # Examples
3911
    ///
3912
    /// ```
3913
    /// # use std::cmp::Ordering;
3914
    /// use itertools::Itertools;
3915
    ///
3916
    /// let a: [(i32, i32); 0] = [];
3917
    /// assert_eq!(a.iter().max_set_by(|_, _| Ordering::Equal), Vec::<&(i32, i32)>::new());
3918
    ///
3919
    /// let a = [(1, 2)];
3920
    /// assert_eq!(a.iter().max_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2)]);
3921
    ///
3922
    /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3923
    /// assert_eq!(a.iter().max_set_by(|&&(_,k1), &&(_,k2)| k1.cmp(&k2)), vec![&(3, 9), &(5, 9)]);
3924
    ///
3925
    /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3926
    /// assert_eq!(a.iter().max_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3927
    /// ```
3928
    ///
3929
    /// The elements can be floats but no particular result is guaranteed
3930
    /// if an element is NaN.
3931
    #[cfg(feature = "use_alloc")]
3932
0
    fn max_set_by<F>(self, mut compare: F) -> Vec<Self::Item>
3933
0
    where
3934
0
        Self: Sized,
3935
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3936
    {
3937
0
        extrema_set::max_set_impl(self, |_| (), |x, y, _, _| compare(x, y))
3938
0
    }
3939
3940
    /// Return all maximum elements of an iterator, as determined by
3941
    /// the specified function.
3942
    ///
3943
    /// # Examples
3944
    ///
3945
    /// ```
3946
    /// use itertools::Itertools;
3947
    ///
3948
    /// let a: [(i32, i32); 0] = [];
3949
    /// assert_eq!(a.iter().max_set_by_key(|_| ()), Vec::<&(i32, i32)>::new());
3950
    ///
3951
    /// let a = [(1, 2)];
3952
    /// assert_eq!(a.iter().max_set_by_key(|&&(k,_)| k), vec![&(1, 2)]);
3953
    ///
3954
    /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3955
    /// assert_eq!(a.iter().max_set_by_key(|&&(_, k)| k), vec![&(3, 9), &(5, 9)]);
3956
    ///
3957
    /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3958
    /// assert_eq!(a.iter().max_set_by_key(|&&(k, _)| k), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3959
    /// ```
3960
    ///
3961
    /// The elements can be floats but no particular result is guaranteed
3962
    /// if an element is NaN.
3963
    #[cfg(feature = "use_alloc")]
3964
0
    fn max_set_by_key<K, F>(self, key: F) -> Vec<Self::Item>
3965
0
    where
3966
0
        Self: Sized,
3967
0
        K: Ord,
3968
0
        F: FnMut(&Self::Item) -> K,
3969
    {
3970
0
        extrema_set::max_set_impl(self, key, |_, _, kx, ky| kx.cmp(ky))
3971
0
    }
3972
3973
    /// Return the minimum and maximum elements in the iterator.
3974
    ///
3975
    /// The return type `MinMaxResult` is an enum of three variants:
3976
    ///
3977
    /// - `NoElements` if the iterator is empty.
3978
    /// - `OneElement(x)` if the iterator has exactly one element.
3979
    /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
3980
    ///    values are equal if and only if there is more than one
3981
    ///    element in the iterator and all elements are equal.
3982
    ///
3983
    /// On an iterator of length `n`, `minmax` does `1.5 * n` comparisons,
3984
    /// and so is faster than calling `min` and `max` separately which does
3985
    /// `2 * n` comparisons.
3986
    ///
3987
    /// # Examples
3988
    ///
3989
    /// ```
3990
    /// use itertools::Itertools;
3991
    /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3992
    ///
3993
    /// let a: [i32; 0] = [];
3994
    /// assert_eq!(a.iter().minmax(), NoElements);
3995
    ///
3996
    /// let a = [1];
3997
    /// assert_eq!(a.iter().minmax(), OneElement(&1));
3998
    ///
3999
    /// let a = [1, 2, 3, 4, 5];
4000
    /// assert_eq!(a.iter().minmax(), MinMax(&1, &5));
4001
    ///
4002
    /// let a = [1, 1, 1, 1];
4003
    /// assert_eq!(a.iter().minmax(), MinMax(&1, &1));
4004
    /// ```
4005
    ///
4006
    /// The elements can be floats but no particular result is guaranteed
4007
    /// if an element is NaN.
4008
0
    fn minmax(self) -> MinMaxResult<Self::Item>
4009
0
    where
4010
0
        Self: Sized,
4011
0
        Self::Item: PartialOrd,
4012
    {
4013
0
        minmax::minmax_impl(self, |_| (), |x, y, _, _| x < y)
4014
0
    }
4015
4016
    /// Return the minimum and maximum element of an iterator, as determined by
4017
    /// the specified function.
4018
    ///
4019
    /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
4020
    ///
4021
    /// For the minimum, the first minimal element is returned.  For the maximum,
4022
    /// the last maximal element wins.  This matches the behavior of the standard
4023
    /// [`Iterator::min`] and [`Iterator::max`] methods.
4024
    ///
4025
    /// The keys can be floats but no particular result is guaranteed
4026
    /// if a key is NaN.
4027
0
    fn minmax_by_key<K, F>(self, key: F) -> MinMaxResult<Self::Item>
4028
0
    where
4029
0
        Self: Sized,
4030
0
        K: PartialOrd,
4031
0
        F: FnMut(&Self::Item) -> K,
4032
    {
4033
0
        minmax::minmax_impl(self, key, |_, _, xk, yk| xk < yk)
4034
0
    }
4035
4036
    /// Return the minimum and maximum element of an iterator, as determined by
4037
    /// the specified comparison function.
4038
    ///
4039
    /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
4040
    ///
4041
    /// For the minimum, the first minimal element is returned.  For the maximum,
4042
    /// the last maximal element wins.  This matches the behavior of the standard
4043
    /// [`Iterator::min`] and [`Iterator::max`] methods.
4044
0
    fn minmax_by<F>(self, mut compare: F) -> MinMaxResult<Self::Item>
4045
0
    where
4046
0
        Self: Sized,
4047
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
4048
    {
4049
0
        minmax::minmax_impl(self, |_| (), |x, y, _, _| Ordering::Less == compare(x, y))
4050
0
    }
4051
4052
    /// Return the position of the maximum element in the iterator.
4053
    ///
4054
    /// If several elements are equally maximum, the position of the
4055
    /// last of them is returned.
4056
    ///
4057
    /// # Examples
4058
    ///
4059
    /// ```
4060
    /// use itertools::Itertools;
4061
    ///
4062
    /// let a: [i32; 0] = [];
4063
    /// assert_eq!(a.iter().position_max(), None);
4064
    ///
4065
    /// let a = [-3, 0, 1, 5, -10];
4066
    /// assert_eq!(a.iter().position_max(), Some(3));
4067
    ///
4068
    /// let a = [1, 1, -1, -1];
4069
    /// assert_eq!(a.iter().position_max(), Some(1));
4070
    /// ```
4071
0
    fn position_max(self) -> Option<usize>
4072
0
    where
4073
0
        Self: Sized,
4074
0
        Self::Item: Ord,
4075
    {
4076
0
        self.enumerate()
4077
0
            .max_by(|x, y| Ord::cmp(&x.1, &y.1))
4078
0
            .map(|x| x.0)
4079
0
    }
4080
4081
    /// Return the position of the maximum element in the iterator, as
4082
    /// determined by the specified function.
4083
    ///
4084
    /// If several elements are equally maximum, the position of the
4085
    /// last of them is returned.
4086
    ///
4087
    /// # Examples
4088
    ///
4089
    /// ```
4090
    /// use itertools::Itertools;
4091
    ///
4092
    /// let a: [i32; 0] = [];
4093
    /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), None);
4094
    ///
4095
    /// let a = [-3_i32, 0, 1, 5, -10];
4096
    /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(4));
4097
    ///
4098
    /// let a = [1_i32, 1, -1, -1];
4099
    /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(3));
4100
    /// ```
4101
0
    fn position_max_by_key<K, F>(self, mut key: F) -> Option<usize>
4102
0
    where
4103
0
        Self: Sized,
4104
0
        K: Ord,
4105
0
        F: FnMut(&Self::Item) -> K,
4106
    {
4107
0
        self.enumerate()
4108
0
            .max_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1)))
4109
0
            .map(|x| x.0)
4110
0
    }
4111
4112
    /// Return the position of the maximum element in the iterator, as
4113
    /// determined by the specified comparison function.
4114
    ///
4115
    /// If several elements are equally maximum, the position of the
4116
    /// last of them is returned.
4117
    ///
4118
    /// # Examples
4119
    ///
4120
    /// ```
4121
    /// use itertools::Itertools;
4122
    ///
4123
    /// let a: [i32; 0] = [];
4124
    /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), None);
4125
    ///
4126
    /// let a = [-3_i32, 0, 1, 5, -10];
4127
    /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(3));
4128
    ///
4129
    /// let a = [1_i32, 1, -1, -1];
4130
    /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(1));
4131
    /// ```
4132
0
    fn position_max_by<F>(self, mut compare: F) -> Option<usize>
4133
0
    where
4134
0
        Self: Sized,
4135
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
4136
    {
4137
0
        self.enumerate()
4138
0
            .max_by(|x, y| compare(&x.1, &y.1))
4139
0
            .map(|x| x.0)
4140
0
    }
4141
4142
    /// Return the position of the minimum element in the iterator.
4143
    ///
4144
    /// If several elements are equally minimum, the position of the
4145
    /// first of them is returned.
4146
    ///
4147
    /// # Examples
4148
    ///
4149
    /// ```
4150
    /// use itertools::Itertools;
4151
    ///
4152
    /// let a: [i32; 0] = [];
4153
    /// assert_eq!(a.iter().position_min(), None);
4154
    ///
4155
    /// let a = [-3, 0, 1, 5, -10];
4156
    /// assert_eq!(a.iter().position_min(), Some(4));
4157
    ///
4158
    /// let a = [1, 1, -1, -1];
4159
    /// assert_eq!(a.iter().position_min(), Some(2));
4160
    /// ```
4161
0
    fn position_min(self) -> Option<usize>
4162
0
    where
4163
0
        Self: Sized,
4164
0
        Self::Item: Ord,
4165
    {
4166
0
        self.enumerate()
4167
0
            .min_by(|x, y| Ord::cmp(&x.1, &y.1))
4168
0
            .map(|x| x.0)
4169
0
    }
4170
4171
    /// Return the position of the minimum element in the iterator, as
4172
    /// determined by the specified function.
4173
    ///
4174
    /// If several elements are equally minimum, the position of the
4175
    /// first of them is returned.
4176
    ///
4177
    /// # Examples
4178
    ///
4179
    /// ```
4180
    /// use itertools::Itertools;
4181
    ///
4182
    /// let a: [i32; 0] = [];
4183
    /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), None);
4184
    ///
4185
    /// let a = [-3_i32, 0, 1, 5, -10];
4186
    /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(1));
4187
    ///
4188
    /// let a = [1_i32, 1, -1, -1];
4189
    /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(0));
4190
    /// ```
4191
0
    fn position_min_by_key<K, F>(self, mut key: F) -> Option<usize>
4192
0
    where
4193
0
        Self: Sized,
4194
0
        K: Ord,
4195
0
        F: FnMut(&Self::Item) -> K,
4196
    {
4197
0
        self.enumerate()
4198
0
            .min_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1)))
4199
0
            .map(|x| x.0)
4200
0
    }
4201
4202
    /// Return the position of the minimum element in the iterator, as
4203
    /// determined by the specified comparison function.
4204
    ///
4205
    /// If several elements are equally minimum, the position of the
4206
    /// first of them is returned.
4207
    ///
4208
    /// # Examples
4209
    ///
4210
    /// ```
4211
    /// use itertools::Itertools;
4212
    ///
4213
    /// let a: [i32; 0] = [];
4214
    /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), None);
4215
    ///
4216
    /// let a = [-3_i32, 0, 1, 5, -10];
4217
    /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(4));
4218
    ///
4219
    /// let a = [1_i32, 1, -1, -1];
4220
    /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(2));
4221
    /// ```
4222
0
    fn position_min_by<F>(self, mut compare: F) -> Option<usize>
4223
0
    where
4224
0
        Self: Sized,
4225
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
4226
    {
4227
0
        self.enumerate()
4228
0
            .min_by(|x, y| compare(&x.1, &y.1))
4229
0
            .map(|x| x.0)
4230
0
    }
4231
4232
    /// Return the positions of the minimum and maximum elements in
4233
    /// the iterator.
4234
    ///
4235
    /// The return type [`MinMaxResult`] is an enum of three variants:
4236
    ///
4237
    /// - `NoElements` if the iterator is empty.
4238
    /// - `OneElement(xpos)` if the iterator has exactly one element.
4239
    /// - `MinMax(xpos, ypos)` is returned otherwise, where the
4240
    ///    element at `xpos` ≤ the element at `ypos`. While the
4241
    ///    referenced elements themselves may be equal, `xpos` cannot
4242
    ///    be equal to `ypos`.
4243
    ///
4244
    /// On an iterator of length `n`, `position_minmax` does `1.5 * n`
4245
    /// comparisons, and so is faster than calling `position_min` and
4246
    /// `position_max` separately which does `2 * n` comparisons.
4247
    ///
4248
    /// For the minimum, if several elements are equally minimum, the
4249
    /// position of the first of them is returned. For the maximum, if
4250
    /// several elements are equally maximum, the position of the last
4251
    /// of them is returned.
4252
    ///
4253
    /// The elements can be floats but no particular result is
4254
    /// guaranteed if an element is NaN.
4255
    ///
4256
    /// # Examples
4257
    ///
4258
    /// ```
4259
    /// use itertools::Itertools;
4260
    /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
4261
    ///
4262
    /// let a: [i32; 0] = [];
4263
    /// assert_eq!(a.iter().position_minmax(), NoElements);
4264
    ///
4265
    /// let a = [10];
4266
    /// assert_eq!(a.iter().position_minmax(), OneElement(0));
4267
    ///
4268
    /// let a = [-3, 0, 1, 5, -10];
4269
    /// assert_eq!(a.iter().position_minmax(), MinMax(4, 3));
4270
    ///
4271
    /// let a = [1, 1, -1, -1];
4272
    /// assert_eq!(a.iter().position_minmax(), MinMax(2, 1));
4273
    /// ```
4274
0
    fn position_minmax(self) -> MinMaxResult<usize>
4275
0
    where
4276
0
        Self: Sized,
4277
0
        Self::Item: PartialOrd,
4278
    {
4279
        use crate::MinMaxResult::{MinMax, NoElements, OneElement};
4280
0
        match minmax::minmax_impl(self.enumerate(), |_| (), |x, y, _, _| x.1 < y.1) {
4281
0
            NoElements => NoElements,
4282
0
            OneElement(x) => OneElement(x.0),
4283
0
            MinMax(x, y) => MinMax(x.0, y.0),
4284
        }
4285
0
    }
4286
4287
    /// Return the postions of the minimum and maximum elements of an
4288
    /// iterator, as determined by the specified function.
4289
    ///
4290
    /// The return value is a variant of [`MinMaxResult`] like for
4291
    /// [`position_minmax`].
4292
    ///
4293
    /// For the minimum, if several elements are equally minimum, the
4294
    /// position of the first of them is returned. For the maximum, if
4295
    /// several elements are equally maximum, the position of the last
4296
    /// of them is returned.
4297
    ///
4298
    /// The keys can be floats but no particular result is guaranteed
4299
    /// if a key is NaN.
4300
    ///
4301
    /// # Examples
4302
    ///
4303
    /// ```
4304
    /// use itertools::Itertools;
4305
    /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
4306
    ///
4307
    /// let a: [i32; 0] = [];
4308
    /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), NoElements);
4309
    ///
4310
    /// let a = [10_i32];
4311
    /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), OneElement(0));
4312
    ///
4313
    /// let a = [-3_i32, 0, 1, 5, -10];
4314
    /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(1, 4));
4315
    ///
4316
    /// let a = [1_i32, 1, -1, -1];
4317
    /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(0, 3));
4318
    /// ```
4319
    ///
4320
    /// [`position_minmax`]: Self::position_minmax
4321
0
    fn position_minmax_by_key<K, F>(self, mut key: F) -> MinMaxResult<usize>
4322
0
    where
4323
0
        Self: Sized,
4324
0
        K: PartialOrd,
4325
0
        F: FnMut(&Self::Item) -> K,
4326
    {
4327
        use crate::MinMaxResult::{MinMax, NoElements, OneElement};
4328
0
        match self.enumerate().minmax_by_key(|e| key(&e.1)) {
4329
0
            NoElements => NoElements,
4330
0
            OneElement(x) => OneElement(x.0),
4331
0
            MinMax(x, y) => MinMax(x.0, y.0),
4332
        }
4333
0
    }
4334
4335
    /// Return the postions of the minimum and maximum elements of an
4336
    /// iterator, as determined by the specified comparison function.
4337
    ///
4338
    /// The return value is a variant of [`MinMaxResult`] like for
4339
    /// [`position_minmax`].
4340
    ///
4341
    /// For the minimum, if several elements are equally minimum, the
4342
    /// position of the first of them is returned. For the maximum, if
4343
    /// several elements are equally maximum, the position of the last
4344
    /// of them is returned.
4345
    ///
4346
    /// # Examples
4347
    ///
4348
    /// ```
4349
    /// use itertools::Itertools;
4350
    /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
4351
    ///
4352
    /// let a: [i32; 0] = [];
4353
    /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), NoElements);
4354
    ///
4355
    /// let a = [10_i32];
4356
    /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), OneElement(0));
4357
    ///
4358
    /// let a = [-3_i32, 0, 1, 5, -10];
4359
    /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(4, 3));
4360
    ///
4361
    /// let a = [1_i32, 1, -1, -1];
4362
    /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(2, 1));
4363
    /// ```
4364
    ///
4365
    /// [`position_minmax`]: Self::position_minmax
4366
0
    fn position_minmax_by<F>(self, mut compare: F) -> MinMaxResult<usize>
4367
0
    where
4368
0
        Self: Sized,
4369
0
        F: FnMut(&Self::Item, &Self::Item) -> Ordering,
4370
    {
4371
        use crate::MinMaxResult::{MinMax, NoElements, OneElement};
4372
0
        match self.enumerate().minmax_by(|x, y| compare(&x.1, &y.1)) {
4373
0
            NoElements => NoElements,
4374
0
            OneElement(x) => OneElement(x.0),
4375
0
            MinMax(x, y) => MinMax(x.0, y.0),
4376
        }
4377
0
    }
4378
4379
    /// If the iterator yields exactly one element, that element will be returned, otherwise
4380
    /// an error will be returned containing an iterator that has the same output as the input
4381
    /// iterator.
4382
    ///
4383
    /// This provides an additional layer of validation over just calling `Iterator::next()`.
4384
    /// If your assumption that there should only be one element yielded is false this provides
4385
    /// the opportunity to detect and handle that, preventing errors at a distance.
4386
    ///
4387
    /// # Examples
4388
    /// ```
4389
    /// use itertools::Itertools;
4390
    ///
4391
    /// assert_eq!((0..10).filter(|&x| x == 2).exactly_one().unwrap(), 2);
4392
    /// assert!((0..10).filter(|&x| x > 1 && x < 4).exactly_one().unwrap_err().eq(2..4));
4393
    /// assert!((0..10).filter(|&x| x > 1 && x < 5).exactly_one().unwrap_err().eq(2..5));
4394
    /// assert!((0..10).filter(|&_| false).exactly_one().unwrap_err().eq(0..0));
4395
    /// ```
4396
0
    fn exactly_one(mut self) -> Result<Self::Item, ExactlyOneError<Self>>
4397
0
    where
4398
0
        Self: Sized,
4399
    {
4400
0
        match self.next() {
4401
0
            Some(first) => match self.next() {
4402
0
                Some(second) => Err(ExactlyOneError::new(
4403
0
                    Some(Either::Left([first, second])),
4404
0
                    self,
4405
0
                )),
4406
0
                None => Ok(first),
4407
            },
4408
0
            None => Err(ExactlyOneError::new(None, self)),
4409
        }
4410
0
    }
4411
4412
    /// If the iterator yields no elements, `Ok(None)` will be returned. If the iterator yields
4413
    /// exactly one element, that element will be returned, otherwise an error will be returned
4414
    /// containing an iterator that has the same output as the input iterator.
4415
    ///
4416
    /// This provides an additional layer of validation over just calling `Iterator::next()`.
4417
    /// If your assumption that there should be at most one element yielded is false this provides
4418
    /// the opportunity to detect and handle that, preventing errors at a distance.
4419
    ///
4420
    /// # Examples
4421
    /// ```
4422
    /// use itertools::Itertools;
4423
    ///
4424
    /// assert_eq!((0..10).filter(|&x| x == 2).at_most_one().unwrap(), Some(2));
4425
    /// assert!((0..10).filter(|&x| x > 1 && x < 4).at_most_one().unwrap_err().eq(2..4));
4426
    /// assert!((0..10).filter(|&x| x > 1 && x < 5).at_most_one().unwrap_err().eq(2..5));
4427
    /// assert_eq!((0..10).filter(|&_| false).at_most_one().unwrap(), None);
4428
    /// ```
4429
0
    fn at_most_one(mut self) -> Result<Option<Self::Item>, ExactlyOneError<Self>>
4430
0
    where
4431
0
        Self: Sized,
4432
    {
4433
0
        match self.next() {
4434
0
            Some(first) => match self.next() {
4435
0
                Some(second) => Err(ExactlyOneError::new(
4436
0
                    Some(Either::Left([first, second])),
4437
0
                    self,
4438
0
                )),
4439
0
                None => Ok(Some(first)),
4440
            },
4441
0
            None => Ok(None),
4442
        }
4443
0
    }
4444
4445
    /// An iterator adaptor that allows the user to peek at multiple `.next()`
4446
    /// values without advancing the base iterator.
4447
    ///
4448
    /// # Examples
4449
    /// ```
4450
    /// use itertools::Itertools;
4451
    ///
4452
    /// let mut iter = (0..10).multipeek();
4453
    /// assert_eq!(iter.peek(), Some(&0));
4454
    /// assert_eq!(iter.peek(), Some(&1));
4455
    /// assert_eq!(iter.peek(), Some(&2));
4456
    /// assert_eq!(iter.next(), Some(0));
4457
    /// assert_eq!(iter.peek(), Some(&1));
4458
    /// ```
4459
    #[cfg(feature = "use_alloc")]
4460
0
    fn multipeek(self) -> MultiPeek<Self>
4461
0
    where
4462
0
        Self: Sized,
4463
    {
4464
0
        multipeek_impl::multipeek(self)
4465
0
    }
4466
4467
    /// Collect the items in this iterator and return a `HashMap` which
4468
    /// contains each item that appears in the iterator and the number
4469
    /// of times it appears.
4470
    ///
4471
    /// # Examples
4472
    /// ```
4473
    /// # use itertools::Itertools;
4474
    /// let counts = [1, 1, 1, 3, 3, 5].iter().counts();
4475
    /// assert_eq!(counts[&1], 3);
4476
    /// assert_eq!(counts[&3], 2);
4477
    /// assert_eq!(counts[&5], 1);
4478
    /// assert_eq!(counts.get(&0), None);
4479
    /// ```
4480
    #[cfg(feature = "use_std")]
4481
0
    fn counts(self) -> HashMap<Self::Item, usize>
4482
0
    where
4483
0
        Self: Sized,
4484
0
        Self::Item: Eq + Hash,
4485
    {
4486
0
        let mut counts = HashMap::new();
4487
0
        self.for_each(|item| *counts.entry(item).or_default() += 1);
4488
0
        counts
4489
0
    }
4490
4491
    /// Collect the items in this iterator and return a `HashMap` which
4492
    /// contains each item that appears in the iterator and the number
4493
    /// of times it appears,
4494
    /// determining identity using a keying function.
4495
    ///
4496
    /// ```
4497
    /// # use itertools::Itertools;
4498
    /// struct Character {
4499
    ///   first_name: &'static str,
4500
    ///   # #[allow(dead_code)]
4501
    ///   last_name:  &'static str,
4502
    /// }
4503
    ///
4504
    /// let characters =
4505
    ///     vec![
4506
    ///         Character { first_name: "Amy",   last_name: "Pond"      },
4507
    ///         Character { first_name: "Amy",   last_name: "Wong"      },
4508
    ///         Character { first_name: "Amy",   last_name: "Santiago"  },
4509
    ///         Character { first_name: "James", last_name: "Bond"      },
4510
    ///         Character { first_name: "James", last_name: "Sullivan"  },
4511
    ///         Character { first_name: "James", last_name: "Norington" },
4512
    ///         Character { first_name: "James", last_name: "Kirk"      },
4513
    ///     ];
4514
    ///
4515
    /// let first_name_frequency =
4516
    ///     characters
4517
    ///         .into_iter()
4518
    ///         .counts_by(|c| c.first_name);
4519
    ///
4520
    /// assert_eq!(first_name_frequency["Amy"], 3);
4521
    /// assert_eq!(first_name_frequency["James"], 4);
4522
    /// assert_eq!(first_name_frequency.contains_key("Asha"), false);
4523
    /// ```
4524
    #[cfg(feature = "use_std")]
4525
0
    fn counts_by<K, F>(self, f: F) -> HashMap<K, usize>
4526
0
    where
4527
0
        Self: Sized,
4528
0
        K: Eq + Hash,
4529
0
        F: FnMut(Self::Item) -> K,
4530
    {
4531
0
        self.map(f).counts()
4532
0
    }
4533
4534
    /// Converts an iterator of tuples into a tuple of containers.
4535
    ///
4536
    /// It consumes an entire iterator of n-ary tuples, producing `n` collections, one for each
4537
    /// column.
4538
    ///
4539
    /// This function is, in some sense, the opposite of [`multizip`].
4540
    ///
4541
    /// ```
4542
    /// use itertools::Itertools;
4543
    ///
4544
    /// let inputs = vec![(1, 2, 3), (4, 5, 6), (7, 8, 9)];
4545
    ///
4546
    /// let (a, b, c): (Vec<_>, Vec<_>, Vec<_>) = inputs
4547
    ///     .into_iter()
4548
    ///     .multiunzip();
4549
    ///
4550
    /// assert_eq!(a, vec![1, 4, 7]);
4551
    /// assert_eq!(b, vec![2, 5, 8]);
4552
    /// assert_eq!(c, vec![3, 6, 9]);
4553
    /// ```
4554
0
    fn multiunzip<FromI>(self) -> FromI
4555
0
    where
4556
0
        Self: Sized + MultiUnzip<FromI>,
4557
    {
4558
0
        MultiUnzip::multiunzip(self)
4559
0
    }
4560
4561
    /// Returns the length of the iterator if one exists.
4562
    /// Otherwise return `self.size_hint()`.
4563
    ///
4564
    /// Fallible [`ExactSizeIterator::len`].
4565
    ///
4566
    /// Inherits guarantees and restrictions from [`Iterator::size_hint`].
4567
    ///
4568
    /// ```
4569
    /// use itertools::Itertools;
4570
    ///
4571
    /// assert_eq!([0; 10].iter().try_len(), Ok(10));
4572
    /// assert_eq!((10..15).try_len(), Ok(5));
4573
    /// assert_eq!((15..10).try_len(), Ok(0));
4574
    /// assert_eq!((10..).try_len(), Err((usize::MAX, None)));
4575
    /// assert_eq!((10..15).filter(|x| x % 2 == 0).try_len(), Err((0, Some(5))));
4576
    /// ```
4577
0
    fn try_len(&self) -> Result<usize, size_hint::SizeHint> {
4578
0
        let sh = self.size_hint();
4579
0
        match sh {
4580
0
            (lo, Some(hi)) if lo == hi => Ok(lo),
4581
0
            _ => Err(sh),
4582
        }
4583
0
    }
4584
}
4585
4586
impl<T> Itertools for T where T: Iterator + ?Sized {}
4587
4588
/// Return `true` if both iterables produce equal sequences
4589
/// (elements pairwise equal and sequences of the same length),
4590
/// `false` otherwise.
4591
///
4592
/// [`IntoIterator`] enabled version of [`Iterator::eq`].
4593
///
4594
/// ```
4595
/// assert!(itertools::equal(vec![1, 2, 3], 1..4));
4596
/// assert!(!itertools::equal(&[0, 0], &[0, 0, 0]));
4597
/// ```
4598
0
pub fn equal<I, J>(a: I, b: J) -> bool
4599
0
where
4600
0
    I: IntoIterator,
4601
0
    J: IntoIterator,
4602
0
    I::Item: PartialEq<J::Item>,
4603
{
4604
0
    a.into_iter().eq(b)
4605
0
}
4606
4607
/// Assert that two iterables produce equal sequences, with the same
4608
/// semantics as [`equal(a, b)`](equal).
4609
///
4610
/// **Panics** on assertion failure with a message that shows the
4611
/// two different elements and the iteration index.
4612
///
4613
/// ```should_panic
4614
/// # use itertools::assert_equal;
4615
/// assert_equal("exceed".split('c'), "excess".split('c'));
4616
/// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1'.
4617
/// ```
4618
#[track_caller]
4619
0
pub fn assert_equal<I, J>(a: I, b: J)
4620
0
where
4621
0
    I: IntoIterator,
4622
0
    J: IntoIterator,
4623
0
    I::Item: fmt::Debug + PartialEq<J::Item>,
4624
0
    J::Item: fmt::Debug,
4625
{
4626
0
    let mut ia = a.into_iter();
4627
0
    let mut ib = b.into_iter();
4628
0
    let mut i: usize = 0;
4629
    loop {
4630
0
        match (ia.next(), ib.next()) {
4631
0
            (None, None) => return,
4632
0
            (a, b) => {
4633
0
                let equal = match (&a, &b) {
4634
0
                    (Some(a), Some(b)) => a == b,
4635
0
                    _ => false,
4636
                };
4637
0
                assert!(
4638
0
                    equal,
4639
0
                    "Failed assertion {a:?} == {b:?} for iteration {i}",
4640
                    i = i,
4641
                    a = a,
4642
                    b = b
4643
                );
4644
0
                i += 1;
4645
            }
4646
        }
4647
    }
4648
0
}
4649
4650
/// Partition a sequence using predicate `pred` so that elements
4651
/// that map to `true` are placed before elements which map to `false`.
4652
///
4653
/// The order within the partitions is arbitrary.
4654
///
4655
/// Return the index of the split point.
4656
///
4657
/// ```
4658
/// use itertools::partition;
4659
///
4660
/// # // use repeated numbers to not promise any ordering
4661
/// let mut data = [7, 1, 1, 7, 1, 1, 7];
4662
/// let split_index = partition(&mut data, |elt| *elt >= 3);
4663
///
4664
/// assert_eq!(data, [7, 7, 7, 1, 1, 1, 1]);
4665
/// assert_eq!(split_index, 3);
4666
/// ```
4667
0
pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize
4668
0
where
4669
0
    I: IntoIterator<Item = &'a mut A>,
4670
0
    I::IntoIter: DoubleEndedIterator,
4671
0
    F: FnMut(&A) -> bool,
4672
{
4673
0
    let mut split_index = 0;
4674
0
    let mut iter = iter.into_iter();
4675
0
    while let Some(front) = iter.next() {
4676
0
        if !pred(front) {
4677
0
            match iter.rfind(|back| pred(back)) {
4678
0
                Some(back) => std::mem::swap(front, back),
4679
0
                None => break,
4680
            }
4681
0
        }
4682
0
        split_index += 1;
4683
    }
4684
0
    split_index
4685
0
}
4686
4687
/// An enum used for controlling the execution of `fold_while`.
4688
///
4689
/// See [`.fold_while()`](Itertools::fold_while) for more information.
4690
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
4691
pub enum FoldWhile<T> {
4692
    /// Continue folding with this value
4693
    Continue(T),
4694
    /// Fold is complete and will return this value
4695
    Done(T),
4696
}
4697
4698
impl<T> FoldWhile<T> {
4699
    /// Return the value in the continue or done.
4700
0
    pub fn into_inner(self) -> T {
4701
0
        match self {
4702
0
            Self::Continue(x) | Self::Done(x) => x,
4703
        }
4704
0
    }
4705
4706
    /// Return true if `self` is `Done`, false if it is `Continue`.
4707
0
    pub fn is_done(&self) -> bool {
4708
0
        match *self {
4709
0
            Self::Continue(_) => false,
4710
0
            Self::Done(_) => true,
4711
        }
4712
0
    }
4713
}