1 #![warn(missing_docs)]
2 #![crate_name="itertools"]
3 #![cfg_attr(not(feature = "use_std"), no_std)]
4 
5 //! Extra iterator adaptors, functions and macros.
6 //!
7 //! To extend [`Iterator`] with methods in this crate, import
8 //! the [`Itertools`] trait:
9 //!
10 //! ```
11 //! use itertools::Itertools;
12 //! ```
13 //!
14 //! Now, new methods like [`interleave`](Itertools::interleave)
15 //! are available on all iterators:
16 //!
17 //! ```
18 //! use itertools::Itertools;
19 //!
20 //! let it = (1..3).interleave(vec![-1, -2]);
21 //! itertools::assert_equal(it, vec![1, -1, 2, -2]);
22 //! ```
23 //!
24 //! Most iterator methods are also provided as functions (with the benefit
25 //! that they convert parameters using [`IntoIterator`]):
26 //!
27 //! ```
28 //! use itertools::interleave;
29 //!
30 //! for elt in interleave(&[1, 2, 3], &[2, 3, 4]) {
31 //!     /* loop body */
32 //! }
33 //! ```
34 //!
35 //! ## Crate Features
36 //!
37 //! - `use_std`
38 //!   - Enabled by default.
39 //!   - Disable to compile itertools using `#![no_std]`. This disables
40 //!     any items that depend on collections (like `group_by`, `unique`,
41 //!     `kmerge`, `join` and many more).
42 //!
43 //! ## Rust Version
44 //!
45 //! This version of itertools requires Rust 1.32 or later.
46 #![doc(html_root_url="https://docs.rs/itertools/0.8/")]
47 
48 #[cfg(not(feature = "use_std"))]
49 extern crate core as std;
50 
51 #[cfg(feature = "use_alloc")]
52 extern crate alloc;
53 
54 #[cfg(feature = "use_alloc")]
55 use alloc::{
56     string::String,
57     vec::Vec,
58 };
59 
60 pub use either::Either;
61 
62 use core::borrow::Borrow;
63 #[cfg(feature = "use_std")]
64 use std::collections::HashMap;
65 use std::iter::{IntoIterator, once};
66 use std::cmp::Ordering;
67 use std::fmt;
68 #[cfg(feature = "use_std")]
69 use std::collections::HashSet;
70 #[cfg(feature = "use_std")]
71 use std::hash::Hash;
72 #[cfg(feature = "use_alloc")]
73 use std::fmt::Write;
74 #[cfg(feature = "use_alloc")]
75 type VecIntoIter<T> = alloc::vec::IntoIter<T>;
76 #[cfg(feature = "use_alloc")]
77 use std::iter::FromIterator;
78 
79 #[macro_use]
80 mod impl_macros;
81 
82 // for compatibility with no std and macros
83 #[doc(hidden)]
84 pub use std::iter as __std_iter;
85 
86 /// The concrete iterator types.
87 pub mod structs {
88     pub use crate::adaptors::{
89         Dedup,
90         DedupBy,
91         DedupWithCount,
92         DedupByWithCount,
93         Interleave,
94         InterleaveShortest,
95         FilterMapOk,
96         FilterOk,
97         Product,
98         PutBack,
99         Batching,
100         MapInto,
101         MapOk,
102         Merge,
103         MergeBy,
104         TakeWhileRef,
105         WhileSome,
106         Coalesce,
107         TupleCombinations,
108         Positions,
109         Update,
110     };
111     #[allow(deprecated)]
112     pub use crate::adaptors::{MapResults, Step};
113     #[cfg(feature = "use_alloc")]
114     pub use crate::adaptors::MultiProduct;
115     #[cfg(feature = "use_alloc")]
116     pub use crate::combinations::Combinations;
117     #[cfg(feature = "use_alloc")]
118     pub use crate::combinations_with_replacement::CombinationsWithReplacement;
119     pub use crate::cons_tuples_impl::ConsTuples;
120     pub use crate::exactly_one_err::ExactlyOneError;
121     pub use crate::format::{Format, FormatWith};
122     pub use crate::flatten_ok::FlattenOk;
123     #[cfg(feature = "use_std")]
124     pub use crate::grouping_map::{GroupingMap, GroupingMapBy};
125     #[cfg(feature = "use_alloc")]
126     pub use crate::groupbylazy::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups};
127     pub use crate::intersperse::{Intersperse, IntersperseWith};
128     #[cfg(feature = "use_alloc")]
129     pub use crate::kmerge_impl::{KMerge, KMergeBy};
130     pub use crate::merge_join::MergeJoinBy;
131     #[cfg(feature = "use_alloc")]
132     pub use crate::multipeek_impl::MultiPeek;
133     #[cfg(feature = "use_alloc")]
134     pub use crate::peek_nth::PeekNth;
135     pub use crate::pad_tail::PadUsing;
136     pub use crate::peeking_take_while::PeekingTakeWhile;
137     #[cfg(feature = "use_alloc")]
138     pub use crate::permutations::Permutations;
139     pub use crate::process_results_impl::ProcessResults;
140     #[cfg(feature = "use_alloc")]
141     pub use crate::powerset::Powerset;
142     #[cfg(feature = "use_alloc")]
143     pub use crate::put_back_n_impl::PutBackN;
144     #[cfg(feature = "use_alloc")]
145     pub use crate::rciter_impl::RcIter;
146     pub use crate::repeatn::RepeatN;
147     #[allow(deprecated)]
148     pub use crate::sources::{RepeatCall, Unfold, Iterate};
149     #[cfg(feature = "use_alloc")]
150     pub use crate::tee::Tee;
151     pub use crate::tuple_impl::{TupleBuffer, TupleWindows, CircularTupleWindows, Tuples};
152     #[cfg(feature = "use_std")]
153     pub use crate::duplicates_impl::{Duplicates, DuplicatesBy};
154     #[cfg(feature = "use_std")]
155     pub use crate::unique_impl::{Unique, UniqueBy};
156     pub use crate::with_position::WithPosition;
157     pub use crate::zip_eq_impl::ZipEq;
158     pub use crate::zip_longest::ZipLongest;
159     pub use crate::ziptuple::Zip;
160 }
161 
162 /// Traits helpful for using certain `Itertools` methods in generic contexts.
163 pub mod traits {
164     pub use crate::tuple_impl::HomogeneousTuple;
165 }
166 
167 #[allow(deprecated)]
168 pub use crate::structs::*;
169 pub use crate::concat_impl::concat;
170 pub use crate::cons_tuples_impl::cons_tuples;
171 pub use crate::diff::diff_with;
172 pub use crate::diff::Diff;
173 #[cfg(feature = "use_alloc")]
174 pub use crate::kmerge_impl::{kmerge_by};
175 pub use crate::minmax::MinMaxResult;
176 pub use crate::peeking_take_while::PeekingNext;
177 pub use crate::process_results_impl::process_results;
178 pub use crate::repeatn::repeat_n;
179 #[allow(deprecated)]
180 pub use crate::sources::{repeat_call, unfold, iterate};
181 pub use crate::with_position::Position;
182 pub use crate::ziptuple::multizip;
183 mod adaptors;
184 mod either_or_both;
185 pub use crate::either_or_both::EitherOrBoth;
186 #[doc(hidden)]
187 pub mod free;
188 #[doc(inline)]
189 pub use crate::free::*;
190 mod concat_impl;
191 mod cons_tuples_impl;
192 #[cfg(feature = "use_alloc")]
193 mod combinations;
194 #[cfg(feature = "use_alloc")]
195 mod combinations_with_replacement;
196 mod exactly_one_err;
197 mod diff;
198 mod flatten_ok;
199 mod format;
200 #[cfg(feature = "use_std")]
201 mod grouping_map;
202 #[cfg(feature = "use_alloc")]
203 mod group_map;
204 #[cfg(feature = "use_alloc")]
205 mod groupbylazy;
206 mod intersperse;
207 #[cfg(feature = "use_alloc")]
208 mod k_smallest;
209 #[cfg(feature = "use_alloc")]
210 mod kmerge_impl;
211 #[cfg(feature = "use_alloc")]
212 mod lazy_buffer;
213 mod merge_join;
214 mod minmax;
215 #[cfg(feature = "use_alloc")]
216 mod multipeek_impl;
217 mod pad_tail;
218 #[cfg(feature = "use_alloc")]
219 mod peek_nth;
220 mod peeking_take_while;
221 #[cfg(feature = "use_alloc")]
222 mod permutations;
223 #[cfg(feature = "use_alloc")]
224 mod powerset;
225 mod process_results_impl;
226 #[cfg(feature = "use_alloc")]
227 mod put_back_n_impl;
228 #[cfg(feature = "use_alloc")]
229 mod rciter_impl;
230 mod repeatn;
231 mod size_hint;
232 mod sources;
233 #[cfg(feature = "use_alloc")]
234 mod tee;
235 mod tuple_impl;
236 #[cfg(feature = "use_std")]
237 mod duplicates_impl;
238 #[cfg(feature = "use_std")]
239 mod unique_impl;
240 mod with_position;
241 mod zip_eq_impl;
242 mod zip_longest;
243 mod ziptuple;
244 
245 #[macro_export]
246 /// Create an iterator over the “cartesian product” of iterators.
247 ///
248 /// Iterator element type is like `(A, B, ..., E)` if formed
249 /// from iterators `(I, J, ..., M)` with element types `I::Item = A`, `J::Item = B`, etc.
250 ///
251 /// ```
252 /// # use itertools::iproduct;
253 /// #
254 /// # fn main() {
255 /// // Iterate over the coordinates of a 4 x 4 x 4 grid
256 /// // from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
257 /// for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
258 ///    // ..
259 /// }
260 /// # }
261 /// ```
262 macro_rules! iproduct {
263     (@flatten $I:expr,) => (
264         $I
265     );
266     (@flatten $I:expr, $J:expr, $($K:expr,)*) => (
267         $crate::iproduct!(@flatten $crate::cons_tuples($crate::iproduct!($I, $J)), $($K,)*)
268     );
269     ($I:expr) => (
270         $crate::__std_iter::IntoIterator::into_iter($I)
271     );
272     ($I:expr, $J:expr) => (
273         $crate::Itertools::cartesian_product($crate::iproduct!($I), $crate::iproduct!($J))
274     );
275     ($I:expr, $J:expr, $($K:expr),+) => (
276         $crate::iproduct!(@flatten $crate::iproduct!($I, $J), $($K,)+)
277     );
278 }
279 
280 #[macro_export]
281 /// Create an iterator running multiple iterators in lockstep.
282 ///
283 /// The `izip!` iterator yields elements until any subiterator
284 /// returns `None`.
285 ///
286 /// This is a version of the standard ``.zip()`` that's supporting more than
287 /// two iterators. The iterator element type is a tuple with one element
288 /// from each of the input iterators. Just like ``.zip()``, the iteration stops
289 /// when the shortest of the inputs reaches its end.
290 ///
291 /// **Note:** The result of this macro is in the general case an iterator
292 /// composed of repeated `.zip()` and a `.map()`; it has an anonymous type.
293 /// The special cases of one and two arguments produce the equivalent of
294 /// `$a.into_iter()` and `$a.into_iter().zip($b)` respectively.
295 ///
296 /// Prefer this macro `izip!()` over [`multizip`] for the performance benefits
297 /// of using the standard library `.zip()`.
298 ///
299 /// ```
300 /// # use itertools::izip;
301 /// #
302 /// # fn main() {
303 ///
304 /// // iterate over three sequences side-by-side
305 /// let mut results = [0, 0, 0, 0];
306 /// let inputs = [3, 7, 9, 6];
307 ///
308 /// for (r, index, input) in izip!(&mut results, 0..10, &inputs) {
309 ///     *r = index * 10 + input;
310 /// }
311 ///
312 /// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]);
313 /// # }
314 /// ```
315 macro_rules! izip {
316     // @closure creates a tuple-flattening closure for .map() call. usage:
317     // @closure partial_pattern => partial_tuple , rest , of , iterators
318     // eg. izip!( @closure ((a, b), c) => (a, b, c) , dd , ee )
319     ( @closure $p:pat => $tup:expr ) => {
320         |$p| $tup
321     };
322 
323     // The "b" identifier is a different identifier on each recursion level thanks to hygiene.
324     ( @closure $p:pat => ( $($tup:tt)* ) , $_iter:expr $( , $tail:expr )* ) => {
325         $crate::izip!(@closure ($p, b) => ( $($tup)*, b ) $( , $tail )*)
326     };
327 
328     // unary
329     ($first:expr $(,)*) => {
330         $crate::__std_iter::IntoIterator::into_iter($first)
331     };
332 
333     // binary
334     ($first:expr, $second:expr $(,)*) => {
335         $crate::izip!($first)
336             .zip($second)
337     };
338 
339     // n-ary where n > 2
340     ( $first:expr $( , $rest:expr )* $(,)* ) => {
341         $crate::izip!($first)
342             $(
343                 .zip($rest)
344             )*
345             .map(
346                 $crate::izip!(@closure a => (a) $( , $rest )*)
347             )
348     };
349 }
350 
351 #[macro_export]
352 /// [Chain][`chain`] zero or more iterators together into one sequence.
353 ///
354 /// The comma-separated arguments must implement [`IntoIterator`].
355 /// The final argument may be followed by a trailing comma.
356 ///
357 /// [`chain`]: Iterator::chain
358 ///
359 /// # Examples
360 ///
361 /// Empty invocations of `chain!` expand to an invocation of [`std::iter::empty`]:
362 /// ```
363 /// use std::iter;
364 /// use itertools::chain;
365 ///
366 /// let _: iter::Empty<()> = chain!();
367 /// let _: iter::Empty<i8> = chain!();
368 /// ```
369 ///
370 /// Invocations of `chain!` with one argument expand to [`arg.into_iter()`](IntoIterator):
371 /// ```
372 /// use std::{ops::Range, slice};
373 /// use itertools::chain;
374 /// let _: <Range<_> as IntoIterator>::IntoIter = chain!((2..6),); // trailing comma optional!
375 /// let _:     <&[_] as IntoIterator>::IntoIter = chain!(&[2, 3, 4]);
376 /// ```
377 ///
378 /// Invocations of `chain!` with multiple arguments [`.into_iter()`](IntoIterator) each
379 /// argument, and then [`chain`] them together:
380 /// ```
381 /// use std::{iter::*, ops::Range, slice};
382 /// use itertools::{assert_equal, chain};
383 ///
384 /// // e.g., this:
385 /// let with_macro:  Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
386 ///     chain![once(&0), repeat(&1).take(2), &[2, 3, 5],];
387 ///
388 /// // ...is equivalant to this:
389 /// let with_method: Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
390 ///     once(&0)
391 ///         .chain(repeat(&1).take(2))
392 ///         .chain(&[2, 3, 5]);
393 ///
394 /// assert_equal(with_macro, with_method);
395 /// ```
396 macro_rules! chain {
397     () => {
398         core::iter::empty()
399     };
400     ($first:expr $(, $rest:expr )* $(,)?) => {
401         {
402             let iter = core::iter::IntoIterator::into_iter($first);
403             $(
404                 let iter =
405                     core::iter::Iterator::chain(
406                         iter,
407                         core::iter::IntoIterator::into_iter($rest));
408             )*
409             iter
410         }
411     };
412 }
413 
414 /// An [`Iterator`] blanket implementation that provides extra adaptors and
415 /// methods.
416 ///
417 /// This trait defines a number of methods. They are divided into two groups:
418 ///
419 /// * *Adaptors* take an iterator and parameter as input, and return
420 /// a new iterator value. These are listed first in the trait. An example
421 /// of an adaptor is [`.interleave()`](Itertools::interleave)
422 ///
423 /// * *Regular methods* are those that don't return iterators and instead
424 /// return a regular value of some other kind.
425 /// [`.next_tuple()`](Itertools::next_tuple) is an example and the first regular
426 /// method in the list.
427 pub trait Itertools : Iterator {
428     // adaptors
429 
430     /// Alternate elements from two iterators until both have run out.
431     ///
432     /// Iterator element type is `Self::Item`.
433     ///
434     /// This iterator is *fused*.
435     ///
436     /// ```
437     /// use itertools::Itertools;
438     ///
439     /// let it = (1..7).interleave(vec![-1, -2]);
440     /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
441     /// ```
interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter> where J: IntoIterator<Item = Self::Item>, Self: Sized442     fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter>
443         where J: IntoIterator<Item = Self::Item>,
444               Self: Sized
445     {
446         interleave(self, other)
447     }
448 
449     /// Alternate elements from two iterators until at least one of them has run
450     /// out.
451     ///
452     /// Iterator element type is `Self::Item`.
453     ///
454     /// ```
455     /// use itertools::Itertools;
456     ///
457     /// let it = (1..7).interleave_shortest(vec![-1, -2]);
458     /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]);
459     /// ```
interleave_shortest<J>(self, other: J) -> InterleaveShortest<Self, J::IntoIter> where J: IntoIterator<Item = Self::Item>, Self: Sized460     fn interleave_shortest<J>(self, other: J) -> InterleaveShortest<Self, J::IntoIter>
461         where J: IntoIterator<Item = Self::Item>,
462               Self: Sized
463     {
464         adaptors::interleave_shortest(self, other.into_iter())
465     }
466 
467     /// An iterator adaptor to insert a particular value
468     /// between each element of the adapted iterator.
469     ///
470     /// Iterator element type is `Self::Item`.
471     ///
472     /// This iterator is *fused*.
473     ///
474     /// ```
475     /// use itertools::Itertools;
476     ///
477     /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]);
478     /// ```
intersperse(self, element: Self::Item) -> Intersperse<Self> where Self: Sized, Self::Item: Clone479     fn intersperse(self, element: Self::Item) -> Intersperse<Self>
480         where Self: Sized,
481               Self::Item: Clone
482     {
483         intersperse::intersperse(self, element)
484     }
485 
486     /// An iterator adaptor to insert a particular value created by a function
487     /// between each element of the adapted iterator.
488     ///
489     /// Iterator element type is `Self::Item`.
490     ///
491     /// This iterator is *fused*.
492     ///
493     /// ```
494     /// use itertools::Itertools;
495     ///
496     /// let mut i = 10;
497     /// itertools::assert_equal((0..3).intersperse_with(|| { i -= 1; i }), vec![0, 9, 1, 8, 2]);
498     /// assert_eq!(i, 8);
499     /// ```
intersperse_with<F>(self, element: F) -> IntersperseWith<Self, F> where Self: Sized, F: FnMut() -> Self::Item500     fn intersperse_with<F>(self, element: F) -> IntersperseWith<Self, F>
501         where Self: Sized,
502         F: FnMut() -> Self::Item
503     {
504         intersperse::intersperse_with(self, element)
505     }
506 
507     /// Create an iterator which iterates over both this and the specified
508     /// iterator simultaneously, yielding pairs of two optional elements.
509     ///
510     /// This iterator is *fused*.
511     ///
512     /// As long as neither input iterator is exhausted yet, it yields two values
513     /// via `EitherOrBoth::Both`.
514     ///
515     /// When the parameter iterator is exhausted, it only yields a value from the
516     /// `self` iterator via `EitherOrBoth::Left`.
517     ///
518     /// When the `self` iterator is exhausted, it only yields a value from the
519     /// parameter iterator via `EitherOrBoth::Right`.
520     ///
521     /// When both iterators return `None`, all further invocations of `.next()`
522     /// will return `None`.
523     ///
524     /// Iterator element type is
525     /// [`EitherOrBoth<Self::Item, J::Item>`](EitherOrBoth).
526     ///
527     /// ```rust
528     /// use itertools::EitherOrBoth::{Both, Right};
529     /// use itertools::Itertools;
530     /// let it = (0..1).zip_longest(1..3);
531     /// itertools::assert_equal(it, vec![Both(0, 1), Right(2)]);
532     /// ```
533     #[inline]
zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter> where J: IntoIterator, Self: Sized534     fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter>
535         where J: IntoIterator,
536               Self: Sized
537     {
538         zip_longest::zip_longest(self, other.into_iter())
539     }
540 
541     /// Create an iterator which iterates over both this and the specified
542     /// iterator simultaneously, yielding pairs of elements.
543     ///
544     /// **Panics** if the iterators reach an end and they are not of equal
545     /// lengths.
546     #[inline]
zip_eq<J>(self, other: J) -> ZipEq<Self, J::IntoIter> where J: IntoIterator, Self: Sized547     fn zip_eq<J>(self, other: J) -> ZipEq<Self, J::IntoIter>
548         where J: IntoIterator,
549               Self: Sized
550     {
551         zip_eq(self, other)
552     }
553 
554     /// A “meta iterator adaptor”. Its closure receives a reference to the
555     /// iterator and may pick off as many elements as it likes, to produce the
556     /// next iterator element.
557     ///
558     /// Iterator element type is `B`.
559     ///
560     /// ```
561     /// use itertools::Itertools;
562     ///
563     /// // An adaptor that gathers elements in pairs
564     /// let pit = (0..4).batching(|it| {
565     ///            match it.next() {
566     ///                None => None,
567     ///                Some(x) => match it.next() {
568     ///                    None => None,
569     ///                    Some(y) => Some((x, y)),
570     ///                }
571     ///            }
572     ///        });
573     ///
574     /// itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
575     /// ```
576     ///
batching<B, F>(self, f: F) -> Batching<Self, F> where F: FnMut(&mut Self) -> Option<B>, Self: Sized577     fn batching<B, F>(self, f: F) -> Batching<Self, F>
578         where F: FnMut(&mut Self) -> Option<B>,
579               Self: Sized
580     {
581         adaptors::batching(self, f)
582     }
583 
584     /// Return an *iterable* that can group iterator elements.
585     /// Consecutive elements that map to the same key (“runs”), are assigned
586     /// to the same group.
587     ///
588     /// `GroupBy` is the storage for the lazy grouping operation.
589     ///
590     /// If the groups are consumed in order, or if each group's iterator is
591     /// dropped without keeping it around, then `GroupBy` uses no
592     /// allocations.  It needs allocations only if several group iterators
593     /// are alive at the same time.
594     ///
595     /// This type implements [`IntoIterator`] (it is **not** an iterator
596     /// itself), because the group iterators need to borrow from this
597     /// value. It should be stored in a local variable or temporary and
598     /// iterated.
599     ///
600     /// Iterator element type is `(K, Group)`: the group's key and the
601     /// group iterator.
602     ///
603     /// ```
604     /// use itertools::Itertools;
605     ///
606     /// // group data into runs of larger than zero or not.
607     /// let data = vec![1, 3, -2, -2, 1, 0, 1, 2];
608     /// // groups:     |---->|------>|--------->|
609     ///
610     /// // Note: The `&` is significant here, `GroupBy` is iterable
611     /// // only by reference. You can also call `.into_iter()` explicitly.
612     /// let mut data_grouped = Vec::new();
613     /// for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) {
614     ///     data_grouped.push((key, group.collect()));
615     /// }
616     /// assert_eq!(data_grouped, vec![(true, vec![1, 3]), (false, vec![-2, -2]), (true, vec![1, 0, 1, 2])]);
617     /// ```
618     #[cfg(feature = "use_alloc")]
group_by<K, F>(self, key: F) -> GroupBy<K, Self, F> where Self: Sized, F: FnMut(&Self::Item) -> K, K: PartialEq,619     fn group_by<K, F>(self, key: F) -> GroupBy<K, Self, F>
620         where Self: Sized,
621               F: FnMut(&Self::Item) -> K,
622               K: PartialEq,
623     {
624         groupbylazy::new(self, key)
625     }
626 
627     /// Return an *iterable* that can chunk the iterator.
628     ///
629     /// Yield subiterators (chunks) that each yield a fixed number elements,
630     /// determined by `size`. The last chunk will be shorter if there aren't
631     /// enough elements.
632     ///
633     /// `IntoChunks` is based on `GroupBy`: it is iterable (implements
634     /// `IntoIterator`, **not** `Iterator`), and it only buffers if several
635     /// chunk iterators are alive at the same time.
636     ///
637     /// Iterator element type is `Chunk`, each chunk's iterator.
638     ///
639     /// **Panics** if `size` is 0.
640     ///
641     /// ```
642     /// use itertools::Itertools;
643     ///
644     /// let data = vec![1, 1, 2, -2, 6, 0, 3, 1];
645     /// //chunk size=3 |------->|-------->|--->|
646     ///
647     /// // Note: The `&` is significant here, `IntoChunks` is iterable
648     /// // only by reference. You can also call `.into_iter()` explicitly.
649     /// for chunk in &data.into_iter().chunks(3) {
650     ///     // Check that the sum of each chunk is 4.
651     ///     assert_eq!(4, chunk.sum());
652     /// }
653     /// ```
654     #[cfg(feature = "use_alloc")]
chunks(self, size: usize) -> IntoChunks<Self> where Self: Sized,655     fn chunks(self, size: usize) -> IntoChunks<Self>
656         where Self: Sized,
657     {
658         assert!(size != 0);
659         groupbylazy::new_chunks(self, size)
660     }
661 
662     /// Return an iterator over all contiguous windows producing tuples of
663     /// a specific size (up to 4).
664     ///
665     /// `tuple_windows` clones the iterator elements so that they can be
666     /// part of successive windows, this makes it most suited for iterators
667     /// of references and other values that are cheap to copy.
668     ///
669     /// ```
670     /// use itertools::Itertools;
671     /// let mut v = Vec::new();
672     ///
673     /// // pairwise iteration
674     /// for (a, b) in (1..5).tuple_windows() {
675     ///     v.push((a, b));
676     /// }
677     /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4)]);
678     ///
679     /// let mut it = (1..5).tuple_windows();
680     /// assert_eq!(Some((1, 2, 3)), it.next());
681     /// assert_eq!(Some((2, 3, 4)), it.next());
682     /// assert_eq!(None, it.next());
683     ///
684     /// // this requires a type hint
685     /// let it = (1..5).tuple_windows::<(_, _, _)>();
686     /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
687     ///
688     /// // you can also specify the complete type
689     /// use itertools::TupleWindows;
690     /// use std::ops::Range;
691     ///
692     /// let it: TupleWindows<Range<u32>, (u32, u32, u32)> = (1..5).tuple_windows();
693     /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
694     /// ```
tuple_windows<T>(self) -> TupleWindows<Self, T> where Self: Sized + Iterator<Item = T::Item>, T: traits::HomogeneousTuple, T::Item: Clone695     fn tuple_windows<T>(self) -> TupleWindows<Self, T>
696         where Self: Sized + Iterator<Item = T::Item>,
697               T: traits::HomogeneousTuple,
698               T::Item: Clone
699     {
700         tuple_impl::tuple_windows(self)
701     }
702 
703     /// Return an iterator over all windows, wrapping back to the first
704     /// elements when the window would otherwise exceed the length of the
705     /// iterator, producing tuples of a specific size (up to 4).
706     ///
707     /// `circular_tuple_windows` clones the iterator elements so that they can be
708     /// part of successive windows, this makes it most suited for iterators
709     /// of references and other values that are cheap to copy.
710     ///
711     /// ```
712     /// use itertools::Itertools;
713     /// let mut v = Vec::new();
714     /// for (a, b) in (1..5).circular_tuple_windows() {
715     ///     v.push((a, b));
716     /// }
717     /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4), (4, 1)]);
718     ///
719     /// let mut it = (1..5).circular_tuple_windows();
720     /// assert_eq!(Some((1, 2, 3)), it.next());
721     /// assert_eq!(Some((2, 3, 4)), it.next());
722     /// assert_eq!(Some((3, 4, 1)), it.next());
723     /// assert_eq!(Some((4, 1, 2)), it.next());
724     /// assert_eq!(None, it.next());
725     ///
726     /// // this requires a type hint
727     /// let it = (1..5).circular_tuple_windows::<(_, _, _)>();
728     /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)]);
729     /// ```
circular_tuple_windows<T>(self) -> CircularTupleWindows<Self, T> where Self: Sized + Clone + Iterator<Item = T::Item> + ExactSizeIterator, T: tuple_impl::TupleCollect + Clone, T::Item: Clone730     fn circular_tuple_windows<T>(self) -> CircularTupleWindows<Self, T>
731         where Self: Sized + Clone + Iterator<Item = T::Item> + ExactSizeIterator,
732               T: tuple_impl::TupleCollect + Clone,
733               T::Item: Clone
734     {
735         tuple_impl::circular_tuple_windows(self)
736     }
737     /// Return an iterator that groups the items in tuples of a specific size
738     /// (up to 4).
739     ///
740     /// See also the method [`.next_tuple()`](Itertools::next_tuple).
741     ///
742     /// ```
743     /// use itertools::Itertools;
744     /// let mut v = Vec::new();
745     /// for (a, b) in (1..5).tuples() {
746     ///     v.push((a, b));
747     /// }
748     /// assert_eq!(v, vec![(1, 2), (3, 4)]);
749     ///
750     /// let mut it = (1..7).tuples();
751     /// assert_eq!(Some((1, 2, 3)), it.next());
752     /// assert_eq!(Some((4, 5, 6)), it.next());
753     /// assert_eq!(None, it.next());
754     ///
755     /// // this requires a type hint
756     /// let it = (1..7).tuples::<(_, _, _)>();
757     /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
758     ///
759     /// // you can also specify the complete type
760     /// use itertools::Tuples;
761     /// use std::ops::Range;
762     ///
763     /// let it: Tuples<Range<u32>, (u32, u32, u32)> = (1..7).tuples();
764     /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
765     /// ```
766     ///
767     /// See also [`Tuples::into_buffer`].
tuples<T>(self) -> Tuples<Self, T> where Self: Sized + Iterator<Item = T::Item>, T: traits::HomogeneousTuple768     fn tuples<T>(self) -> Tuples<Self, T>
769         where Self: Sized + Iterator<Item = T::Item>,
770               T: traits::HomogeneousTuple
771     {
772         tuple_impl::tuples(self)
773     }
774 
775     /// Split into an iterator pair that both yield all elements from
776     /// the original iterator.
777     ///
778     /// **Note:** If the iterator is clonable, prefer using that instead
779     /// of using this method. It is likely to be more efficient.
780     ///
781     /// Iterator element type is `Self::Item`.
782     ///
783     /// ```
784     /// use itertools::Itertools;
785     /// let xs = vec![0, 1, 2, 3];
786     ///
787     /// let (mut t1, t2) = xs.into_iter().tee();
788     /// itertools::assert_equal(t1.next(), Some(0));
789     /// itertools::assert_equal(t2, 0..4);
790     /// itertools::assert_equal(t1, 1..4);
791     /// ```
792     #[cfg(feature = "use_alloc")]
tee(self) -> (Tee<Self>, Tee<Self>) where Self: Sized, Self::Item: Clone793     fn tee(self) -> (Tee<Self>, Tee<Self>)
794         where Self: Sized,
795               Self::Item: Clone
796     {
797         tee::new(self)
798     }
799 
800     /// Return an iterator adaptor that steps `n` elements in the base iterator
801     /// for each iteration.
802     ///
803     /// The iterator steps by yielding the next element from the base iterator,
804     /// then skipping forward `n - 1` elements.
805     ///
806     /// Iterator element type is `Self::Item`.
807     ///
808     /// **Panics** if the step is 0.
809     ///
810     /// ```
811     /// use itertools::Itertools;
812     ///
813     /// let it = (0..8).step(3);
814     /// itertools::assert_equal(it, vec![0, 3, 6]);
815     /// ```
816     #[deprecated(note="Use std .step_by() instead", since="0.8.0")]
817     #[allow(deprecated)]
step(self, n: usize) -> Step<Self> where Self: Sized818     fn step(self, n: usize) -> Step<Self>
819         where Self: Sized
820     {
821         adaptors::step(self, n)
822     }
823 
824     /// Convert each item of the iterator using the [`Into`] trait.
825     ///
826     /// ```rust
827     /// use itertools::Itertools;
828     ///
829     /// (1i32..42i32).map_into::<f64>().collect_vec();
830     /// ```
map_into<R>(self) -> MapInto<Self, R> where Self: Sized, Self::Item: Into<R>,831     fn map_into<R>(self) -> MapInto<Self, R>
832         where Self: Sized,
833               Self::Item: Into<R>,
834     {
835         adaptors::map_into(self)
836     }
837 
838     /// See [`.map_ok()`](Itertools::map_ok).
839     #[deprecated(note="Use .map_ok() instead", since="0.10.0")]
map_results<F, T, U, E>(self, f: F) -> MapOk<Self, F> where Self: Iterator<Item = Result<T, E>> + Sized, F: FnMut(T) -> U,840     fn map_results<F, T, U, E>(self, f: F) -> MapOk<Self, F>
841         where Self: Iterator<Item = Result<T, E>> + Sized,
842               F: FnMut(T) -> U,
843     {
844         self.map_ok(f)
845     }
846 
847     /// Return an iterator adaptor that applies the provided closure
848     /// to every `Result::Ok` value. `Result::Err` values are
849     /// unchanged.
850     ///
851     /// ```
852     /// use itertools::Itertools;
853     ///
854     /// let input = vec![Ok(41), Err(false), Ok(11)];
855     /// let it = input.into_iter().map_ok(|i| i + 1);
856     /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
857     /// ```
map_ok<F, T, U, E>(self, f: F) -> MapOk<Self, F> where Self: Iterator<Item = Result<T, E>> + Sized, F: FnMut(T) -> U,858     fn map_ok<F, T, U, E>(self, f: F) -> MapOk<Self, F>
859         where Self: Iterator<Item = Result<T, E>> + Sized,
860               F: FnMut(T) -> U,
861     {
862         adaptors::map_ok(self, f)
863     }
864 
865     /// Return an iterator adaptor that filters every `Result::Ok`
866     /// value with the provided closure. `Result::Err` values are
867     /// unchanged.
868     ///
869     /// ```
870     /// use itertools::Itertools;
871     ///
872     /// let input = vec![Ok(22), Err(false), Ok(11)];
873     /// let it = input.into_iter().filter_ok(|&i| i > 20);
874     /// itertools::assert_equal(it, vec![Ok(22), Err(false)]);
875     /// ```
filter_ok<F, T, E>(self, f: F) -> FilterOk<Self, F> where Self: Iterator<Item = Result<T, E>> + Sized, F: FnMut(&T) -> bool,876     fn filter_ok<F, T, E>(self, f: F) -> FilterOk<Self, F>
877         where Self: Iterator<Item = Result<T, E>> + Sized,
878               F: FnMut(&T) -> bool,
879     {
880         adaptors::filter_ok(self, f)
881     }
882 
883     /// Return an iterator adaptor that filters and transforms every
884     /// `Result::Ok` value with the provided closure. `Result::Err`
885     /// values are unchanged.
886     ///
887     /// ```
888     /// use itertools::Itertools;
889     ///
890     /// let input = vec![Ok(22), Err(false), Ok(11)];
891     /// let it = input.into_iter().filter_map_ok(|i| if i > 20 { Some(i * 2) } else { None });
892     /// itertools::assert_equal(it, vec![Ok(44), Err(false)]);
893     /// ```
filter_map_ok<F, T, U, E>(self, f: F) -> FilterMapOk<Self, F> where Self: Iterator<Item = Result<T, E>> + Sized, F: FnMut(T) -> Option<U>,894     fn filter_map_ok<F, T, U, E>(self, f: F) -> FilterMapOk<Self, F>
895         where Self: Iterator<Item = Result<T, E>> + Sized,
896               F: FnMut(T) -> Option<U>,
897     {
898         adaptors::filter_map_ok(self, f)
899     }
900 
901     /// Return an iterator adaptor that flattens every `Result::Ok` value into
902     /// a series of `Result::Ok` values. `Result::Err` values are unchanged.
903     ///
904     /// This is useful when you have some common error type for your crate and
905     /// need to propogate it upwards, but the `Result::Ok` case needs to be flattened.
906     ///
907     /// ```
908     /// use itertools::Itertools;
909     ///
910     /// let input = vec![Ok(0..2), Err(false), Ok(2..4)];
911     /// let it = input.iter().cloned().flatten_ok();
912     /// itertools::assert_equal(it.clone(), vec![Ok(0), Ok(1), Err(false), Ok(2), Ok(3)]);
913     ///
914     /// // This can also be used to propogate errors when collecting.
915     /// let output_result: Result<Vec<i32>, bool> = it.collect();
916     /// assert_eq!(output_result, Err(false));
917     /// ```
flatten_ok<T, E>(self) -> FlattenOk<Self, T, E> where Self: Iterator<Item = Result<T, E>> + Sized, T: IntoIterator918     fn flatten_ok<T, E>(self) -> FlattenOk<Self, T, E>
919         where Self: Iterator<Item = Result<T, E>> + Sized,
920               T: IntoIterator
921     {
922         flatten_ok::flatten_ok(self)
923     }
924 
925     /// Return an iterator adaptor that merges the two base iterators in
926     /// ascending order.  If both base iterators are sorted (ascending), the
927     /// result is sorted.
928     ///
929     /// Iterator element type is `Self::Item`.
930     ///
931     /// ```
932     /// use itertools::Itertools;
933     ///
934     /// let a = (0..11).step(3);
935     /// let b = (0..11).step(5);
936     /// let it = a.merge(b);
937     /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]);
938     /// ```
merge<J>(self, other: J) -> Merge<Self, J::IntoIter> where Self: Sized, Self::Item: PartialOrd, J: IntoIterator<Item = Self::Item>939     fn merge<J>(self, other: J) -> Merge<Self, J::IntoIter>
940         where Self: Sized,
941               Self::Item: PartialOrd,
942               J: IntoIterator<Item = Self::Item>
943     {
944         merge(self, other)
945     }
946 
947     /// Return an iterator adaptor that merges the two base iterators in order.
948     /// This is much like [`.merge()`](Itertools::merge) but allows for a custom ordering.
949     ///
950     /// This can be especially useful for sequences of tuples.
951     ///
952     /// Iterator element type is `Self::Item`.
953     ///
954     /// ```
955     /// use itertools::Itertools;
956     ///
957     /// let a = (0..).zip("bc".chars());
958     /// let b = (0..).zip("ad".chars());
959     /// let it = a.merge_by(b, |x, y| x.1 <= y.1);
960     /// itertools::assert_equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]);
961     /// ```
962 
merge_by<J, F>(self, other: J, is_first: F) -> MergeBy<Self, J::IntoIter, F> where Self: Sized, J: IntoIterator<Item = Self::Item>, F: FnMut(&Self::Item, &Self::Item) -> bool963     fn merge_by<J, F>(self, other: J, is_first: F) -> MergeBy<Self, J::IntoIter, F>
964         where Self: Sized,
965               J: IntoIterator<Item = Self::Item>,
966               F: FnMut(&Self::Item, &Self::Item) -> bool
967     {
968         adaptors::merge_by_new(self, other.into_iter(), is_first)
969     }
970 
971     /// Create an iterator that merges items from both this and the specified
972     /// iterator in ascending order.
973     ///
974     /// It chooses whether to pair elements based on the `Ordering` returned by the
975     /// specified compare function. At any point, inspecting the tip of the
976     /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
977     /// `J::Item` respectively, the resulting iterator will:
978     ///
979     /// - Emit `EitherOrBoth::Left(i)` when `i < j`,
980     ///   and remove `i` from its source iterator
981     /// - Emit `EitherOrBoth::Right(j)` when `i > j`,
982     ///   and remove `j` from its source iterator
983     /// - Emit `EitherOrBoth::Both(i, j)` when  `i == j`,
984     ///   and remove both `i` and `j` from their respective source iterators
985     ///
986     /// ```
987     /// use itertools::Itertools;
988     /// use itertools::EitherOrBoth::{Left, Right, Both};
989     ///
990     /// let multiples_of_2 = (0..10).step(2);
991     /// let multiples_of_3 = (0..10).step(3);
992     ///
993     /// itertools::assert_equal(
994     ///     multiples_of_2.merge_join_by(multiples_of_3, |i, j| i.cmp(j)),
995     ///     vec![Both(0, 0), Left(2), Right(3), Left(4), Both(6, 6), Left(8), Right(9)]
996     /// );
997     /// ```
998     #[inline]
merge_join_by<J, F>(self, other: J, cmp_fn: F) -> MergeJoinBy<Self, J::IntoIter, F> where J: IntoIterator, F: FnMut(&Self::Item, &J::Item) -> std::cmp::Ordering, Self: Sized999     fn merge_join_by<J, F>(self, other: J, cmp_fn: F) -> MergeJoinBy<Self, J::IntoIter, F>
1000         where J: IntoIterator,
1001               F: FnMut(&Self::Item, &J::Item) -> std::cmp::Ordering,
1002               Self: Sized
1003     {
1004         merge_join_by(self, other, cmp_fn)
1005     }
1006 
1007     /// Return an iterator adaptor that flattens an iterator of iterators by
1008     /// merging them in ascending order.
1009     ///
1010     /// If all base iterators are sorted (ascending), the result is sorted.
1011     ///
1012     /// Iterator element type is `Self::Item`.
1013     ///
1014     /// ```
1015     /// use itertools::Itertools;
1016     ///
1017     /// let a = (0..6).step(3);
1018     /// let b = (1..6).step(3);
1019     /// let c = (2..6).step(3);
1020     /// let it = vec![a, b, c].into_iter().kmerge();
1021     /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5]);
1022     /// ```
1023     #[cfg(feature = "use_alloc")]
kmerge(self) -> KMerge<<Self::Item as IntoIterator>::IntoIter> where Self: Sized, Self::Item: IntoIterator, <Self::Item as IntoIterator>::Item: PartialOrd,1024     fn kmerge(self) -> KMerge<<Self::Item as IntoIterator>::IntoIter>
1025         where Self: Sized,
1026               Self::Item: IntoIterator,
1027               <Self::Item as IntoIterator>::Item: PartialOrd,
1028     {
1029         kmerge(self)
1030     }
1031 
1032     /// Return an iterator adaptor that flattens an iterator of iterators by
1033     /// merging them according to the given closure.
1034     ///
1035     /// The closure `first` is called with two elements *a*, *b* and should
1036     /// return `true` if *a* is ordered before *b*.
1037     ///
1038     /// If all base iterators are sorted according to `first`, the result is
1039     /// sorted.
1040     ///
1041     /// Iterator element type is `Self::Item`.
1042     ///
1043     /// ```
1044     /// use itertools::Itertools;
1045     ///
1046     /// let a = vec![-1f64, 2., 3., -5., 6., -7.];
1047     /// let b = vec![0., 2., -4.];
1048     /// let mut it = vec![a, b].into_iter().kmerge_by(|a, b| a.abs() < b.abs());
1049     /// assert_eq!(it.next(), Some(0.));
1050     /// assert_eq!(it.last(), Some(-7.));
1051     /// ```
1052     #[cfg(feature = "use_alloc")]
kmerge_by<F>(self, first: F) -> KMergeBy<<Self::Item as IntoIterator>::IntoIter, F> where Self: Sized, Self::Item: IntoIterator, F: FnMut(&<Self::Item as IntoIterator>::Item, &<Self::Item as IntoIterator>::Item) -> bool1053     fn kmerge_by<F>(self, first: F)
1054         -> KMergeBy<<Self::Item as IntoIterator>::IntoIter, F>
1055         where Self: Sized,
1056               Self::Item: IntoIterator,
1057               F: FnMut(&<Self::Item as IntoIterator>::Item,
1058                        &<Self::Item as IntoIterator>::Item) -> bool
1059     {
1060         kmerge_by(self, first)
1061     }
1062 
1063     /// Return an iterator adaptor that iterates over the cartesian product of
1064     /// the element sets of two iterators `self` and `J`.
1065     ///
1066     /// Iterator element type is `(Self::Item, J::Item)`.
1067     ///
1068     /// ```
1069     /// use itertools::Itertools;
1070     ///
1071     /// let it = (0..2).cartesian_product("αβ".chars());
1072     /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]);
1073     /// ```
cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter> where Self: Sized, Self::Item: Clone, J: IntoIterator, J::IntoIter: Clone1074     fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter>
1075         where Self: Sized,
1076               Self::Item: Clone,
1077               J: IntoIterator,
1078               J::IntoIter: Clone
1079     {
1080         adaptors::cartesian_product(self, other.into_iter())
1081     }
1082 
1083     /// Return an iterator adaptor that iterates over the cartesian product of
1084     /// all subiterators returned by meta-iterator `self`.
1085     ///
1086     /// All provided iterators must yield the same `Item` type. To generate
1087     /// the product of iterators yielding multiple types, use the
1088     /// [`iproduct`] macro instead.
1089     ///
1090     ///
1091     /// The iterator element type is `Vec<T>`, where `T` is the iterator element
1092     /// of the subiterators.
1093     ///
1094     /// ```
1095     /// use itertools::Itertools;
1096     /// let mut multi_prod = (0..3).map(|i| (i * 2)..(i * 2 + 2))
1097     ///     .multi_cartesian_product();
1098     /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 4]));
1099     /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 5]));
1100     /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 4]));
1101     /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 5]));
1102     /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 4]));
1103     /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 5]));
1104     /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 4]));
1105     /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 5]));
1106     /// assert_eq!(multi_prod.next(), None);
1107     /// ```
1108     #[cfg(feature = "use_alloc")]
multi_cartesian_product(self) -> MultiProduct<<Self::Item as IntoIterator>::IntoIter> where Self: Iterator + Sized, Self::Item: IntoIterator, <Self::Item as IntoIterator>::IntoIter: Clone, <Self::Item as IntoIterator>::Item: Clone1109     fn multi_cartesian_product(self) -> MultiProduct<<Self::Item as IntoIterator>::IntoIter>
1110         where Self: Iterator + Sized,
1111               Self::Item: IntoIterator,
1112               <Self::Item as IntoIterator>::IntoIter: Clone,
1113               <Self::Item as IntoIterator>::Item: Clone
1114     {
1115         adaptors::multi_cartesian_product(self)
1116     }
1117 
1118     /// Return an iterator adaptor that uses the passed-in closure to
1119     /// optionally merge together consecutive elements.
1120     ///
1121     /// The closure `f` is passed two elements, `previous` and `current` and may
1122     /// return either (1) `Ok(combined)` to merge the two values or
1123     /// (2) `Err((previous', current'))` to indicate they can't be merged.
1124     /// In (2), the value `previous'` is emitted by the iterator.
1125     /// Either (1) `combined` or (2) `current'` becomes the previous value
1126     /// when coalesce continues with the next pair of elements to merge. The
1127     /// value that remains at the end is also emitted by the iterator.
1128     ///
1129     /// Iterator element type is `Self::Item`.
1130     ///
1131     /// This iterator is *fused*.
1132     ///
1133     /// ```
1134     /// use itertools::Itertools;
1135     ///
1136     /// // sum same-sign runs together
1137     /// let data = vec![-1., -2., -3., 3., 1., 0., -1.];
1138     /// itertools::assert_equal(data.into_iter().coalesce(|x, y|
1139     ///         if (x >= 0.) == (y >= 0.) {
1140     ///             Ok(x + y)
1141     ///         } else {
1142     ///             Err((x, y))
1143     ///         }),
1144     ///         vec![-6., 4., -1.]);
1145     /// ```
coalesce<F>(self, f: F) -> Coalesce<Self, F> where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Result<Self::Item, (Self::Item, Self::Item)>1146     fn coalesce<F>(self, f: F) -> Coalesce<Self, F>
1147         where Self: Sized,
1148               F: FnMut(Self::Item, Self::Item)
1149                        -> Result<Self::Item, (Self::Item, Self::Item)>
1150     {
1151         adaptors::coalesce(self, f)
1152     }
1153 
1154     /// Remove duplicates from sections of consecutive identical elements.
1155     /// If the iterator is sorted, all elements will be unique.
1156     ///
1157     /// Iterator element type is `Self::Item`.
1158     ///
1159     /// This iterator is *fused*.
1160     ///
1161     /// ```
1162     /// use itertools::Itertools;
1163     ///
1164     /// let data = vec![1., 1., 2., 3., 3., 2., 2.];
1165     /// itertools::assert_equal(data.into_iter().dedup(),
1166     ///                         vec![1., 2., 3., 2.]);
1167     /// ```
dedup(self) -> Dedup<Self> where Self: Sized, Self::Item: PartialEq,1168     fn dedup(self) -> Dedup<Self>
1169         where Self: Sized,
1170               Self::Item: PartialEq,
1171     {
1172         adaptors::dedup(self)
1173     }
1174 
1175     /// Remove duplicates from sections of consecutive identical elements,
1176     /// determining equality using a comparison function.
1177     /// If the iterator is sorted, all elements will be unique.
1178     ///
1179     /// Iterator element type is `Self::Item`.
1180     ///
1181     /// This iterator is *fused*.
1182     ///
1183     /// ```
1184     /// use itertools::Itertools;
1185     ///
1186     /// let data = vec![(0, 1.), (1, 1.), (0, 2.), (0, 3.), (1, 3.), (1, 2.), (2, 2.)];
1187     /// itertools::assert_equal(data.into_iter().dedup_by(|x, y| x.1 == y.1),
1188     ///                         vec![(0, 1.), (0, 2.), (0, 3.), (1, 2.)]);
1189     /// ```
dedup_by<Cmp>(self, cmp: Cmp) -> DedupBy<Self, Cmp> where Self: Sized, Cmp: FnMut(&Self::Item, &Self::Item)->bool,1190     fn dedup_by<Cmp>(self, cmp: Cmp) -> DedupBy<Self, Cmp>
1191         where Self: Sized,
1192               Cmp: FnMut(&Self::Item, &Self::Item)->bool,
1193     {
1194         adaptors::dedup_by(self, cmp)
1195     }
1196 
1197     /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1198     /// how many repeated elements were present.
1199     /// If the iterator is sorted, all elements will be unique.
1200     ///
1201     /// Iterator element type is `(usize, Self::Item)`.
1202     ///
1203     /// This iterator is *fused*.
1204     ///
1205     /// ```
1206     /// use itertools::Itertools;
1207     ///
1208     /// let data = vec!['a', 'a', 'b', 'c', 'c', 'b', 'b'];
1209     /// itertools::assert_equal(data.into_iter().dedup_with_count(),
1210     ///                         vec![(2, 'a'), (1, 'b'), (2, 'c'), (2, 'b')]);
1211     /// ```
dedup_with_count(self) -> DedupWithCount<Self> where Self: Sized,1212     fn dedup_with_count(self) -> DedupWithCount<Self>
1213     where
1214         Self: Sized,
1215     {
1216         adaptors::dedup_with_count(self)
1217     }
1218 
1219     /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1220     /// how many repeated elements were present.
1221     /// This will determine equality using a comparison function.
1222     /// If the iterator is sorted, all elements will be unique.
1223     ///
1224     /// Iterator element type is `(usize, Self::Item)`.
1225     ///
1226     /// This iterator is *fused*.
1227     ///
1228     /// ```
1229     /// use itertools::Itertools;
1230     ///
1231     /// let data = vec![(0, 'a'), (1, 'a'), (0, 'b'), (0, 'c'), (1, 'c'), (1, 'b'), (2, 'b')];
1232     /// itertools::assert_equal(data.into_iter().dedup_by_with_count(|x, y| x.1 == y.1),
1233     ///                         vec![(2, (0, 'a')), (1, (0, 'b')), (2, (0, 'c')), (2, (1, 'b'))]);
1234     /// ```
dedup_by_with_count<Cmp>(self, cmp: Cmp) -> DedupByWithCount<Self, Cmp> where Self: Sized, Cmp: FnMut(&Self::Item, &Self::Item) -> bool,1235     fn dedup_by_with_count<Cmp>(self, cmp: Cmp) -> DedupByWithCount<Self, Cmp>
1236     where
1237         Self: Sized,
1238         Cmp: FnMut(&Self::Item, &Self::Item) -> bool,
1239     {
1240         adaptors::dedup_by_with_count(self, cmp)
1241     }
1242 
1243     /// Return an iterator adaptor that produces elements that appear more than once during the
1244     /// iteration. Duplicates are detected using hash and equality.
1245     ///
1246     /// The iterator is stable, returning the duplicate items in the order in which they occur in
1247     /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1248     /// than twice, the second item is the item retained and the rest are discarded.
1249     ///
1250     /// ```
1251     /// use itertools::Itertools;
1252     ///
1253     /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1254     /// itertools::assert_equal(data.into_iter().duplicates(),
1255     ///                         vec![20, 10]);
1256     /// ```
1257     #[cfg(feature = "use_std")]
duplicates(self) -> Duplicates<Self> where Self: Sized, Self::Item: Eq + Hash1258     fn duplicates(self) -> Duplicates<Self>
1259         where Self: Sized,
1260               Self::Item: Eq + Hash
1261     {
1262         duplicates_impl::duplicates(self)
1263     }
1264 
1265     /// Return an iterator adaptor that produces elements that appear more than once during the
1266     /// iteration. Duplicates are detected using hash and equality.
1267     ///
1268     /// Duplicates are detected by comparing the key they map to with the keying function `f` by
1269     /// hash and equality. The keys are stored in a hash map in the iterator.
1270     ///
1271     /// The iterator is stable, returning the duplicate items in the order in which they occur in
1272     /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1273     /// than twice, the second item is the item retained and the rest are discarded.
1274     ///
1275     /// ```
1276     /// use itertools::Itertools;
1277     ///
1278     /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1279     /// itertools::assert_equal(data.into_iter().duplicates_by(|s| s.len()),
1280     ///                         vec!["aa", "c"]);
1281     /// ```
1282     #[cfg(feature = "use_std")]
duplicates_by<V, F>(self, f: F) -> DuplicatesBy<Self, V, F> where Self: Sized, V: Eq + Hash, F: FnMut(&Self::Item) -> V1283     fn duplicates_by<V, F>(self, f: F) -> DuplicatesBy<Self, V, F>
1284         where Self: Sized,
1285               V: Eq + Hash,
1286               F: FnMut(&Self::Item) -> V
1287     {
1288         duplicates_impl::duplicates_by(self, f)
1289     }
1290 
1291     /// Return an iterator adaptor that filters out elements that have
1292     /// already been produced once during the iteration. Duplicates
1293     /// are detected using hash and equality.
1294     ///
1295     /// Clones of visited elements are stored in a hash set in the
1296     /// iterator.
1297     ///
1298     /// The iterator is stable, returning the non-duplicate items in the order
1299     /// in which they occur in the adapted iterator. In a set of duplicate
1300     /// items, the first item encountered is the item retained.
1301     ///
1302     /// ```
1303     /// use itertools::Itertools;
1304     ///
1305     /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1306     /// itertools::assert_equal(data.into_iter().unique(),
1307     ///                         vec![10, 20, 30, 40, 50]);
1308     /// ```
1309     #[cfg(feature = "use_std")]
unique(self) -> Unique<Self> where Self: Sized, Self::Item: Clone + Eq + Hash1310     fn unique(self) -> Unique<Self>
1311         where Self: Sized,
1312               Self::Item: Clone + Eq + Hash
1313     {
1314         unique_impl::unique(self)
1315     }
1316 
1317     /// Return an iterator adaptor that filters out elements that have
1318     /// already been produced once during the iteration.
1319     ///
1320     /// Duplicates are detected by comparing the key they map to
1321     /// with the keying function `f` by hash and equality.
1322     /// The keys are stored in a hash set in the iterator.
1323     ///
1324     /// The iterator is stable, returning the non-duplicate items in the order
1325     /// in which they occur in the adapted iterator. In a set of duplicate
1326     /// items, the first item encountered is the item retained.
1327     ///
1328     /// ```
1329     /// use itertools::Itertools;
1330     ///
1331     /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1332     /// itertools::assert_equal(data.into_iter().unique_by(|s| s.len()),
1333     ///                         vec!["a", "bb", "ccc"]);
1334     /// ```
1335     #[cfg(feature = "use_std")]
unique_by<V, F>(self, f: F) -> UniqueBy<Self, V, F> where Self: Sized, V: Eq + Hash, F: FnMut(&Self::Item) -> V1336     fn unique_by<V, F>(self, f: F) -> UniqueBy<Self, V, F>
1337         where Self: Sized,
1338               V: Eq + Hash,
1339               F: FnMut(&Self::Item) -> V
1340     {
1341         unique_impl::unique_by(self, f)
1342     }
1343 
1344     /// Return an iterator adaptor that borrows from this iterator and
1345     /// takes items while the closure `accept` returns `true`.
1346     ///
1347     /// This adaptor can only be used on iterators that implement `PeekingNext`
1348     /// like `.peekable()`, `put_back` and a few other collection iterators.
1349     ///
1350     /// The last and rejected element (first `false`) is still available when
1351     /// `peeking_take_while` is done.
1352     ///
1353     ///
1354     /// See also [`.take_while_ref()`](Itertools::take_while_ref)
1355     /// which is a similar adaptor.
peeking_take_while<F>(&mut self, accept: F) -> PeekingTakeWhile<Self, F> where Self: Sized + PeekingNext, F: FnMut(&Self::Item) -> bool,1356     fn peeking_take_while<F>(&mut self, accept: F) -> PeekingTakeWhile<Self, F>
1357         where Self: Sized + PeekingNext,
1358               F: FnMut(&Self::Item) -> bool,
1359     {
1360         peeking_take_while::peeking_take_while(self, accept)
1361     }
1362 
1363     /// Return an iterator adaptor that borrows from a `Clone`-able iterator
1364     /// to only pick off elements while the predicate `accept` returns `true`.
1365     ///
1366     /// It uses the `Clone` trait to restore the original iterator so that the
1367     /// last and rejected element (first `false`) is still available when
1368     /// `take_while_ref` is done.
1369     ///
1370     /// ```
1371     /// use itertools::Itertools;
1372     ///
1373     /// let mut hexadecimals = "0123456789abcdef".chars();
1374     ///
1375     /// let decimals = hexadecimals.take_while_ref(|c| c.is_numeric())
1376     ///                            .collect::<String>();
1377     /// assert_eq!(decimals, "0123456789");
1378     /// assert_eq!(hexadecimals.next(), Some('a'));
1379     ///
1380     /// ```
take_while_ref<F>(&mut self, accept: F) -> TakeWhileRef<Self, F> where Self: Clone, F: FnMut(&Self::Item) -> bool1381     fn take_while_ref<F>(&mut self, accept: F) -> TakeWhileRef<Self, F>
1382         where Self: Clone,
1383               F: FnMut(&Self::Item) -> bool
1384     {
1385         adaptors::take_while_ref(self, accept)
1386     }
1387 
1388     /// Return an iterator adaptor that filters `Option<A>` iterator elements
1389     /// and produces `A`. Stops on the first `None` encountered.
1390     ///
1391     /// Iterator element type is `A`, the unwrapped element.
1392     ///
1393     /// ```
1394     /// use itertools::Itertools;
1395     ///
1396     /// // List all hexadecimal digits
1397     /// itertools::assert_equal(
1398     ///     (0..).map(|i| std::char::from_digit(i, 16)).while_some(),
1399     ///     "0123456789abcdef".chars());
1400     ///
1401     /// ```
while_some<A>(self) -> WhileSome<Self> where Self: Sized + Iterator<Item = Option<A>>1402     fn while_some<A>(self) -> WhileSome<Self>
1403         where Self: Sized + Iterator<Item = Option<A>>
1404     {
1405         adaptors::while_some(self)
1406     }
1407 
1408     /// Return an iterator adaptor that iterates over the combinations of the
1409     /// elements from an iterator.
1410     ///
1411     /// Iterator element can be any homogeneous tuple of type `Self::Item` with
1412     /// size up to 12.
1413     ///
1414     /// ```
1415     /// use itertools::Itertools;
1416     ///
1417     /// let mut v = Vec::new();
1418     /// for (a, b) in (1..5).tuple_combinations() {
1419     ///     v.push((a, b));
1420     /// }
1421     /// assert_eq!(v, vec![(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]);
1422     ///
1423     /// let mut it = (1..5).tuple_combinations();
1424     /// assert_eq!(Some((1, 2, 3)), it.next());
1425     /// assert_eq!(Some((1, 2, 4)), it.next());
1426     /// assert_eq!(Some((1, 3, 4)), it.next());
1427     /// assert_eq!(Some((2, 3, 4)), it.next());
1428     /// assert_eq!(None, it.next());
1429     ///
1430     /// // this requires a type hint
1431     /// let it = (1..5).tuple_combinations::<(_, _, _)>();
1432     /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1433     ///
1434     /// // you can also specify the complete type
1435     /// use itertools::TupleCombinations;
1436     /// use std::ops::Range;
1437     ///
1438     /// let it: TupleCombinations<Range<u32>, (u32, u32, u32)> = (1..5).tuple_combinations();
1439     /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1440     /// ```
tuple_combinations<T>(self) -> TupleCombinations<Self, T> where Self: Sized + Clone, Self::Item: Clone, T: adaptors::HasCombination<Self>,1441     fn tuple_combinations<T>(self) -> TupleCombinations<Self, T>
1442         where Self: Sized + Clone,
1443               Self::Item: Clone,
1444               T: adaptors::HasCombination<Self>,
1445     {
1446         adaptors::tuple_combinations(self)
1447     }
1448 
1449     /// Return an iterator adaptor that iterates over the `k`-length combinations of
1450     /// the elements from an iterator.
1451     ///
1452     /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1453     /// and clones the iterator elements.
1454     ///
1455     /// ```
1456     /// use itertools::Itertools;
1457     ///
1458     /// let it = (1..5).combinations(3);
1459     /// itertools::assert_equal(it, vec![
1460     ///     vec![1, 2, 3],
1461     ///     vec![1, 2, 4],
1462     ///     vec![1, 3, 4],
1463     ///     vec![2, 3, 4],
1464     /// ]);
1465     /// ```
1466     ///
1467     /// Note: Combinations does not take into account the equality of the iterated values.
1468     /// ```
1469     /// use itertools::Itertools;
1470     ///
1471     /// let it = vec![1, 2, 2].into_iter().combinations(2);
1472     /// itertools::assert_equal(it, vec![
1473     ///     vec![1, 2], // Note: these are the same
1474     ///     vec![1, 2], // Note: these are the same
1475     ///     vec![2, 2],
1476     /// ]);
1477     /// ```
1478     #[cfg(feature = "use_alloc")]
combinations(self, k: usize) -> Combinations<Self> where Self: Sized, Self::Item: Clone1479     fn combinations(self, k: usize) -> Combinations<Self>
1480         where Self: Sized,
1481               Self::Item: Clone
1482     {
1483         combinations::combinations(self, k)
1484     }
1485 
1486     /// Return an iterator that iterates over the `k`-length combinations of
1487     /// the elements from an iterator, with replacement.
1488     ///
1489     /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1490     /// and clones the iterator elements.
1491     ///
1492     /// ```
1493     /// use itertools::Itertools;
1494     ///
1495     /// let it = (1..4).combinations_with_replacement(2);
1496     /// itertools::assert_equal(it, vec![
1497     ///     vec![1, 1],
1498     ///     vec![1, 2],
1499     ///     vec![1, 3],
1500     ///     vec![2, 2],
1501     ///     vec![2, 3],
1502     ///     vec![3, 3],
1503     /// ]);
1504     /// ```
1505     #[cfg(feature = "use_alloc")]
combinations_with_replacement(self, k: usize) -> CombinationsWithReplacement<Self> where Self: Sized, Self::Item: Clone,1506     fn combinations_with_replacement(self, k: usize) -> CombinationsWithReplacement<Self>
1507     where
1508         Self: Sized,
1509         Self::Item: Clone,
1510     {
1511         combinations_with_replacement::combinations_with_replacement(self, k)
1512     }
1513 
1514     /// Return an iterator adaptor that iterates over all k-permutations of the
1515     /// elements from an iterator.
1516     ///
1517     /// Iterator element type is `Vec<Self::Item>` with length `k`. The iterator
1518     /// produces a new Vec per iteration, and clones the iterator elements.
1519     ///
1520     /// If `k` is greater than the length of the input iterator, the resultant
1521     /// iterator adaptor will be empty.
1522     ///
1523     /// ```
1524     /// use itertools::Itertools;
1525     ///
1526     /// let perms = (5..8).permutations(2);
1527     /// itertools::assert_equal(perms, vec![
1528     ///     vec![5, 6],
1529     ///     vec![5, 7],
1530     ///     vec![6, 5],
1531     ///     vec![6, 7],
1532     ///     vec![7, 5],
1533     ///     vec![7, 6],
1534     /// ]);
1535     /// ```
1536     ///
1537     /// Note: Permutations does not take into account the equality of the iterated values.
1538     ///
1539     /// ```
1540     /// use itertools::Itertools;
1541     ///
1542     /// let it = vec![2, 2].into_iter().permutations(2);
1543     /// itertools::assert_equal(it, vec![
1544     ///     vec![2, 2], // Note: these are the same
1545     ///     vec![2, 2], // Note: these are the same
1546     /// ]);
1547     /// ```
1548     ///
1549     /// Note: The source iterator is collected lazily, and will not be
1550     /// re-iterated if the permutations adaptor is completed and re-iterated.
1551     #[cfg(feature = "use_alloc")]
permutations(self, k: usize) -> Permutations<Self> where Self: Sized, Self::Item: Clone1552     fn permutations(self, k: usize) -> Permutations<Self>
1553         where Self: Sized,
1554               Self::Item: Clone
1555     {
1556         permutations::permutations(self, k)
1557     }
1558 
1559     /// Return an iterator that iterates through the powerset of the elements from an
1560     /// iterator.
1561     ///
1562     /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new `Vec`
1563     /// per iteration, and clones the iterator elements.
1564     ///
1565     /// The powerset of a set contains all subsets including the empty set and the full
1566     /// input set. A powerset has length _2^n_ where _n_ is the length of the input
1567     /// set.
1568     ///
1569     /// Each `Vec` produced by this iterator represents a subset of the elements
1570     /// produced by the source iterator.
1571     ///
1572     /// ```
1573     /// use itertools::Itertools;
1574     ///
1575     /// let sets = (1..4).powerset().collect::<Vec<_>>();
1576     /// itertools::assert_equal(sets, vec![
1577     ///     vec![],
1578     ///     vec![1],
1579     ///     vec![2],
1580     ///     vec![3],
1581     ///     vec![1, 2],
1582     ///     vec![1, 3],
1583     ///     vec![2, 3],
1584     ///     vec![1, 2, 3],
1585     /// ]);
1586     /// ```
1587     #[cfg(feature = "use_alloc")]
powerset(self) -> Powerset<Self> where Self: Sized, Self::Item: Clone,1588     fn powerset(self) -> Powerset<Self>
1589         where Self: Sized,
1590               Self::Item: Clone,
1591     {
1592         powerset::powerset(self)
1593     }
1594 
1595     /// Return an iterator adaptor that pads the sequence to a minimum length of
1596     /// `min` by filling missing elements using a closure `f`.
1597     ///
1598     /// Iterator element type is `Self::Item`.
1599     ///
1600     /// ```
1601     /// use itertools::Itertools;
1602     ///
1603     /// let it = (0..5).pad_using(10, |i| 2*i);
1604     /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 10, 12, 14, 16, 18]);
1605     ///
1606     /// let it = (0..10).pad_using(5, |i| 2*i);
1607     /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1608     ///
1609     /// let it = (0..5).pad_using(10, |i| 2*i).rev();
1610     /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]);
1611     /// ```
pad_using<F>(self, min: usize, f: F) -> PadUsing<Self, F> where Self: Sized, F: FnMut(usize) -> Self::Item1612     fn pad_using<F>(self, min: usize, f: F) -> PadUsing<Self, F>
1613         where Self: Sized,
1614               F: FnMut(usize) -> Self::Item
1615     {
1616         pad_tail::pad_using(self, min, f)
1617     }
1618 
1619     /// Return an iterator adaptor that wraps each element in a `Position` to
1620     /// ease special-case handling of the first or last elements.
1621     ///
1622     /// Iterator element type is
1623     /// [`Position<Self::Item>`](Position)
1624     ///
1625     /// ```
1626     /// use itertools::{Itertools, Position};
1627     ///
1628     /// let it = (0..4).with_position();
1629     /// itertools::assert_equal(it,
1630     ///                         vec![Position::First(0),
1631     ///                              Position::Middle(1),
1632     ///                              Position::Middle(2),
1633     ///                              Position::Last(3)]);
1634     ///
1635     /// let it = (0..1).with_position();
1636     /// itertools::assert_equal(it, vec![Position::Only(0)]);
1637     /// ```
with_position(self) -> WithPosition<Self> where Self: Sized,1638     fn with_position(self) -> WithPosition<Self>
1639         where Self: Sized,
1640     {
1641         with_position::with_position(self)
1642     }
1643 
1644     /// Return an iterator adaptor that yields the indices of all elements
1645     /// satisfying a predicate, counted from the start of the iterator.
1646     ///
1647     /// Equivalent to `iter.enumerate().filter(|(_, v)| predicate(v)).map(|(i, _)| i)`.
1648     ///
1649     /// ```
1650     /// use itertools::Itertools;
1651     ///
1652     /// let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
1653     /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 0), vec![1, 4, 5]);
1654     ///
1655     /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]);
1656     /// ```
positions<P>(self, predicate: P) -> Positions<Self, P> where Self: Sized, P: FnMut(Self::Item) -> bool,1657     fn positions<P>(self, predicate: P) -> Positions<Self, P>
1658         where Self: Sized,
1659               P: FnMut(Self::Item) -> bool,
1660     {
1661         adaptors::positions(self, predicate)
1662     }
1663 
1664     /// Return an iterator adaptor that applies a mutating function
1665     /// to each element before yielding it.
1666     ///
1667     /// ```
1668     /// use itertools::Itertools;
1669     ///
1670     /// let input = vec![vec![1], vec![3, 2, 1]];
1671     /// let it = input.into_iter().update(|mut v| v.push(0));
1672     /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]);
1673     /// ```
update<F>(self, updater: F) -> Update<Self, F> where Self: Sized, F: FnMut(&mut Self::Item),1674     fn update<F>(self, updater: F) -> Update<Self, F>
1675         where Self: Sized,
1676               F: FnMut(&mut Self::Item),
1677     {
1678         adaptors::update(self, updater)
1679     }
1680 
1681     // non-adaptor methods
1682     /// Advances the iterator and returns the next items grouped in a tuple of
1683     /// a specific size (up to 12).
1684     ///
1685     /// If there are enough elements to be grouped in a tuple, then the tuple is
1686     /// returned inside `Some`, otherwise `None` is returned.
1687     ///
1688     /// ```
1689     /// use itertools::Itertools;
1690     ///
1691     /// let mut iter = 1..5;
1692     ///
1693     /// assert_eq!(Some((1, 2)), iter.next_tuple());
1694     /// ```
next_tuple<T>(&mut self) -> Option<T> where Self: Sized + Iterator<Item = T::Item>, T: traits::HomogeneousTuple1695     fn next_tuple<T>(&mut self) -> Option<T>
1696         where Self: Sized + Iterator<Item = T::Item>,
1697               T: traits::HomogeneousTuple
1698     {
1699         T::collect_from_iter_no_buf(self)
1700     }
1701 
1702     /// Collects all items from the iterator into a tuple of a specific size
1703     /// (up to 12).
1704     ///
1705     /// If the number of elements inside the iterator is **exactly** equal to
1706     /// the tuple size, then the tuple is returned inside `Some`, otherwise
1707     /// `None` is returned.
1708     ///
1709     /// ```
1710     /// use itertools::Itertools;
1711     ///
1712     /// let iter = 1..3;
1713     ///
1714     /// if let Some((x, y)) = iter.collect_tuple() {
1715     ///     assert_eq!((x, y), (1, 2))
1716     /// } else {
1717     ///     panic!("Expected two elements")
1718     /// }
1719     /// ```
collect_tuple<T>(mut self) -> Option<T> where Self: Sized + Iterator<Item = T::Item>, T: traits::HomogeneousTuple1720     fn collect_tuple<T>(mut self) -> Option<T>
1721         where Self: Sized + Iterator<Item = T::Item>,
1722               T: traits::HomogeneousTuple
1723     {
1724         match self.next_tuple() {
1725             elt @ Some(_) => match self.next() {
1726                 Some(_) => None,
1727                 None => elt,
1728             },
1729             _ => None
1730         }
1731     }
1732 
1733 
1734     /// Find the position and value of the first element satisfying a predicate.
1735     ///
1736     /// The iterator is not advanced past the first element found.
1737     ///
1738     /// ```
1739     /// use itertools::Itertools;
1740     ///
1741     /// let text = "Hα";
1742     /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α')));
1743     /// ```
find_position<P>(&mut self, mut pred: P) -> Option<(usize, Self::Item)> where P: FnMut(&Self::Item) -> bool1744     fn find_position<P>(&mut self, mut pred: P) -> Option<(usize, Self::Item)>
1745         where P: FnMut(&Self::Item) -> bool
1746     {
1747         let mut index = 0usize;
1748         for elt in self {
1749             if pred(&elt) {
1750                 return Some((index, elt));
1751             }
1752             index += 1;
1753         }
1754         None
1755     }
1756     /// Find the value of the first element satisfying a predicate or return the last element, if any.
1757     ///
1758     /// The iterator is not advanced past the first element found.
1759     ///
1760     /// ```
1761     /// use itertools::Itertools;
1762     ///
1763     /// let numbers = [1, 2, 3, 4];
1764     /// assert_eq!(numbers.iter().find_or_last(|&&x| x > 5), Some(&4));
1765     /// assert_eq!(numbers.iter().find_or_last(|&&x| x > 2), Some(&3));
1766     /// assert_eq!(std::iter::empty::<i32>().find_or_last(|&x| x > 5), None);
1767     /// ```
find_or_last<P>(mut self, mut predicate: P) -> Option<Self::Item> where Self: Sized, P: FnMut(&Self::Item) -> bool,1768     fn find_or_last<P>(mut self, mut predicate: P) -> Option<Self::Item>
1769         where Self: Sized,
1770               P: FnMut(&Self::Item) -> bool,
1771     {
1772         let mut prev = None;
1773         self.find_map(|x| if predicate(&x) { Some(x) } else { prev = Some(x); None })
1774             .or(prev)
1775     }
1776     /// Find the value of the first element satisfying a predicate or return the first element, if any.
1777     ///
1778     /// The iterator is not advanced past the first element found.
1779     ///
1780     /// ```
1781     /// use itertools::Itertools;
1782     ///
1783     /// let numbers = [1, 2, 3, 4];
1784     /// assert_eq!(numbers.iter().find_or_first(|&&x| x > 5), Some(&1));
1785     /// assert_eq!(numbers.iter().find_or_first(|&&x| x > 2), Some(&3));
1786     /// assert_eq!(std::iter::empty::<i32>().find_or_first(|&x| x > 5), None);
1787     /// ```
find_or_first<P>(mut self, mut predicate: P) -> Option<Self::Item> where Self: Sized, P: FnMut(&Self::Item) -> bool,1788     fn find_or_first<P>(mut self, mut predicate: P) -> Option<Self::Item>
1789         where Self: Sized,
1790               P: FnMut(&Self::Item) -> bool,
1791     {
1792         let first = self.next()?;
1793         Some(if predicate(&first) {
1794             first
1795         } else {
1796             self.find(|x| predicate(&x)).unwrap_or(first)
1797         })
1798     }
1799     /// Returns `true` if the given item is present in this iterator.
1800     ///
1801     /// This method is short-circuiting. If the given item is present in this
1802     /// iterator, this method will consume the iterator up-to-and-including
1803     /// the item. If the given item is not present in this iterator, the
1804     /// iterator will be exhausted.
1805     ///
1806     /// ```
1807     /// use itertools::Itertools;
1808     ///
1809     /// #[derive(PartialEq, Debug)]
1810     /// enum Enum { A, B, C, D, E, }
1811     ///
1812     /// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter();
1813     ///
1814     /// // search `iter` for `B`
1815     /// assert_eq!(iter.contains(&Enum::B), true);
1816     /// // `B` was found, so the iterator now rests at the item after `B` (i.e, `C`).
1817     /// assert_eq!(iter.next(), Some(Enum::C));
1818     ///
1819     /// // search `iter` for `E`
1820     /// assert_eq!(iter.contains(&Enum::E), false);
1821     /// // `E` wasn't found, so `iter` is now exhausted
1822     /// assert_eq!(iter.next(), None);
1823     /// ```
contains<Q>(&mut self, query: &Q) -> bool where Self: Sized, Self::Item: Borrow<Q>, Q: PartialEq,1824     fn contains<Q>(&mut self, query: &Q) -> bool
1825     where
1826         Self: Sized,
1827         Self::Item: Borrow<Q>,
1828         Q: PartialEq,
1829     {
1830         self.any(|x| x.borrow() == query)
1831     }
1832 
1833     /// Check whether all elements compare equal.
1834     ///
1835     /// Empty iterators are considered to have equal elements:
1836     ///
1837     /// ```
1838     /// use itertools::Itertools;
1839     ///
1840     /// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
1841     /// assert!(!data.iter().all_equal());
1842     /// assert!(data[0..3].iter().all_equal());
1843     /// assert!(data[3..5].iter().all_equal());
1844     /// assert!(data[5..8].iter().all_equal());
1845     ///
1846     /// let data : Option<usize> = None;
1847     /// assert!(data.into_iter().all_equal());
1848     /// ```
all_equal(&mut self) -> bool where Self: Sized, Self::Item: PartialEq,1849     fn all_equal(&mut self) -> bool
1850         where Self: Sized,
1851               Self::Item: PartialEq,
1852     {
1853         match self.next() {
1854             None => true,
1855             Some(a) => self.all(|x| a == x),
1856         }
1857     }
1858 
1859     /// Check whether all elements are unique (non equal).
1860     ///
1861     /// Empty iterators are considered to have unique elements:
1862     ///
1863     /// ```
1864     /// use itertools::Itertools;
1865     ///
1866     /// let data = vec![1, 2, 3, 4, 1, 5];
1867     /// assert!(!data.iter().all_unique());
1868     /// assert!(data[0..4].iter().all_unique());
1869     /// assert!(data[1..6].iter().all_unique());
1870     ///
1871     /// let data : Option<usize> = None;
1872     /// assert!(data.into_iter().all_unique());
1873     /// ```
1874     #[cfg(feature = "use_std")]
all_unique(&mut self) -> bool where Self: Sized, Self::Item: Eq + Hash1875     fn all_unique(&mut self) -> bool
1876         where Self: Sized,
1877               Self::Item: Eq + Hash
1878     {
1879         let mut used = HashSet::new();
1880         self.all(move |elt| used.insert(elt))
1881     }
1882 
1883     /// Consume the first `n` elements from the iterator eagerly,
1884     /// and return the same iterator again.
1885     ///
1886     /// It works similarly to *.skip(* `n` *)* except it is eager and
1887     /// preserves the iterator type.
1888     ///
1889     /// ```
1890     /// use itertools::Itertools;
1891     ///
1892     /// let mut iter = "αβγ".chars().dropping(2);
1893     /// itertools::assert_equal(iter, "γ".chars());
1894     /// ```
1895     ///
1896     /// *Fusing notes: if the iterator is exhausted by dropping,
1897     /// the result of calling `.next()` again depends on the iterator implementation.*
dropping(mut self, n: usize) -> Self where Self: Sized1898     fn dropping(mut self, n: usize) -> Self
1899         where Self: Sized
1900     {
1901         if n > 0 {
1902             self.nth(n - 1);
1903         }
1904         self
1905     }
1906 
1907     /// Consume the last `n` elements from the iterator eagerly,
1908     /// and return the same iterator again.
1909     ///
1910     /// This is only possible on double ended iterators. `n` may be
1911     /// larger than the number of elements.
1912     ///
1913     /// Note: This method is eager, dropping the back elements immediately and
1914     /// preserves the iterator type.
1915     ///
1916     /// ```
1917     /// use itertools::Itertools;
1918     ///
1919     /// let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
1920     /// itertools::assert_equal(init, vec![0, 3, 6]);
1921     /// ```
dropping_back(mut self, n: usize) -> Self where Self: Sized, Self: DoubleEndedIterator1922     fn dropping_back(mut self, n: usize) -> Self
1923         where Self: Sized,
1924               Self: DoubleEndedIterator
1925     {
1926         if n > 0 {
1927             (&mut self).rev().nth(n - 1);
1928         }
1929         self
1930     }
1931 
1932     /// Run the closure `f` eagerly on each element of the iterator.
1933     ///
1934     /// Consumes the iterator until its end.
1935     ///
1936     /// ```
1937     /// use std::sync::mpsc::channel;
1938     /// use itertools::Itertools;
1939     ///
1940     /// let (tx, rx) = channel();
1941     ///
1942     /// // use .foreach() to apply a function to each value -- sending it
1943     /// (0..5).map(|x| x * 2 + 1).foreach(|x| { tx.send(x).unwrap(); } );
1944     ///
1945     /// drop(tx);
1946     ///
1947     /// itertools::assert_equal(rx.iter(), vec![1, 3, 5, 7, 9]);
1948     /// ```
1949     #[deprecated(note="Use .for_each() instead", since="0.8.0")]
foreach<F>(self, f: F) where F: FnMut(Self::Item), Self: Sized,1950     fn foreach<F>(self, f: F)
1951         where F: FnMut(Self::Item),
1952               Self: Sized,
1953     {
1954         self.for_each(f)
1955     }
1956 
1957     /// Combine all an iterator's elements into one element by using [`Extend`].
1958     ///
1959     /// This combinator will extend the first item with each of the rest of the
1960     /// items of the iterator. If the iterator is empty, the default value of
1961     /// `I::Item` is returned.
1962     ///
1963     /// ```rust
1964     /// use itertools::Itertools;
1965     ///
1966     /// let input = vec![vec![1], vec![2, 3], vec![4, 5, 6]];
1967     /// assert_eq!(input.into_iter().concat(),
1968     ///            vec![1, 2, 3, 4, 5, 6]);
1969     /// ```
concat(self) -> Self::Item where Self: Sized, Self::Item: Extend<<<Self as Iterator>::Item as IntoIterator>::Item> + IntoIterator + Default1970     fn concat(self) -> Self::Item
1971         where Self: Sized,
1972               Self::Item: Extend<<<Self as Iterator>::Item as IntoIterator>::Item> + IntoIterator + Default
1973     {
1974         concat(self)
1975     }
1976 
1977     /// `.collect_vec()` is simply a type specialization of [`Iterator::collect`],
1978     /// for convenience.
1979     #[cfg(feature = "use_alloc")]
collect_vec(self) -> Vec<Self::Item> where Self: Sized1980     fn collect_vec(self) -> Vec<Self::Item>
1981         where Self: Sized
1982     {
1983         self.collect()
1984     }
1985 
1986     /// `.try_collect()` is more convenient way of writing
1987     /// `.collect::<Result<_, _>>()`
1988     ///
1989     /// # Example
1990     ///
1991     /// ```
1992     /// use std::{fs, io};
1993     /// use itertools::Itertools;
1994     ///
1995     /// fn process_dir_entries(entries: &[fs::DirEntry]) {
1996     ///     // ...
1997     /// }
1998     ///
1999     /// fn do_stuff() -> std::io::Result<()> {
2000     ///     let entries: Vec<_> = fs::read_dir(".")?.try_collect()?;
2001     ///     process_dir_entries(&entries);
2002     ///
2003     ///     Ok(())
2004     /// }
2005     /// ```
2006     #[cfg(feature = "use_alloc")]
try_collect<T, U, E>(self) -> Result<U, E> where Self: Sized + Iterator<Item = Result<T, E>>, Result<U, E>: FromIterator<Result<T, E>>,2007     fn try_collect<T, U, E>(self) -> Result<U, E>
2008     where
2009         Self: Sized + Iterator<Item = Result<T, E>>,
2010         Result<U, E>: FromIterator<Result<T, E>>,
2011     {
2012         self.collect()
2013     }
2014 
2015     /// Assign to each reference in `self` from the `from` iterator,
2016     /// stopping at the shortest of the two iterators.
2017     ///
2018     /// The `from` iterator is queried for its next element before the `self`
2019     /// iterator, and if either is exhausted the method is done.
2020     ///
2021     /// Return the number of elements written.
2022     ///
2023     /// ```
2024     /// use itertools::Itertools;
2025     ///
2026     /// let mut xs = [0; 4];
2027     /// xs.iter_mut().set_from(1..);
2028     /// assert_eq!(xs, [1, 2, 3, 4]);
2029     /// ```
2030     #[inline]
set_from<'a, A: 'a, J>(&mut self, from: J) -> usize where Self: Iterator<Item = &'a mut A>, J: IntoIterator<Item = A>2031     fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize
2032         where Self: Iterator<Item = &'a mut A>,
2033               J: IntoIterator<Item = A>
2034     {
2035         let mut count = 0;
2036         for elt in from {
2037             match self.next() {
2038                 None => break,
2039                 Some(ptr) => *ptr = elt,
2040             }
2041             count += 1;
2042         }
2043         count
2044     }
2045 
2046     /// Combine all iterator elements into one String, separated by `sep`.
2047     ///
2048     /// Use the `Display` implementation of each element.
2049     ///
2050     /// ```
2051     /// use itertools::Itertools;
2052     ///
2053     /// assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
2054     /// assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");
2055     /// ```
2056     #[cfg(feature = "use_alloc")]
join(&mut self, sep: &str) -> String where Self::Item: std::fmt::Display2057     fn join(&mut self, sep: &str) -> String
2058         where Self::Item: std::fmt::Display
2059     {
2060         match self.next() {
2061             None => String::new(),
2062             Some(first_elt) => {
2063                 // estimate lower bound of capacity needed
2064                 let (lower, _) = self.size_hint();
2065                 let mut result = String::with_capacity(sep.len() * lower);
2066                 write!(&mut result, "{}", first_elt).unwrap();
2067                 self.for_each(|elt| {
2068                     result.push_str(sep);
2069                     write!(&mut result, "{}", elt).unwrap();
2070                 });
2071                 result
2072             }
2073         }
2074     }
2075 
2076     /// Format all iterator elements, separated by `sep`.
2077     ///
2078     /// All elements are formatted (any formatting trait)
2079     /// with `sep` inserted between each element.
2080     ///
2081     /// **Panics** if the formatter helper is formatted more than once.
2082     ///
2083     /// ```
2084     /// use itertools::Itertools;
2085     ///
2086     /// let data = [1.1, 2.71828, -3.];
2087     /// assert_eq!(
2088     ///     format!("{:.2}", data.iter().format(", ")),
2089     ///            "1.10, 2.72, -3.00");
2090     /// ```
format(self, sep: &str) -> Format<Self> where Self: Sized,2091     fn format(self, sep: &str) -> Format<Self>
2092         where Self: Sized,
2093     {
2094         format::new_format_default(self, sep)
2095     }
2096 
2097     /// Format all iterator elements, separated by `sep`.
2098     ///
2099     /// This is a customizable version of [`.format()`](Itertools::format).
2100     ///
2101     /// The supplied closure `format` is called once per iterator element,
2102     /// with two arguments: the element and a callback that takes a
2103     /// `&Display` value, i.e. any reference to type that implements `Display`.
2104     ///
2105     /// Using `&format_args!(...)` is the most versatile way to apply custom
2106     /// element formatting. The callback can be called multiple times if needed.
2107     ///
2108     /// **Panics** if the formatter helper is formatted more than once.
2109     ///
2110     /// ```
2111     /// use itertools::Itertools;
2112     ///
2113     /// let data = [1.1, 2.71828, -3.];
2114     /// let data_formatter = data.iter().format_with(", ", |elt, f| f(&format_args!("{:.2}", elt)));
2115     /// assert_eq!(format!("{}", data_formatter),
2116     ///            "1.10, 2.72, -3.00");
2117     ///
2118     /// // .format_with() is recursively composable
2119     /// let matrix = [[1., 2., 3.],
2120     ///               [4., 5., 6.]];
2121     /// let matrix_formatter = matrix.iter().format_with("\n", |row, f| {
2122     ///                                 f(&row.iter().format_with(", ", |elt, g| g(&elt)))
2123     ///                              });
2124     /// assert_eq!(format!("{}", matrix_formatter),
2125     ///            "1, 2, 3\n4, 5, 6");
2126     ///
2127     ///
2128     /// ```
format_with<F>(self, sep: &str, format: F) -> FormatWith<Self, F> where Self: Sized, F: FnMut(Self::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result,2129     fn format_with<F>(self, sep: &str, format: F) -> FormatWith<Self, F>
2130         where Self: Sized,
2131               F: FnMut(Self::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result,
2132     {
2133         format::new_format(self, sep, format)
2134     }
2135 
2136     /// See [`.fold_ok()`](Itertools::fold_ok).
2137     #[deprecated(note="Use .fold_ok() instead", since="0.10.0")]
fold_results<A, E, B, F>(&mut self, start: B, f: F) -> Result<B, E> where Self: Iterator<Item = Result<A, E>>, F: FnMut(B, A) -> B2138     fn fold_results<A, E, B, F>(&mut self, start: B, f: F) -> Result<B, E>
2139         where Self: Iterator<Item = Result<A, E>>,
2140               F: FnMut(B, A) -> B
2141     {
2142         self.fold_ok(start, f)
2143     }
2144 
2145     /// Fold `Result` values from an iterator.
2146     ///
2147     /// Only `Ok` values are folded. If no error is encountered, the folded
2148     /// value is returned inside `Ok`. Otherwise, the operation terminates
2149     /// and returns the first `Err` value it encounters. No iterator elements are
2150     /// consumed after the first error.
2151     ///
2152     /// The first accumulator value is the `start` parameter.
2153     /// Each iteration passes the accumulator value and the next value inside `Ok`
2154     /// to the fold function `f` and its return value becomes the new accumulator value.
2155     ///
2156     /// For example the sequence *Ok(1), Ok(2), Ok(3)* will result in a
2157     /// computation like this:
2158     ///
2159     /// ```ignore
2160     /// let mut accum = start;
2161     /// accum = f(accum, 1);
2162     /// accum = f(accum, 2);
2163     /// accum = f(accum, 3);
2164     /// ```
2165     ///
2166     /// With a `start` value of 0 and an addition as folding function,
2167     /// this effectively results in *((0 + 1) + 2) + 3*
2168     ///
2169     /// ```
2170     /// use std::ops::Add;
2171     /// use itertools::Itertools;
2172     ///
2173     /// let values = [1, 2, -2, -1, 2, 1];
2174     /// assert_eq!(
2175     ///     values.iter()
2176     ///           .map(Ok::<_, ()>)
2177     ///           .fold_ok(0, Add::add),
2178     ///     Ok(3)
2179     /// );
2180     /// assert!(
2181     ///     values.iter()
2182     ///           .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
2183     ///           .fold_ok(0, Add::add)
2184     ///           .is_err()
2185     /// );
2186     /// ```
fold_ok<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E> where Self: Iterator<Item = Result<A, E>>, F: FnMut(B, A) -> B2187     fn fold_ok<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
2188         where Self: Iterator<Item = Result<A, E>>,
2189               F: FnMut(B, A) -> B
2190     {
2191         for elt in self {
2192             match elt {
2193                 Ok(v) => start = f(start, v),
2194                 Err(u) => return Err(u),
2195             }
2196         }
2197         Ok(start)
2198     }
2199 
2200     /// Fold `Option` values from an iterator.
2201     ///
2202     /// Only `Some` values are folded. If no `None` is encountered, the folded
2203     /// value is returned inside `Some`. Otherwise, the operation terminates
2204     /// and returns `None`. No iterator elements are consumed after the `None`.
2205     ///
2206     /// This is the `Option` equivalent to [`fold_ok`](Itertools::fold_ok).
2207     ///
2208     /// ```
2209     /// use std::ops::Add;
2210     /// use itertools::Itertools;
2211     ///
2212     /// let mut values = vec![Some(1), Some(2), Some(-2)].into_iter();
2213     /// assert_eq!(values.fold_options(5, Add::add), Some(5 + 1 + 2 - 2));
2214     ///
2215     /// let mut more_values = vec![Some(2), None, Some(0)].into_iter();
2216     /// assert!(more_values.fold_options(0, Add::add).is_none());
2217     /// assert_eq!(more_values.next().unwrap(), Some(0));
2218     /// ```
fold_options<A, B, F>(&mut self, mut start: B, mut f: F) -> Option<B> where Self: Iterator<Item = Option<A>>, F: FnMut(B, A) -> B2219     fn fold_options<A, B, F>(&mut self, mut start: B, mut f: F) -> Option<B>
2220         where Self: Iterator<Item = Option<A>>,
2221               F: FnMut(B, A) -> B
2222     {
2223         for elt in self {
2224             match elt {
2225                 Some(v) => start = f(start, v),
2226                 None => return None,
2227             }
2228         }
2229         Some(start)
2230     }
2231 
2232     /// Accumulator of the elements in the iterator.
2233     ///
2234     /// Like `.fold()`, without a base case. If the iterator is
2235     /// empty, return `None`. With just one element, return it.
2236     /// Otherwise elements are accumulated in sequence using the closure `f`.
2237     ///
2238     /// ```
2239     /// use itertools::Itertools;
2240     ///
2241     /// assert_eq!((0..10).fold1(|x, y| x + y).unwrap_or(0), 45);
2242     /// assert_eq!((0..0).fold1(|x, y| x * y), None);
2243     /// ```
fold1<F>(mut self, f: F) -> Option<Self::Item> where F: FnMut(Self::Item, Self::Item) -> Self::Item, Self: Sized,2244     fn fold1<F>(mut self, f: F) -> Option<Self::Item>
2245         where F: FnMut(Self::Item, Self::Item) -> Self::Item,
2246               Self: Sized,
2247     {
2248         self.next().map(move |x| self.fold(x, f))
2249     }
2250 
2251     /// Accumulate the elements in the iterator in a tree-like manner.
2252     ///
2253     /// You can think of it as, while there's more than one item, repeatedly
2254     /// combining adjacent items.  It does so in bottom-up-merge-sort order,
2255     /// however, so that it needs only logarithmic stack space.
2256     ///
2257     /// This produces a call tree like the following (where the calls under
2258     /// an item are done after reading that item):
2259     ///
2260     /// ```text
2261     /// 1 2 3 4 5 6 7
2262     /// │ │ │ │ │ │ │
2263     /// └─f └─f └─f │
2264     ///   │   │   │ │
2265     ///   └───f   └─f
2266     ///       │     │
2267     ///       └─────f
2268     /// ```
2269     ///
2270     /// Which, for non-associative functions, will typically produce a different
2271     /// result than the linear call tree used by `fold1`:
2272     ///
2273     /// ```text
2274     /// 1 2 3 4 5 6 7
2275     /// │ │ │ │ │ │ │
2276     /// └─f─f─f─f─f─f
2277     /// ```
2278     ///
2279     /// If `f` is associative, prefer the normal `fold1` instead.
2280     ///
2281     /// ```
2282     /// use itertools::Itertools;
2283     ///
2284     /// // The same tree as above
2285     /// let num_strings = (1..8).map(|x| x.to_string());
2286     /// assert_eq!(num_strings.tree_fold1(|x, y| format!("f({}, {})", x, y)),
2287     ///     Some(String::from("f(f(f(1, 2), f(3, 4)), f(f(5, 6), 7))")));
2288     ///
2289     /// // Like fold1, an empty iterator produces None
2290     /// assert_eq!((0..0).tree_fold1(|x, y| x * y), None);
2291     ///
2292     /// // tree_fold1 matches fold1 for associative operations...
2293     /// assert_eq!((0..10).tree_fold1(|x, y| x + y),
2294     ///     (0..10).fold1(|x, y| x + y));
2295     /// // ...but not for non-associative ones
2296     /// assert_ne!((0..10).tree_fold1(|x, y| x - y),
2297     ///     (0..10).fold1(|x, y| x - y));
2298     /// ```
tree_fold1<F>(mut self, mut f: F) -> Option<Self::Item> where F: FnMut(Self::Item, Self::Item) -> Self::Item, Self: Sized,2299     fn tree_fold1<F>(mut self, mut f: F) -> Option<Self::Item>
2300         where F: FnMut(Self::Item, Self::Item) -> Self::Item,
2301               Self: Sized,
2302     {
2303         type State<T> = Result<T, Option<T>>;
2304 
2305         fn inner0<T, II, FF>(it: &mut II, f: &mut FF) -> State<T>
2306             where
2307                 II: Iterator<Item = T>,
2308                 FF: FnMut(T, T) -> T
2309         {
2310             // This function could be replaced with `it.next().ok_or(None)`,
2311             // but half the useful tree_fold1 work is combining adjacent items,
2312             // so put that in a form that LLVM is more likely to optimize well.
2313 
2314             let a =
2315                 if let Some(v) = it.next() { v }
2316                 else { return Err(None) };
2317             let b =
2318                 if let Some(v) = it.next() { v }
2319                 else { return Err(Some(a)) };
2320             Ok(f(a, b))
2321         }
2322 
2323         fn inner<T, II, FF>(stop: usize, it: &mut II, f: &mut FF) -> State<T>
2324             where
2325                 II: Iterator<Item = T>,
2326                 FF: FnMut(T, T) -> T
2327         {
2328             let mut x = inner0(it, f)?;
2329             for height in 0..stop {
2330                 // Try to get another tree the same size with which to combine it,
2331                 // creating a new tree that's twice as big for next time around.
2332                 let next =
2333                     if height == 0 {
2334                         inner0(it, f)
2335                     } else {
2336                         inner(height, it, f)
2337                     };
2338                 match next {
2339                     Ok(y) => x = f(x, y),
2340 
2341                     // If we ran out of items, combine whatever we did manage
2342                     // to get.  It's better combined with the current value
2343                     // than something in a parent frame, because the tree in
2344                     // the parent is always as least as big as this one.
2345                     Err(None) => return Err(Some(x)),
2346                     Err(Some(y)) => return Err(Some(f(x, y))),
2347                 }
2348             }
2349             Ok(x)
2350         }
2351 
2352         match inner(usize::max_value(), &mut self, &mut f) {
2353             Err(x) => x,
2354             _ => unreachable!(),
2355         }
2356     }
2357 
2358     /// An iterator method that applies a function, producing a single, final value.
2359     ///
2360     /// `fold_while()` is basically equivalent to [`Iterator::fold`] but with additional support for
2361     /// early exit via short-circuiting.
2362     ///
2363     /// ```
2364     /// use itertools::Itertools;
2365     /// use itertools::FoldWhile::{Continue, Done};
2366     ///
2367     /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2368     ///
2369     /// let mut result = 0;
2370     ///
2371     /// // for loop:
2372     /// for i in &numbers {
2373     ///     if *i > 5 {
2374     ///         break;
2375     ///     }
2376     ///     result = result + i;
2377     /// }
2378     ///
2379     /// // fold:
2380     /// let result2 = numbers.iter().fold(0, |acc, x| {
2381     ///     if *x > 5 { acc } else { acc + x }
2382     /// });
2383     ///
2384     /// // fold_while:
2385     /// let result3 = numbers.iter().fold_while(0, |acc, x| {
2386     ///     if *x > 5 { Done(acc) } else { Continue(acc + x) }
2387     /// }).into_inner();
2388     ///
2389     /// // they're the same
2390     /// assert_eq!(result, result2);
2391     /// assert_eq!(result2, result3);
2392     /// ```
2393     ///
2394     /// The big difference between the computations of `result2` and `result3` is that while
2395     /// `fold()` called the provided closure for every item of the callee iterator,
2396     /// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`.
fold_while<B, F>(&mut self, init: B, mut f: F) -> FoldWhile<B> where Self: Sized, F: FnMut(B, Self::Item) -> FoldWhile<B>2397     fn fold_while<B, F>(&mut self, init: B, mut f: F) -> FoldWhile<B>
2398         where Self: Sized,
2399               F: FnMut(B, Self::Item) -> FoldWhile<B>
2400     {
2401         use Result::{
2402             Ok as Continue,
2403             Err as Break,
2404         };
2405 
2406         let result = self.try_fold(init, #[inline(always)] |acc, v|
2407             match f(acc, v) {
2408               FoldWhile::Continue(acc) => Continue(acc),
2409               FoldWhile::Done(acc) => Break(acc),
2410             }
2411         );
2412 
2413         match result {
2414             Continue(acc) => FoldWhile::Continue(acc),
2415             Break(acc) => FoldWhile::Done(acc),
2416         }
2417     }
2418 
2419     /// Iterate over the entire iterator and add all the elements.
2420     ///
2421     /// An empty iterator returns `None`, otherwise `Some(sum)`.
2422     ///
2423     /// # Panics
2424     ///
2425     /// When calling `sum1()` and a primitive integer type is being returned, this
2426     /// method will panic if the computation overflows and debug assertions are
2427     /// enabled.
2428     ///
2429     /// # Examples
2430     ///
2431     /// ```
2432     /// use itertools::Itertools;
2433     ///
2434     /// let empty_sum = (1..1).sum1::<i32>();
2435     /// assert_eq!(empty_sum, None);
2436     ///
2437     /// let nonempty_sum = (1..11).sum1::<i32>();
2438     /// assert_eq!(nonempty_sum, Some(55));
2439     /// ```
sum1<S>(mut self) -> Option<S> where Self: Sized, S: std::iter::Sum<Self::Item>,2440     fn sum1<S>(mut self) -> Option<S>
2441         where Self: Sized,
2442               S: std::iter::Sum<Self::Item>,
2443     {
2444         self.next()
2445             .map(|first| once(first).chain(self).sum())
2446     }
2447 
2448     /// Iterate over the entire iterator and multiply all the elements.
2449     ///
2450     /// An empty iterator returns `None`, otherwise `Some(product)`.
2451     ///
2452     /// # Panics
2453     ///
2454     /// When calling `product1()` and a primitive integer type is being returned,
2455     /// method will panic if the computation overflows and debug assertions are
2456     /// enabled.
2457     ///
2458     /// # Examples
2459     /// ```
2460     /// use itertools::Itertools;
2461     ///
2462     /// let empty_product = (1..1).product1::<i32>();
2463     /// assert_eq!(empty_product, None);
2464     ///
2465     /// let nonempty_product = (1..11).product1::<i32>();
2466     /// assert_eq!(nonempty_product, Some(3628800));
2467     /// ```
product1<P>(mut self) -> Option<P> where Self: Sized, P: std::iter::Product<Self::Item>,2468     fn product1<P>(mut self) -> Option<P>
2469         where Self: Sized,
2470               P: std::iter::Product<Self::Item>,
2471     {
2472         self.next()
2473             .map(|first| once(first).chain(self).product())
2474     }
2475 
2476     /// Sort all iterator elements into a new iterator in ascending order.
2477     ///
2478     /// **Note:** This consumes the entire iterator, uses the
2479     /// [`slice::sort_unstable`] method and returns the result as a new
2480     /// iterator that owns its elements.
2481     ///
2482     /// The sorted iterator, if directly collected to a `Vec`, is converted
2483     /// without any extra copying or allocation cost.
2484     ///
2485     /// ```
2486     /// use itertools::Itertools;
2487     ///
2488     /// // sort the letters of the text in ascending order
2489     /// let text = "bdacfe";
2490     /// itertools::assert_equal(text.chars().sorted_unstable(),
2491     ///                         "abcdef".chars());
2492     /// ```
2493     #[cfg(feature = "use_alloc")]
sorted_unstable(self) -> VecIntoIter<Self::Item> where Self: Sized, Self::Item: Ord2494     fn sorted_unstable(self) -> VecIntoIter<Self::Item>
2495         where Self: Sized,
2496               Self::Item: Ord
2497     {
2498         // Use .sort_unstable() directly since it is not quite identical with
2499         // .sort_by(Ord::cmp)
2500         let mut v = Vec::from_iter(self);
2501         v.sort_unstable();
2502         v.into_iter()
2503     }
2504 
2505     /// Sort all iterator elements into a new iterator in ascending order.
2506     ///
2507     /// **Note:** This consumes the entire iterator, uses the
2508     /// [`slice::sort_unstable_by`] method and returns the result as a new
2509     /// iterator that owns its elements.
2510     ///
2511     /// The sorted iterator, if directly collected to a `Vec`, is converted
2512     /// without any extra copying or allocation cost.
2513     ///
2514     /// ```
2515     /// use itertools::Itertools;
2516     ///
2517     /// // sort people in descending order by age
2518     /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2519     ///
2520     /// let oldest_people_first = people
2521     ///     .into_iter()
2522     ///     .sorted_unstable_by(|a, b| Ord::cmp(&b.1, &a.1))
2523     ///     .map(|(person, _age)| person);
2524     ///
2525     /// itertools::assert_equal(oldest_people_first,
2526     ///                         vec!["Jill", "Jack", "Jane", "John"]);
2527     /// ```
2528     #[cfg(feature = "use_alloc")]
sorted_unstable_by<F>(self, cmp: F) -> VecIntoIter<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,2529     fn sorted_unstable_by<F>(self, cmp: F) -> VecIntoIter<Self::Item>
2530         where Self: Sized,
2531               F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2532     {
2533         let mut v = Vec::from_iter(self);
2534         v.sort_unstable_by(cmp);
2535         v.into_iter()
2536     }
2537 
2538     /// Sort all iterator elements into a new iterator in ascending order.
2539     ///
2540     /// **Note:** This consumes the entire iterator, uses the
2541     /// [`slice::sort_unstable_by_key`] method and returns the result as a new
2542     /// iterator that owns its elements.
2543     ///
2544     /// The sorted iterator, if directly collected to a `Vec`, is converted
2545     /// without any extra copying or allocation cost.
2546     ///
2547     /// ```
2548     /// use itertools::Itertools;
2549     ///
2550     /// // sort people in descending order by age
2551     /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2552     ///
2553     /// let oldest_people_first = people
2554     ///     .into_iter()
2555     ///     .sorted_unstable_by_key(|x| -x.1)
2556     ///     .map(|(person, _age)| person);
2557     ///
2558     /// itertools::assert_equal(oldest_people_first,
2559     ///                         vec!["Jill", "Jack", "Jane", "John"]);
2560     /// ```
2561     #[cfg(feature = "use_alloc")]
sorted_unstable_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item> where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K,2562     fn sorted_unstable_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item>
2563         where Self: Sized,
2564               K: Ord,
2565               F: FnMut(&Self::Item) -> K,
2566     {
2567         let mut v = Vec::from_iter(self);
2568         v.sort_unstable_by_key(f);
2569         v.into_iter()
2570     }
2571 
2572     /// Sort all iterator elements into a new iterator in ascending order.
2573     ///
2574     /// **Note:** This consumes the entire iterator, uses the
2575     /// [`slice::sort`] method and returns the result as a new
2576     /// iterator that owns its elements.
2577     ///
2578     /// The sorted iterator, if directly collected to a `Vec`, is converted
2579     /// without any extra copying or allocation cost.
2580     ///
2581     /// ```
2582     /// use itertools::Itertools;
2583     ///
2584     /// // sort the letters of the text in ascending order
2585     /// let text = "bdacfe";
2586     /// itertools::assert_equal(text.chars().sorted(),
2587     ///                         "abcdef".chars());
2588     /// ```
2589     #[cfg(feature = "use_alloc")]
sorted(self) -> VecIntoIter<Self::Item> where Self: Sized, Self::Item: Ord2590     fn sorted(self) -> VecIntoIter<Self::Item>
2591         where Self: Sized,
2592               Self::Item: Ord
2593     {
2594         // Use .sort() directly since it is not quite identical with
2595         // .sort_by(Ord::cmp)
2596         let mut v = Vec::from_iter(self);
2597         v.sort();
2598         v.into_iter()
2599     }
2600 
2601     /// Sort all iterator elements into a new iterator in ascending order.
2602     ///
2603     /// **Note:** This consumes the entire iterator, uses the
2604     /// [`slice::sort_by`] method and returns the result as a new
2605     /// iterator that owns its elements.
2606     ///
2607     /// The sorted iterator, if directly collected to a `Vec`, is converted
2608     /// without any extra copying or allocation cost.
2609     ///
2610     /// ```
2611     /// use itertools::Itertools;
2612     ///
2613     /// // sort people in descending order by age
2614     /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2615     ///
2616     /// let oldest_people_first = people
2617     ///     .into_iter()
2618     ///     .sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
2619     ///     .map(|(person, _age)| person);
2620     ///
2621     /// itertools::assert_equal(oldest_people_first,
2622     ///                         vec!["Jill", "Jack", "Jane", "John"]);
2623     /// ```
2624     #[cfg(feature = "use_alloc")]
sorted_by<F>(self, cmp: F) -> VecIntoIter<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,2625     fn sorted_by<F>(self, cmp: F) -> VecIntoIter<Self::Item>
2626         where Self: Sized,
2627               F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2628     {
2629         let mut v = Vec::from_iter(self);
2630         v.sort_by(cmp);
2631         v.into_iter()
2632     }
2633 
2634     /// Sort all iterator elements into a new iterator in ascending order.
2635     ///
2636     /// **Note:** This consumes the entire iterator, uses the
2637     /// [`slice::sort_by_key`] method and returns the result as a new
2638     /// iterator that owns its elements.
2639     ///
2640     /// The sorted iterator, if directly collected to a `Vec`, is converted
2641     /// without any extra copying or allocation cost.
2642     ///
2643     /// ```
2644     /// use itertools::Itertools;
2645     ///
2646     /// // sort people in descending order by age
2647     /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2648     ///
2649     /// let oldest_people_first = people
2650     ///     .into_iter()
2651     ///     .sorted_by_key(|x| -x.1)
2652     ///     .map(|(person, _age)| person);
2653     ///
2654     /// itertools::assert_equal(oldest_people_first,
2655     ///                         vec!["Jill", "Jack", "Jane", "John"]);
2656     /// ```
2657     #[cfg(feature = "use_alloc")]
sorted_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item> where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K,2658     fn sorted_by_key<K, F>(self, f: F) -> VecIntoIter<Self::Item>
2659         where Self: Sized,
2660               K: Ord,
2661               F: FnMut(&Self::Item) -> K,
2662     {
2663         let mut v = Vec::from_iter(self);
2664         v.sort_by_key(f);
2665         v.into_iter()
2666     }
2667 
2668     /// Sort the k smallest elements into a new iterator, in ascending order.
2669     ///
2670     /// **Note:** This consumes the entire iterator, and returns the result
2671     /// as a new iterator that owns its elements.  If the input contains
2672     /// less than k elements, the result is equivalent to `self.sorted()`.
2673     ///
2674     /// This is guaranteed to use `k * sizeof(Self::Item) + O(1)` memory
2675     /// and `O(n log k)` time, with `n` the number of elements in the input.
2676     ///
2677     /// The sorted iterator, if directly collected to a `Vec`, is converted
2678     /// without any extra copying or allocation cost.
2679     ///
2680     /// **Note:** This is functionally-equivalent to `self.sorted().take(k)`
2681     /// but much more efficient.
2682     ///
2683     /// ```
2684     /// use itertools::Itertools;
2685     ///
2686     /// // A random permutation of 0..15
2687     /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
2688     ///
2689     /// let five_smallest = numbers
2690     ///     .into_iter()
2691     ///     .k_smallest(5);
2692     ///
2693     /// itertools::assert_equal(five_smallest, 0..5);
2694     /// ```
2695     #[cfg(feature = "use_alloc")]
k_smallest(self, k: usize) -> VecIntoIter<Self::Item> where Self: Sized, Self::Item: Ord2696     fn k_smallest(self, k: usize) -> VecIntoIter<Self::Item>
2697         where Self: Sized,
2698               Self::Item: Ord
2699     {
2700         crate::k_smallest::k_smallest(self, k)
2701             .into_sorted_vec()
2702             .into_iter()
2703     }
2704 
2705     /// Collect all iterator elements into one of two
2706     /// partitions. Unlike [`Iterator::partition`], each partition may
2707     /// have a distinct type.
2708     ///
2709     /// ```
2710     /// use itertools::{Itertools, Either};
2711     ///
2712     /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
2713     ///
2714     /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
2715     ///     .into_iter()
2716     ///     .partition_map(|r| {
2717     ///         match r {
2718     ///             Ok(v) => Either::Left(v),
2719     ///             Err(v) => Either::Right(v),
2720     ///         }
2721     ///     });
2722     ///
2723     /// assert_eq!(successes, [1, 2]);
2724     /// assert_eq!(failures, [false, true]);
2725     /// ```
partition_map<A, B, F, L, R>(self, mut predicate: F) -> (A, B) where Self: Sized, F: FnMut(Self::Item) -> Either<L, R>, A: Default + Extend<L>, B: Default + Extend<R>,2726     fn partition_map<A, B, F, L, R>(self, mut predicate: F) -> (A, B)
2727         where Self: Sized,
2728               F: FnMut(Self::Item) -> Either<L, R>,
2729               A: Default + Extend<L>,
2730               B: Default + Extend<R>,
2731     {
2732         let mut left = A::default();
2733         let mut right = B::default();
2734 
2735         self.for_each(|val| match predicate(val) {
2736             Either::Left(v) => left.extend(Some(v)),
2737             Either::Right(v) => right.extend(Some(v)),
2738         });
2739 
2740         (left, right)
2741     }
2742 
2743     /// Partition a sequence of `Result`s into one list of all the `Ok` elements
2744     /// and another list of all the `Err` elements.
2745     ///
2746     /// ```
2747     /// use itertools::Itertools;
2748     ///
2749     /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
2750     ///
2751     /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
2752     ///     .into_iter()
2753     ///     .partition_result();
2754     ///
2755     /// assert_eq!(successes, [1, 2]);
2756     /// assert_eq!(failures, [false, true]);
2757     /// ```
partition_result<A, B, T, E>(self) -> (A, B) where Self: Iterator<Item = Result<T, E>> + Sized, A: Default + Extend<T>, B: Default + Extend<E>,2758     fn partition_result<A, B, T, E>(self) -> (A, B)
2759         where
2760             Self: Iterator<Item = Result<T, E>> + Sized,
2761             A: Default + Extend<T>,
2762             B: Default + Extend<E>,
2763     {
2764         self.partition_map(|r| match r {
2765             Ok(v) => Either::Left(v),
2766             Err(v) => Either::Right(v),
2767         })
2768     }
2769 
2770     /// Return a `HashMap` of keys mapped to `Vec`s of values. Keys and values
2771     /// are taken from `(Key, Value)` tuple pairs yielded by the input iterator.
2772     ///
2773     /// ```
2774     /// use itertools::Itertools;
2775     ///
2776     /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
2777     /// let lookup = data.into_iter().into_group_map();
2778     ///
2779     /// assert_eq!(lookup[&0], vec![10, 20]);
2780     /// assert_eq!(lookup.get(&1), None);
2781     /// assert_eq!(lookup[&2], vec![12, 42]);
2782     /// assert_eq!(lookup[&3], vec![13, 33]);
2783     /// ```
2784     #[cfg(feature = "use_std")]
into_group_map<K, V>(self) -> HashMap<K, Vec<V>> where Self: Iterator<Item=(K, V)> + Sized, K: Hash + Eq,2785     fn into_group_map<K, V>(self) -> HashMap<K, Vec<V>>
2786         where Self: Iterator<Item=(K, V)> + Sized,
2787               K: Hash + Eq,
2788     {
2789         group_map::into_group_map(self)
2790     }
2791 
2792     /// Return an `Iterator` on a `HashMap`. Keys mapped to `Vec`s of values. The key is specified
2793     /// in the closure.
2794     /// Different to `into_group_map_by` because the key is still present. It is also more general.
2795     /// You can also fold the `group_map`.
2796     ///
2797     /// ```
2798     /// use itertools::Itertools;
2799     /// use std::collections::HashMap;
2800     ///
2801     /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
2802     /// let lookup: HashMap<u32,Vec<(u32, u32)>> =
2803     ///     data.clone().into_iter().into_group_map_by(|a| a.0);
2804     ///
2805     /// assert_eq!(lookup[&0], vec![(0,10),(0,20)]);
2806     /// assert_eq!(lookup.get(&1), None);
2807     /// assert_eq!(lookup[&2], vec![(2,12), (2,42)]);
2808     /// assert_eq!(lookup[&3], vec![(3,13), (3,33)]);
2809     ///
2810     /// assert_eq!(
2811     ///     data.into_iter()
2812     ///         .into_group_map_by(|x| x.0)
2813     ///         .into_iter()
2814     ///         .map(|(key, values)| (key, values.into_iter().fold(0,|acc, (_,v)| acc + v )))
2815     ///         .collect::<HashMap<u32,u32>>()[&0],
2816     ///     30,
2817     /// );
2818     /// ```
2819     #[cfg(feature = "use_std")]
into_group_map_by<K, V, F>(self, f: F) -> HashMap<K, Vec<V>> where Self: Iterator<Item=V> + Sized, K: Hash + Eq, F: Fn(&V) -> K,2820     fn into_group_map_by<K, V, F>(self, f: F) -> HashMap<K, Vec<V>>
2821         where
2822             Self: Iterator<Item=V> + Sized,
2823             K: Hash + Eq,
2824             F: Fn(&V) -> K,
2825     {
2826         group_map::into_group_map_by(self, f)
2827     }
2828 
2829     /// Constructs a `GroupingMap` to be used later with one of the efficient
2830     /// group-and-fold operations it allows to perform.
2831     ///
2832     /// The input iterator must yield item in the form of `(K, V)` where the
2833     /// value of type `K` will be used as key to identify the groups and the
2834     /// value of type `V` as value for the folding operation.
2835     ///
2836     /// See [`GroupingMap`] for more informations
2837     /// on what operations are available.
2838     #[cfg(feature = "use_std")]
into_grouping_map<K, V>(self) -> GroupingMap<Self> where Self: Iterator<Item=(K, V)> + Sized, K: Hash + Eq,2839     fn into_grouping_map<K, V>(self) -> GroupingMap<Self>
2840         where Self: Iterator<Item=(K, V)> + Sized,
2841               K: Hash + Eq,
2842     {
2843         grouping_map::new(self)
2844     }
2845 
2846     /// Constructs a `GroupingMap` to be used later with one of the efficient
2847     /// group-and-fold operations it allows to perform.
2848     ///
2849     /// The values from this iterator will be used as values for the folding operation
2850     /// while the keys will be obtained from the values by calling `key_mapper`.
2851     ///
2852     /// See [`GroupingMap`] for more informations
2853     /// on what operations are available.
2854     #[cfg(feature = "use_std")]
into_grouping_map_by<K, V, F>(self, key_mapper: F) -> GroupingMapBy<Self, F> where Self: Iterator<Item=V> + Sized, K: Hash + Eq, F: FnMut(&V) -> K2855     fn into_grouping_map_by<K, V, F>(self, key_mapper: F) -> GroupingMapBy<Self, F>
2856         where Self: Iterator<Item=V> + Sized,
2857               K: Hash + Eq,
2858               F: FnMut(&V) -> K
2859     {
2860         grouping_map::new(grouping_map::MapForGrouping::new(self, key_mapper))
2861     }
2862 
2863     /// Return the minimum and maximum elements in the iterator.
2864     ///
2865     /// The return type `MinMaxResult` is an enum of three variants:
2866     ///
2867     /// - `NoElements` if the iterator is empty.
2868     /// - `OneElement(x)` if the iterator has exactly one element.
2869     /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
2870     ///    values are equal if and only if there is more than one
2871     ///    element in the iterator and all elements are equal.
2872     ///
2873     /// On an iterator of length `n`, `minmax` does `1.5 * n` comparisons,
2874     /// and so is faster than calling `min` and `max` separately which does
2875     /// `2 * n` comparisons.
2876     ///
2877     /// # Examples
2878     ///
2879     /// ```
2880     /// use itertools::Itertools;
2881     /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
2882     ///
2883     /// let a: [i32; 0] = [];
2884     /// assert_eq!(a.iter().minmax(), NoElements);
2885     ///
2886     /// let a = [1];
2887     /// assert_eq!(a.iter().minmax(), OneElement(&1));
2888     ///
2889     /// let a = [1, 2, 3, 4, 5];
2890     /// assert_eq!(a.iter().minmax(), MinMax(&1, &5));
2891     ///
2892     /// let a = [1, 1, 1, 1];
2893     /// assert_eq!(a.iter().minmax(), MinMax(&1, &1));
2894     /// ```
2895     ///
2896     /// The elements can be floats but no particular result is guaranteed
2897     /// if an element is NaN.
minmax(self) -> MinMaxResult<Self::Item> where Self: Sized, Self::Item: PartialOrd2898     fn minmax(self) -> MinMaxResult<Self::Item>
2899         where Self: Sized, Self::Item: PartialOrd
2900     {
2901         minmax::minmax_impl(self, |_| (), |x, y, _, _| x < y)
2902     }
2903 
2904     /// Return the minimum and maximum element of an iterator, as determined by
2905     /// the specified function.
2906     ///
2907     /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
2908     ///
2909     /// For the minimum, the first minimal element is returned.  For the maximum,
2910     /// the last maximal element wins.  This matches the behavior of the standard
2911     /// [`Iterator::min`] and [`Iterator::max`] methods.
2912     ///
2913     /// The keys can be floats but no particular result is guaranteed
2914     /// if a key is NaN.
minmax_by_key<K, F>(self, key: F) -> MinMaxResult<Self::Item> where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K2915     fn minmax_by_key<K, F>(self, key: F) -> MinMaxResult<Self::Item>
2916         where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K
2917     {
2918         minmax::minmax_impl(self, key, |_, _, xk, yk| xk < yk)
2919     }
2920 
2921     /// Return the minimum and maximum element of an iterator, as determined by
2922     /// the specified comparison function.
2923     ///
2924     /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
2925     ///
2926     /// For the minimum, the first minimal element is returned.  For the maximum,
2927     /// the last maximal element wins.  This matches the behavior of the standard
2928     /// [`Iterator::min`] and [`Iterator::max`] methods.
minmax_by<F>(self, mut compare: F) -> MinMaxResult<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering2929     fn minmax_by<F>(self, mut compare: F) -> MinMaxResult<Self::Item>
2930         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering
2931     {
2932         minmax::minmax_impl(
2933             self,
2934             |_| (),
2935             |x, y, _, _| Ordering::Less == compare(x, y)
2936         )
2937     }
2938 
2939     /// Return the position of the maximum element in the iterator.
2940     ///
2941     /// If several elements are equally maximum, the position of the
2942     /// last of them is returned.
2943     ///
2944     /// # Examples
2945     ///
2946     /// ```
2947     /// use itertools::Itertools;
2948     ///
2949     /// let a: [i32; 0] = [];
2950     /// assert_eq!(a.iter().position_max(), None);
2951     ///
2952     /// let a = [-3, 0, 1, 5, -10];
2953     /// assert_eq!(a.iter().position_max(), Some(3));
2954     ///
2955     /// let a = [1, 1, -1, -1];
2956     /// assert_eq!(a.iter().position_max(), Some(1));
2957     /// ```
position_max(self) -> Option<usize> where Self: Sized, Self::Item: Ord2958     fn position_max(self) -> Option<usize>
2959         where Self: Sized, Self::Item: Ord
2960     {
2961         self.enumerate()
2962             .max_by(|x, y| Ord::cmp(&x.1, &y.1))
2963             .map(|x| x.0)
2964     }
2965 
2966     /// Return the position of the maximum element in the iterator, as
2967     /// determined by the specified function.
2968     ///
2969     /// If several elements are equally maximum, the position of the
2970     /// last of them is returned.
2971     ///
2972     /// # Examples
2973     ///
2974     /// ```
2975     /// use itertools::Itertools;
2976     ///
2977     /// let a: [i32; 0] = [];
2978     /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), None);
2979     ///
2980     /// let a = [-3_i32, 0, 1, 5, -10];
2981     /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(4));
2982     ///
2983     /// let a = [1_i32, 1, -1, -1];
2984     /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(3));
2985     /// ```
position_max_by_key<K, F>(self, mut key: F) -> Option<usize> where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K2986     fn position_max_by_key<K, F>(self, mut key: F) -> Option<usize>
2987         where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K
2988     {
2989         self.enumerate()
2990             .max_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1)))
2991             .map(|x| x.0)
2992     }
2993 
2994     /// Return the position of the maximum element in the iterator, as
2995     /// determined by the specified comparison function.
2996     ///
2997     /// If several elements are equally maximum, the position of the
2998     /// last of them is returned.
2999     ///
3000     /// # Examples
3001     ///
3002     /// ```
3003     /// use itertools::Itertools;
3004     ///
3005     /// let a: [i32; 0] = [];
3006     /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), None);
3007     ///
3008     /// let a = [-3_i32, 0, 1, 5, -10];
3009     /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(3));
3010     ///
3011     /// let a = [1_i32, 1, -1, -1];
3012     /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(1));
3013     /// ```
position_max_by<F>(self, mut compare: F) -> Option<usize> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering3014     fn position_max_by<F>(self, mut compare: F) -> Option<usize>
3015         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering
3016     {
3017         self.enumerate()
3018             .max_by(|x, y| compare(&x.1, &y.1))
3019             .map(|x| x.0)
3020     }
3021 
3022     /// Return the position of the minimum element in the iterator.
3023     ///
3024     /// If several elements are equally minimum, the position of the
3025     /// first of them is returned.
3026     ///
3027     /// # Examples
3028     ///
3029     /// ```
3030     /// use itertools::Itertools;
3031     ///
3032     /// let a: [i32; 0] = [];
3033     /// assert_eq!(a.iter().position_min(), None);
3034     ///
3035     /// let a = [-3, 0, 1, 5, -10];
3036     /// assert_eq!(a.iter().position_min(), Some(4));
3037     ///
3038     /// let a = [1, 1, -1, -1];
3039     /// assert_eq!(a.iter().position_min(), Some(2));
3040     /// ```
position_min(self) -> Option<usize> where Self: Sized, Self::Item: Ord3041     fn position_min(self) -> Option<usize>
3042         where Self: Sized, Self::Item: Ord
3043     {
3044         self.enumerate()
3045             .min_by(|x, y| Ord::cmp(&x.1, &y.1))
3046             .map(|x| x.0)
3047     }
3048 
3049     /// Return the position of the minimum element in the iterator, as
3050     /// determined by the specified function.
3051     ///
3052     /// If several elements are equally minimum, the position of the
3053     /// first of them is returned.
3054     ///
3055     /// # Examples
3056     ///
3057     /// ```
3058     /// use itertools::Itertools;
3059     ///
3060     /// let a: [i32; 0] = [];
3061     /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), None);
3062     ///
3063     /// let a = [-3_i32, 0, 1, 5, -10];
3064     /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(1));
3065     ///
3066     /// let a = [1_i32, 1, -1, -1];
3067     /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(0));
3068     /// ```
position_min_by_key<K, F>(self, mut key: F) -> Option<usize> where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K3069     fn position_min_by_key<K, F>(self, mut key: F) -> Option<usize>
3070         where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K
3071     {
3072         self.enumerate()
3073             .min_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1)))
3074             .map(|x| x.0)
3075     }
3076 
3077     /// Return the position of the minimum element in the iterator, as
3078     /// determined by the specified comparison function.
3079     ///
3080     /// If several elements are equally minimum, the position of the
3081     /// first of them is returned.
3082     ///
3083     /// # Examples
3084     ///
3085     /// ```
3086     /// use itertools::Itertools;
3087     ///
3088     /// let a: [i32; 0] = [];
3089     /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), None);
3090     ///
3091     /// let a = [-3_i32, 0, 1, 5, -10];
3092     /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(4));
3093     ///
3094     /// let a = [1_i32, 1, -1, -1];
3095     /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(2));
3096     /// ```
position_min_by<F>(self, mut compare: F) -> Option<usize> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering3097     fn position_min_by<F>(self, mut compare: F) -> Option<usize>
3098         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering
3099     {
3100         self.enumerate()
3101             .min_by(|x, y| compare(&x.1, &y.1))
3102             .map(|x| x.0)
3103     }
3104 
3105     /// Return the positions of the minimum and maximum elements in
3106     /// the iterator.
3107     ///
3108     /// The return type [`MinMaxResult`] is an enum of three variants:
3109     ///
3110     /// - `NoElements` if the iterator is empty.
3111     /// - `OneElement(xpos)` if the iterator has exactly one element.
3112     /// - `MinMax(xpos, ypos)` is returned otherwise, where the
3113     ///    element at `xpos` ≤ the element at `ypos`. While the
3114     ///    referenced elements themselves may be equal, `xpos` cannot
3115     ///    be equal to `ypos`.
3116     ///
3117     /// On an iterator of length `n`, `position_minmax` does `1.5 * n`
3118     /// comparisons, and so is faster than calling `positon_min` and
3119     /// `position_max` separately which does `2 * n` comparisons.
3120     ///
3121     /// For the minimum, if several elements are equally minimum, the
3122     /// position of the first of them is returned. For the maximum, if
3123     /// several elements are equally maximum, the position of the last
3124     /// of them is returned.
3125     ///
3126     /// The elements can be floats but no particular result is
3127     /// guaranteed if an element is NaN.
3128     ///
3129     /// # Examples
3130     ///
3131     /// ```
3132     /// use itertools::Itertools;
3133     /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3134     ///
3135     /// let a: [i32; 0] = [];
3136     /// assert_eq!(a.iter().position_minmax(), NoElements);
3137     ///
3138     /// let a = [10];
3139     /// assert_eq!(a.iter().position_minmax(), OneElement(0));
3140     ///
3141     /// let a = [-3, 0, 1, 5, -10];
3142     /// assert_eq!(a.iter().position_minmax(), MinMax(4, 3));
3143     ///
3144     /// let a = [1, 1, -1, -1];
3145     /// assert_eq!(a.iter().position_minmax(), MinMax(2, 1));
3146     /// ```
position_minmax(self) -> MinMaxResult<usize> where Self: Sized, Self::Item: PartialOrd3147     fn position_minmax(self) -> MinMaxResult<usize>
3148         where Self: Sized, Self::Item: PartialOrd
3149     {
3150         use crate::MinMaxResult::{NoElements, OneElement, MinMax};
3151         match minmax::minmax_impl(self.enumerate(), |_| (), |x, y, _, _| x.1 < y.1) {
3152             NoElements => NoElements,
3153             OneElement(x) => OneElement(x.0),
3154             MinMax(x, y) => MinMax(x.0, y.0),
3155         }
3156     }
3157 
3158     /// Return the postions of the minimum and maximum elements of an
3159     /// iterator, as determined by the specified function.
3160     ///
3161     /// The return value is a variant of [`MinMaxResult`] like for
3162     /// [`position_minmax`].
3163     ///
3164     /// For the minimum, if several elements are equally minimum, the
3165     /// position of the first of them is returned. For the maximum, if
3166     /// several elements are equally maximum, the position of the last
3167     /// of them is returned.
3168     ///
3169     /// The keys can be floats but no particular result is guaranteed
3170     /// if a key is NaN.
3171     ///
3172     /// # Examples
3173     ///
3174     /// ```
3175     /// use itertools::Itertools;
3176     /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3177     ///
3178     /// let a: [i32; 0] = [];
3179     /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), NoElements);
3180     ///
3181     /// let a = [10_i32];
3182     /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), OneElement(0));
3183     ///
3184     /// let a = [-3_i32, 0, 1, 5, -10];
3185     /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(1, 4));
3186     ///
3187     /// let a = [1_i32, 1, -1, -1];
3188     /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(0, 3));
3189     /// ```
3190     ///
3191     /// [`position_minmax`]: Self::position_minmax
position_minmax_by_key<K, F>(self, mut key: F) -> MinMaxResult<usize> where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K3192     fn position_minmax_by_key<K, F>(self, mut key: F) -> MinMaxResult<usize>
3193         where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K
3194     {
3195         use crate::MinMaxResult::{NoElements, OneElement, MinMax};
3196         match self.enumerate().minmax_by_key(|e| key(&e.1)) {
3197             NoElements => NoElements,
3198             OneElement(x) => OneElement(x.0),
3199             MinMax(x, y) => MinMax(x.0, y.0),
3200         }
3201     }
3202 
3203     /// Return the postions of the minimum and maximum elements of an
3204     /// iterator, as determined by the specified comparison function.
3205     ///
3206     /// The return value is a variant of [`MinMaxResult`] like for
3207     /// [`position_minmax`].
3208     ///
3209     /// For the minimum, if several elements are equally minimum, the
3210     /// position of the first of them is returned. For the maximum, if
3211     /// several elements are equally maximum, the position of the last
3212     /// of them is returned.
3213     ///
3214     /// # Examples
3215     ///
3216     /// ```
3217     /// use itertools::Itertools;
3218     /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3219     ///
3220     /// let a: [i32; 0] = [];
3221     /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), NoElements);
3222     ///
3223     /// let a = [10_i32];
3224     /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), OneElement(0));
3225     ///
3226     /// let a = [-3_i32, 0, 1, 5, -10];
3227     /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(4, 3));
3228     ///
3229     /// let a = [1_i32, 1, -1, -1];
3230     /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(2, 1));
3231     /// ```
3232     ///
3233     /// [`position_minmax`]: Self::position_minmax
position_minmax_by<F>(self, mut compare: F) -> MinMaxResult<usize> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering3234     fn position_minmax_by<F>(self, mut compare: F) -> MinMaxResult<usize>
3235         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering
3236     {
3237         use crate::MinMaxResult::{NoElements, OneElement, MinMax};
3238         match self.enumerate().minmax_by(|x, y| compare(&x.1, &y.1)) {
3239             NoElements => NoElements,
3240             OneElement(x) => OneElement(x.0),
3241             MinMax(x, y) => MinMax(x.0, y.0),
3242         }
3243     }
3244 
3245     /// If the iterator yields exactly one element, that element will be returned, otherwise
3246     /// an error will be returned containing an iterator that has the same output as the input
3247     /// iterator.
3248     ///
3249     /// This provides an additional layer of validation over just calling `Iterator::next()`.
3250     /// If your assumption that there should only be one element yielded is false this provides
3251     /// the opportunity to detect and handle that, preventing errors at a distance.
3252     ///
3253     /// # Examples
3254     /// ```
3255     /// use itertools::Itertools;
3256     ///
3257     /// assert_eq!((0..10).filter(|&x| x == 2).exactly_one().unwrap(), 2);
3258     /// assert!((0..10).filter(|&x| x > 1 && x < 4).exactly_one().unwrap_err().eq(2..4));
3259     /// assert!((0..10).filter(|&x| x > 1 && x < 5).exactly_one().unwrap_err().eq(2..5));
3260     /// assert!((0..10).filter(|&_| false).exactly_one().unwrap_err().eq(0..0));
3261     /// ```
exactly_one(mut self) -> Result<Self::Item, ExactlyOneError<Self>> where Self: Sized,3262     fn exactly_one(mut self) -> Result<Self::Item, ExactlyOneError<Self>>
3263     where
3264         Self: Sized,
3265     {
3266         match self.next() {
3267             Some(first) => {
3268                 match self.next() {
3269                     Some(second) => {
3270                         Err(ExactlyOneError::new(Some(Either::Left([first, second])), self))
3271                     }
3272                     None => {
3273                         Ok(first)
3274                     }
3275                 }
3276             }
3277             None => Err(ExactlyOneError::new(None, self)),
3278         }
3279     }
3280 
3281     /// If the iterator yields no elements, Ok(None) will be returned. If the iterator yields
3282     /// exactly one element, that element will be returned, otherwise an error will be returned
3283     /// containing an iterator that has the same output as the input iterator.
3284     ///
3285     /// This provides an additional layer of validation over just calling `Iterator::next()`.
3286     /// If your assumption that there should be at most one element yielded is false this provides
3287     /// the opportunity to detect and handle that, preventing errors at a distance.
3288     ///
3289     /// # Examples
3290     /// ```
3291     /// use itertools::Itertools;
3292     ///
3293     /// assert_eq!((0..10).filter(|&x| x == 2).at_most_one().unwrap(), Some(2));
3294     /// assert!((0..10).filter(|&x| x > 1 && x < 4).at_most_one().unwrap_err().eq(2..4));
3295     /// assert!((0..10).filter(|&x| x > 1 && x < 5).at_most_one().unwrap_err().eq(2..5));
3296     /// assert_eq!((0..10).filter(|&_| false).at_most_one().unwrap(), None);
3297     /// ```
at_most_one(mut self) -> Result<Option<Self::Item>, ExactlyOneError<Self>> where Self: Sized,3298     fn at_most_one(mut self) -> Result<Option<Self::Item>, ExactlyOneError<Self>>
3299     where
3300         Self: Sized,
3301     {
3302         match self.next() {
3303             Some(first) => {
3304                 match self.next() {
3305                     Some(second) => {
3306                         Err(ExactlyOneError::new(Some(Either::Left([first, second])), self))
3307                     }
3308                     None => {
3309                         Ok(Some(first))
3310                     }
3311                 }
3312             }
3313             None => Ok(None),
3314         }
3315     }
3316 
3317     /// An iterator adaptor that allows the user to peek at multiple `.next()`
3318     /// values without advancing the base iterator.
3319     ///
3320     /// # Examples
3321     /// ```
3322     /// use itertools::Itertools;
3323     ///
3324     /// let mut iter = (0..10).multipeek();
3325     /// assert_eq!(iter.peek(), Some(&0));
3326     /// assert_eq!(iter.peek(), Some(&1));
3327     /// assert_eq!(iter.peek(), Some(&2));
3328     /// assert_eq!(iter.next(), Some(0));
3329     /// assert_eq!(iter.peek(), Some(&1));
3330     /// ```
3331     #[cfg(feature = "use_alloc")]
multipeek(self) -> MultiPeek<Self> where Self: Sized,3332     fn multipeek(self) -> MultiPeek<Self>
3333     where
3334         Self: Sized,
3335     {
3336         multipeek_impl::multipeek(self)
3337     }
3338 
3339     /// Collect the items in this iterator and return a `HashMap` which
3340     /// contains each item that appears in the iterator and the number
3341     /// of times it appears.
3342     ///
3343     /// # Examples
3344     /// ```
3345     /// # use itertools::Itertools;
3346     /// let counts = [1, 1, 1, 3, 3, 5].into_iter().counts();
3347     /// assert_eq!(counts[&1], 3);
3348     /// assert_eq!(counts[&3], 2);
3349     /// assert_eq!(counts[&5], 1);
3350     /// assert_eq!(counts.get(&0), None);
3351     /// ```
3352     #[cfg(feature = "use_std")]
counts(self) -> HashMap<Self::Item, usize> where Self: Sized, Self::Item: Eq + Hash,3353     fn counts(self) -> HashMap<Self::Item, usize>
3354     where
3355         Self: Sized,
3356         Self::Item: Eq + Hash,
3357     {
3358         let mut counts = HashMap::new();
3359         self.for_each(|item| *counts.entry(item).or_default() += 1);
3360         counts
3361     }
3362 
3363     /// Collect the items in this iterator and return a `HashMap` which
3364     /// contains each item that appears in the iterator and the number
3365     /// of times it appears,
3366     /// determining identity using a keying function.
3367     ///
3368     /// ```
3369     /// # use itertools::Itertools;
3370     /// struct Character {
3371     ///   first_name: &'static str,
3372     ///   last_name:  &'static str,
3373     /// }
3374     ///
3375     /// let characters =
3376     ///     vec![
3377     ///         Character { first_name: "Amy",   last_name: "Pond"      },
3378     ///         Character { first_name: "Amy",   last_name: "Wong"      },
3379     ///         Character { first_name: "Amy",   last_name: "Santiago"  },
3380     ///         Character { first_name: "James", last_name: "Bond"      },
3381     ///         Character { first_name: "James", last_name: "Sullivan"  },
3382     ///         Character { first_name: "James", last_name: "Norington" },
3383     ///         Character { first_name: "James", last_name: "Kirk"      },
3384     ///     ];
3385     ///
3386     /// let first_name_frequency =
3387     ///     characters
3388     ///         .into_iter()
3389     ///         .counts_by(|c| c.first_name);
3390     ///
3391     /// assert_eq!(first_name_frequency["Amy"], 3);
3392     /// assert_eq!(first_name_frequency["James"], 4);
3393     /// assert_eq!(first_name_frequency.contains_key("Asha"), false);
3394     /// ```
3395     #[cfg(feature = "use_std")]
counts_by<K, F>(self, f: F) -> HashMap<K, usize> where Self: Sized, K: Eq + Hash, F: FnMut(Self::Item) -> K,3396     fn counts_by<K, F>(self, f: F) -> HashMap<K, usize>
3397     where
3398         Self: Sized,
3399         K: Eq + Hash,
3400         F: FnMut(Self::Item) -> K,
3401     {
3402         self.map(f).counts()
3403     }
3404 }
3405 
3406 impl<T: ?Sized> Itertools for T where T: Iterator { }
3407 
3408 /// Return `true` if both iterables produce equal sequences
3409 /// (elements pairwise equal and sequences of the same length),
3410 /// `false` otherwise.
3411 ///
3412 /// This is an [`IntoIterator`] enabled function that is similar to the standard
3413 /// library method [`Iterator::eq`].
3414 ///
3415 /// ```
3416 /// assert!(itertools::equal(vec![1, 2, 3], 1..4));
3417 /// assert!(!itertools::equal(&[0, 0], &[0, 0, 0]));
3418 /// ```
equal<I, J>(a: I, b: J) -> bool where I: IntoIterator, J: IntoIterator, I::Item: PartialEq<J::Item>3419 pub fn equal<I, J>(a: I, b: J) -> bool
3420     where I: IntoIterator,
3421           J: IntoIterator,
3422           I::Item: PartialEq<J::Item>
3423 {
3424     let mut ia = a.into_iter();
3425     let mut ib = b.into_iter();
3426     loop {
3427         match ia.next() {
3428             Some(x) => match ib.next() {
3429                 Some(y) => if x != y { return false; },
3430                 None => return false,
3431             },
3432             None => return ib.next().is_none()
3433         }
3434     }
3435 }
3436 
3437 /// Assert that two iterables produce equal sequences, with the same
3438 /// semantics as [`equal(a, b)`](equal).
3439 ///
3440 /// **Panics** on assertion failure with a message that shows the
3441 /// two iteration elements.
3442 ///
3443 /// ```ignore
3444 /// assert_equal("exceed".split('c'), "excess".split('c'));
3445 /// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1',
3446 /// ```
assert_equal<I, J>(a: I, b: J) where I: IntoIterator, J: IntoIterator, I::Item: fmt::Debug + PartialEq<J::Item>, J::Item: fmt::Debug,3447 pub fn assert_equal<I, J>(a: I, b: J)
3448     where I: IntoIterator,
3449           J: IntoIterator,
3450           I::Item: fmt::Debug + PartialEq<J::Item>,
3451           J::Item: fmt::Debug,
3452 {
3453     let mut ia = a.into_iter();
3454     let mut ib = b.into_iter();
3455     let mut i = 0;
3456     loop {
3457         match (ia.next(), ib.next()) {
3458             (None, None) => return,
3459             (a, b) => {
3460                 let equal = match (&a, &b) {
3461                     (&Some(ref a), &Some(ref b)) => a == b,
3462                     _ => false,
3463                 };
3464                 assert!(equal, "Failed assertion {a:?} == {b:?} for iteration {i}",
3465                         i=i, a=a, b=b);
3466                 i += 1;
3467             }
3468         }
3469     }
3470 }
3471 
3472 /// Partition a sequence using predicate `pred` so that elements
3473 /// that map to `true` are placed before elements which map to `false`.
3474 ///
3475 /// The order within the partitions is arbitrary.
3476 ///
3477 /// Return the index of the split point.
3478 ///
3479 /// ```
3480 /// use itertools::partition;
3481 ///
3482 /// # // use repeated numbers to not promise any ordering
3483 /// let mut data = [7, 1, 1, 7, 1, 1, 7];
3484 /// let split_index = partition(&mut data, |elt| *elt >= 3);
3485 ///
3486 /// assert_eq!(data, [7, 7, 7, 1, 1, 1, 1]);
3487 /// assert_eq!(split_index, 3);
3488 /// ```
partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize where I: IntoIterator<Item = &'a mut A>, I::IntoIter: DoubleEndedIterator, F: FnMut(&A) -> bool3489 pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize
3490     where I: IntoIterator<Item = &'a mut A>,
3491           I::IntoIter: DoubleEndedIterator,
3492           F: FnMut(&A) -> bool
3493 {
3494     let mut split_index = 0;
3495     let mut iter = iter.into_iter();
3496     'main: while let Some(front) = iter.next() {
3497         if !pred(front) {
3498             loop {
3499                 match iter.next_back() {
3500                     Some(back) => if pred(back) {
3501                         std::mem::swap(front, back);
3502                         break;
3503                     },
3504                     None => break 'main,
3505                 }
3506             }
3507         }
3508         split_index += 1;
3509     }
3510     split_index
3511 }
3512 
3513 /// An enum used for controlling the execution of `fold_while`.
3514 ///
3515 /// See [`.fold_while()`](Itertools::fold_while) for more information.
3516 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3517 pub enum FoldWhile<T> {
3518     /// Continue folding with this value
3519     Continue(T),
3520     /// Fold is complete and will return this value
3521     Done(T),
3522 }
3523 
3524 impl<T> FoldWhile<T> {
3525     /// Return the value in the continue or done.
into_inner(self) -> T3526     pub fn into_inner(self) -> T {
3527         match self {
3528             FoldWhile::Continue(x) | FoldWhile::Done(x) => x,
3529         }
3530     }
3531 
3532     /// Return true if `self` is `Done`, false if it is `Continue`.
is_done(&self) -> bool3533     pub fn is_done(&self) -> bool {
3534         match *self {
3535             FoldWhile::Continue(_) => false,
3536             FoldWhile::Done(_) => true,
3537         }
3538     }
3539 }
3540