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