2 #![crate_name="itertools"]
3 #![cfg_attr(not(feature = "use_std"), no_std)]
5 //! Extra iterator adaptors, functions and macros.
7 //! To extend [`Iterator`] with methods in this crate, import
8 //! the [`Itertools`] trait:
11 //! use itertools::Itertools;
14 //! Now, new methods like [`interleave`](Itertools::interleave)
15 //! are available on all iterators:
18 //! use itertools::Itertools;
20 //! let it = (1..3).interleave(vec![-1, -2]);
21 //! itertools::assert_equal(it, vec![1, -1, 2, -2]);
24 //! Most iterator methods are also provided as functions (with the benefit
25 //! that they convert parameters using [`IntoIterator`]):
28 //! use itertools::interleave;
30 //! for elt in interleave(&[1, 2, 3], &[2, 3, 4]) {
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).
45 //! This version of itertools requires Rust 1.32 or later.
46 #![doc(html_root_url="https://docs.rs/itertools/0.8/")]
48 #[cfg(not(feature = "use_std"))]
49 extern crate core
as std
;
51 #[cfg(feature = "use_alloc")]
54 #[cfg(feature = "use_alloc")]
60 pub use either
::Either
;
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
;
68 #[cfg(feature = "use_std")]
69 use std
::collections
::HashSet
;
70 #[cfg(feature = "use_std")]
72 #[cfg(feature = "use_alloc")]
74 #[cfg(feature = "use_alloc")]
75 type VecIntoIter
<T
> = alloc
::vec
::IntoIter
<T
>;
76 #[cfg(feature = "use_alloc")]
77 use std
::iter
::FromIterator
;
82 // for compatibility with no std and macros
84 pub use std
::iter
as __std_iter
;
86 /// The concrete iterator types.
88 pub use crate::adaptors
::{
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
;
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
;
162 /// Traits helpful for using certain `Itertools` methods in generic contexts.
164 pub use crate::tuple_impl
::HomogeneousTuple
;
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
;
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
;
186 pub use crate::either_or_both
::EitherOrBoth
;
190 pub use crate::free
::*;
192 mod cons_tuples_impl
;
193 #[cfg(feature = "use_alloc")]
195 #[cfg(feature = "use_alloc")]
196 mod combinations_with_replacement
;
200 #[cfg(feature = "use_std")]
203 #[cfg(feature = "use_std")]
205 #[cfg(feature = "use_alloc")]
207 #[cfg(feature = "use_alloc")]
210 #[cfg(feature = "use_alloc")]
212 #[cfg(feature = "use_alloc")]
214 #[cfg(feature = "use_alloc")]
218 #[cfg(feature = "use_alloc")]
221 #[cfg(feature = "use_alloc")]
223 mod peeking_take_while
;
224 #[cfg(feature = "use_alloc")]
226 #[cfg(feature = "use_alloc")]
228 mod process_results_impl
;
229 #[cfg(feature = "use_alloc")]
231 #[cfg(feature = "use_alloc")]
236 #[cfg(feature = "use_alloc")]
239 #[cfg(feature = "use_std")]
241 #[cfg(feature = "use_std")]
250 /// Create an iterator over the “cartesian product” of iterators.
252 /// Iterator element type is like `(A, B, ..., E)` if formed
253 /// from iterators `(I, J, ..., M)` with element types `I::Item = A`, `J::Item = B`, etc.
256 /// # use itertools::iproduct;
259 /// // Iterate over the coordinates of a 4 x 4 x 4 grid
260 /// // from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
261 /// for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
266 macro_rules
! iproduct
{
267 (@flatten $I
:expr
,) => (
270 (@flatten $I
:expr
, $J
:expr
, $
($K
:expr
,)*) => (
271 $
crate::iproduct
!(@flatten $
crate::cons_tuples($
crate::iproduct
!($I
, $J
)), $
($K
,)*)
274 $
crate::__std_iter
::IntoIterator
::into_iter($I
)
276 ($I
:expr
, $J
:expr
) => (
277 $
crate::Itertools
::cartesian_product($
crate::iproduct
!($I
), $
crate::iproduct
!($J
))
279 ($I
:expr
, $J
:expr
, $
($K
:expr
),+) => (
280 $
crate::iproduct
!(@flatten $
crate::iproduct
!($I
, $J
), $
($K
,)+)
285 /// Create an iterator running multiple iterators in lockstep.
287 /// The `izip!` iterator yields elements until any subiterator
290 /// This is a version of the standard ``.zip()`` that's supporting more than
291 /// two iterators. The iterator element type is a tuple with one element
292 /// from each of the input iterators. Just like ``.zip()``, the iteration stops
293 /// when the shortest of the inputs reaches its end.
295 /// **Note:** The result of this macro is in the general case an iterator
296 /// composed of repeated `.zip()` and a `.map()`; it has an anonymous type.
297 /// The special cases of one and two arguments produce the equivalent of
298 /// `$a.into_iter()` and `$a.into_iter().zip($b)` respectively.
300 /// Prefer this macro `izip!()` over [`multizip`] for the performance benefits
301 /// of using the standard library `.zip()`.
304 /// # use itertools::izip;
308 /// // iterate over three sequences side-by-side
309 /// let mut results = [0, 0, 0, 0];
310 /// let inputs = [3, 7, 9, 6];
312 /// for (r, index, input) in izip!(&mut results, 0..10, &inputs) {
313 /// *r = index * 10 + input;
316 /// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]);
320 // @closure creates a tuple-flattening closure for .map() call. usage:
321 // @closure partial_pattern => partial_tuple , rest , of , iterators
322 // eg. izip!( @closure ((a, b), c) => (a, b, c) , dd , ee )
323 ( @closure $p
:pat
=> $tup
:expr
) => {
327 // The "b" identifier is a different identifier on each recursion level thanks to hygiene.
328 ( @closure $p
:pat
=> ( $
($tup
:tt
)* ) , $_iter
:expr $
( , $tail
:expr
)* ) => {
329 $
crate::izip
!(@
closure ($p
, b
) => ( $
($tup
)*, b
) $
( , $tail
)*)
333 ($first
:expr $
(,)*) => {
334 $
crate::__std_iter
::IntoIterator
::into_iter($first
)
338 ($first
:expr
, $second
:expr $
(,)*) => {
339 $
crate::izip
!($first
)
344 ( $first
:expr $
( , $rest
:expr
)* $
(,)* ) => {
345 $
crate::izip
!($first
)
350 $
crate::izip
!(@closure a
=> (a
) $
( , $rest
)*)
356 /// [Chain][`chain`] zero or more iterators together into one sequence.
358 /// The comma-separated arguments must implement [`IntoIterator`].
359 /// The final argument may be followed by a trailing comma.
361 /// [`chain`]: Iterator::chain
365 /// Empty invocations of `chain!` expand to an invocation of [`std::iter::empty`]:
368 /// use itertools::chain;
370 /// let _: iter::Empty<()> = chain!();
371 /// let _: iter::Empty<i8> = chain!();
374 /// Invocations of `chain!` with one argument expand to [`arg.into_iter()`](IntoIterator):
376 /// use std::{ops::Range, slice};
377 /// use itertools::chain;
378 /// let _: <Range<_> as IntoIterator>::IntoIter = chain!((2..6),); // trailing comma optional!
379 /// let _: <&[_] as IntoIterator>::IntoIter = chain!(&[2, 3, 4]);
382 /// Invocations of `chain!` with multiple arguments [`.into_iter()`](IntoIterator) each
383 /// argument, and then [`chain`] them together:
385 /// use std::{iter::*, ops::Range, slice};
386 /// use itertools::{assert_equal, chain};
389 /// let with_macro: Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
390 /// chain![once(&0), repeat(&1).take(2), &[2, 3, 5],];
392 /// // ...is equivalent to this:
393 /// let with_method: Chain<Chain<Once<_>, Take<Repeat<_>>>, slice::Iter<_>> =
395 /// .chain(repeat(&1).take(2))
396 /// .chain(&[2, 3, 5]);
398 /// assert_equal(with_macro, with_method);
404 ($first
:expr $
(, $rest
:expr
)* $
(,)?
) => {
406 let iter
= core
::iter
::IntoIterator
::into_iter($first
);
409 core
::iter
::Iterator
::chain(
411 core
::iter
::IntoIterator
::into_iter($rest
));
418 /// An [`Iterator`] blanket implementation that provides extra adaptors and
421 /// This trait defines a number of methods. They are divided into two groups:
423 /// * *Adaptors* take an iterator and parameter as input, and return
424 /// a new iterator value. These are listed first in the trait. An example
425 /// of an adaptor is [`.interleave()`](Itertools::interleave)
427 /// * *Regular methods* are those that don't return iterators and instead
428 /// return a regular value of some other kind.
429 /// [`.next_tuple()`](Itertools::next_tuple) is an example and the first regular
430 /// method in the list.
431 pub trait Itertools
: Iterator
{
434 /// Alternate elements from two iterators until both have run out.
436 /// Iterator element type is `Self::Item`.
438 /// This iterator is *fused*.
441 /// use itertools::Itertools;
443 /// let it = (1..7).interleave(vec![-1, -2]);
444 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
446 fn interleave
<J
>(self, other
: J
) -> Interleave
<Self, J
::IntoIter
>
447 where J
: IntoIterator
<Item
= Self::Item
>,
450 interleave(self, other
)
453 /// Alternate elements from two iterators until at least one of them has run
456 /// Iterator element type is `Self::Item`.
459 /// use itertools::Itertools;
461 /// let it = (1..7).interleave_shortest(vec![-1, -2]);
462 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]);
464 fn interleave_shortest
<J
>(self, other
: J
) -> InterleaveShortest
<Self, J
::IntoIter
>
465 where J
: IntoIterator
<Item
= Self::Item
>,
468 adaptors
::interleave_shortest(self, other
.into_iter())
471 /// An iterator adaptor to insert a particular value
472 /// between each element of the adapted iterator.
474 /// Iterator element type is `Self::Item`.
476 /// This iterator is *fused*.
479 /// use itertools::Itertools;
481 /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]);
483 fn intersperse(self, element
: Self::Item
) -> Intersperse
<Self>
487 intersperse
::intersperse(self, element
)
490 /// An iterator adaptor to insert a particular value created by a function
491 /// between each element of the adapted iterator.
493 /// Iterator element type is `Self::Item`.
495 /// This iterator is *fused*.
498 /// use itertools::Itertools;
501 /// itertools::assert_equal((0..3).intersperse_with(|| { i -= 1; i }), vec![0, 9, 1, 8, 2]);
502 /// assert_eq!(i, 8);
504 fn intersperse_with
<F
>(self, element
: F
) -> IntersperseWith
<Self, F
>
506 F
: FnMut() -> Self::Item
508 intersperse
::intersperse_with(self, element
)
511 /// Create an iterator which iterates over both this and the specified
512 /// iterator simultaneously, yielding pairs of two optional elements.
514 /// This iterator is *fused*.
516 /// As long as neither input iterator is exhausted yet, it yields two values
517 /// via `EitherOrBoth::Both`.
519 /// When the parameter iterator is exhausted, it only yields a value from the
520 /// `self` iterator via `EitherOrBoth::Left`.
522 /// When the `self` iterator is exhausted, it only yields a value from the
523 /// parameter iterator via `EitherOrBoth::Right`.
525 /// When both iterators return `None`, all further invocations of `.next()`
526 /// will return `None`.
528 /// Iterator element type is
529 /// [`EitherOrBoth<Self::Item, J::Item>`](EitherOrBoth).
532 /// use itertools::EitherOrBoth::{Both, Right};
533 /// use itertools::Itertools;
534 /// let it = (0..1).zip_longest(1..3);
535 /// itertools::assert_equal(it, vec![Both(0, 1), Right(2)]);
538 fn zip_longest
<J
>(self, other
: J
) -> ZipLongest
<Self, J
::IntoIter
>
539 where J
: IntoIterator
,
542 zip_longest
::zip_longest(self, other
.into_iter())
545 /// Create an iterator which iterates over both this and the specified
546 /// iterator simultaneously, yielding pairs of elements.
548 /// **Panics** if the iterators reach an end and they are not of equal
551 fn zip_eq
<J
>(self, other
: J
) -> ZipEq
<Self, J
::IntoIter
>
552 where J
: IntoIterator
,
558 /// A “meta iterator adaptor”. Its closure receives a reference to the
559 /// iterator and may pick off as many elements as it likes, to produce the
560 /// next iterator element.
562 /// Iterator element type is `B`.
565 /// use itertools::Itertools;
567 /// // An adaptor that gathers elements in pairs
568 /// let pit = (0..4).batching(|it| {
569 /// match it.next() {
571 /// Some(x) => match it.next() {
573 /// Some(y) => Some((x, y)),
578 /// itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
581 fn batching
<B
, F
>(self, f
: F
) -> Batching
<Self, F
>
582 where F
: FnMut(&mut Self) -> Option
<B
>,
585 adaptors
::batching(self, f
)
588 /// Return an *iterable* that can group iterator elements.
589 /// Consecutive elements that map to the same key (“runs”), are assigned
590 /// to the same group.
592 /// `GroupBy` is the storage for the lazy grouping operation.
594 /// If the groups are consumed in order, or if each group's iterator is
595 /// dropped without keeping it around, then `GroupBy` uses no
596 /// allocations. It needs allocations only if several group iterators
597 /// are alive at the same time.
599 /// This type implements [`IntoIterator`] (it is **not** an iterator
600 /// itself), because the group iterators need to borrow from this
601 /// value. It should be stored in a local variable or temporary and
604 /// Iterator element type is `(K, Group)`: the group's key and the
608 /// use itertools::Itertools;
610 /// // group data into runs of larger than zero or not.
611 /// let data = vec![1, 3, -2, -2, 1, 0, 1, 2];
612 /// // groups: |---->|------>|--------->|
614 /// // Note: The `&` is significant here, `GroupBy` is iterable
615 /// // only by reference. You can also call `.into_iter()` explicitly.
616 /// let mut data_grouped = Vec::new();
617 /// for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) {
618 /// data_grouped.push((key, group.collect()));
620 /// assert_eq!(data_grouped, vec![(true, vec![1, 3]), (false, vec![-2, -2]), (true, vec![1, 0, 1, 2])]);
622 #[cfg(feature = "use_alloc")]
623 fn group_by
<K
, F
>(self, key
: F
) -> GroupBy
<K
, Self, F
>
625 F
: FnMut(&Self::Item
) -> K
,
628 groupbylazy
::new(self, key
)
631 /// Return an *iterable* that can chunk the iterator.
633 /// Yield subiterators (chunks) that each yield a fixed number elements,
634 /// determined by `size`. The last chunk will be shorter if there aren't
637 /// `IntoChunks` is based on `GroupBy`: it is iterable (implements
638 /// `IntoIterator`, **not** `Iterator`), and it only buffers if several
639 /// chunk iterators are alive at the same time.
641 /// Iterator element type is `Chunk`, each chunk's iterator.
643 /// **Panics** if `size` is 0.
646 /// use itertools::Itertools;
648 /// let data = vec![1, 1, 2, -2, 6, 0, 3, 1];
649 /// //chunk size=3 |------->|-------->|--->|
651 /// // Note: The `&` is significant here, `IntoChunks` is iterable
652 /// // only by reference. You can also call `.into_iter()` explicitly.
653 /// for chunk in &data.into_iter().chunks(3) {
654 /// // Check that the sum of each chunk is 4.
655 /// assert_eq!(4, chunk.sum());
658 #[cfg(feature = "use_alloc")]
659 fn chunks(self, size
: usize) -> IntoChunks
<Self>
663 groupbylazy
::new_chunks(self, size
)
666 /// Return an iterator over all contiguous windows producing tuples of
667 /// a specific size (up to 12).
669 /// `tuple_windows` clones the iterator elements so that they can be
670 /// part of successive windows, this makes it most suited for iterators
671 /// of references and other values that are cheap to copy.
674 /// use itertools::Itertools;
675 /// let mut v = Vec::new();
677 /// // pairwise iteration
678 /// for (a, b) in (1..5).tuple_windows() {
681 /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4)]);
683 /// let mut it = (1..5).tuple_windows();
684 /// assert_eq!(Some((1, 2, 3)), it.next());
685 /// assert_eq!(Some((2, 3, 4)), it.next());
686 /// assert_eq!(None, it.next());
688 /// // this requires a type hint
689 /// let it = (1..5).tuple_windows::<(_, _, _)>();
690 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
692 /// // you can also specify the complete type
693 /// use itertools::TupleWindows;
694 /// use std::ops::Range;
696 /// let it: TupleWindows<Range<u32>, (u32, u32, u32)> = (1..5).tuple_windows();
697 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
699 fn tuple_windows
<T
>(self) -> TupleWindows
<Self, T
>
700 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
701 T
: traits
::HomogeneousTuple
,
704 tuple_impl
::tuple_windows(self)
707 /// Return an iterator over all windows, wrapping back to the first
708 /// elements when the window would otherwise exceed the length of the
709 /// iterator, producing tuples of a specific size (up to 12).
711 /// `circular_tuple_windows` clones the iterator elements so that they can be
712 /// part of successive windows, this makes it most suited for iterators
713 /// of references and other values that are cheap to copy.
716 /// use itertools::Itertools;
717 /// let mut v = Vec::new();
718 /// for (a, b) in (1..5).circular_tuple_windows() {
721 /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4), (4, 1)]);
723 /// let mut it = (1..5).circular_tuple_windows();
724 /// assert_eq!(Some((1, 2, 3)), it.next());
725 /// assert_eq!(Some((2, 3, 4)), it.next());
726 /// assert_eq!(Some((3, 4, 1)), it.next());
727 /// assert_eq!(Some((4, 1, 2)), it.next());
728 /// assert_eq!(None, it.next());
730 /// // this requires a type hint
731 /// let it = (1..5).circular_tuple_windows::<(_, _, _)>();
732 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)]);
734 fn circular_tuple_windows
<T
>(self) -> CircularTupleWindows
<Self, T
>
735 where Self: Sized
+ Clone
+ Iterator
<Item
= T
::Item
> + ExactSizeIterator
,
736 T
: tuple_impl
::TupleCollect
+ Clone
,
739 tuple_impl
::circular_tuple_windows(self)
741 /// Return an iterator that groups the items in tuples of a specific size
744 /// See also the method [`.next_tuple()`](Itertools::next_tuple).
747 /// use itertools::Itertools;
748 /// let mut v = Vec::new();
749 /// for (a, b) in (1..5).tuples() {
752 /// assert_eq!(v, vec![(1, 2), (3, 4)]);
754 /// let mut it = (1..7).tuples();
755 /// assert_eq!(Some((1, 2, 3)), it.next());
756 /// assert_eq!(Some((4, 5, 6)), it.next());
757 /// assert_eq!(None, it.next());
759 /// // this requires a type hint
760 /// let it = (1..7).tuples::<(_, _, _)>();
761 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
763 /// // you can also specify the complete type
764 /// use itertools::Tuples;
765 /// use std::ops::Range;
767 /// let it: Tuples<Range<u32>, (u32, u32, u32)> = (1..7).tuples();
768 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
771 /// See also [`Tuples::into_buffer`].
772 fn tuples
<T
>(self) -> Tuples
<Self, T
>
773 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
774 T
: traits
::HomogeneousTuple
776 tuple_impl
::tuples(self)
779 /// Split into an iterator pair that both yield all elements from
780 /// the original iterator.
782 /// **Note:** If the iterator is clonable, prefer using that instead
783 /// of using this method. Cloning is likely to be more efficient.
785 /// Iterator element type is `Self::Item`.
788 /// use itertools::Itertools;
789 /// let xs = vec![0, 1, 2, 3];
791 /// let (mut t1, t2) = xs.into_iter().tee();
792 /// itertools::assert_equal(t1.next(), Some(0));
793 /// itertools::assert_equal(t2, 0..4);
794 /// itertools::assert_equal(t1, 1..4);
796 #[cfg(feature = "use_alloc")]
797 fn tee(self) -> (Tee
<Self>, Tee
<Self>)
804 /// Return an iterator adaptor that steps `n` elements in the base iterator
805 /// for each iteration.
807 /// The iterator steps by yielding the next element from the base iterator,
808 /// then skipping forward `n - 1` elements.
810 /// Iterator element type is `Self::Item`.
812 /// **Panics** if the step is 0.
815 /// use itertools::Itertools;
817 /// let it = (0..8).step(3);
818 /// itertools::assert_equal(it, vec![0, 3, 6]);
820 #[deprecated(note="Use std .step_by() instead", since="0.8.0")]
822 fn step(self, n
: usize) -> Step
<Self>
825 adaptors
::step(self, n
)
828 /// Convert each item of the iterator using the [`Into`] trait.
831 /// use itertools::Itertools;
833 /// (1i32..42i32).map_into::<f64>().collect_vec();
835 fn map_into
<R
>(self) -> MapInto
<Self, R
>
839 adaptors
::map_into(self)
842 /// See [`.map_ok()`](Itertools::map_ok).
843 #[deprecated(note="Use .map_ok() instead", since="0.10.0")]
844 fn map_results
<F
, T
, U
, E
>(self, f
: F
) -> MapOk
<Self, F
>
845 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
851 /// Return an iterator adaptor that applies the provided closure
852 /// to every `Result::Ok` value. `Result::Err` values are
856 /// use itertools::Itertools;
858 /// let input = vec![Ok(41), Err(false), Ok(11)];
859 /// let it = input.into_iter().map_ok(|i| i + 1);
860 /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
862 fn map_ok
<F
, T
, U
, E
>(self, f
: F
) -> MapOk
<Self, F
>
863 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
866 adaptors
::map_ok(self, f
)
869 /// Return an iterator adaptor that filters every `Result::Ok`
870 /// value with the provided closure. `Result::Err` values are
874 /// use itertools::Itertools;
876 /// let input = vec![Ok(22), Err(false), Ok(11)];
877 /// let it = input.into_iter().filter_ok(|&i| i > 20);
878 /// itertools::assert_equal(it, vec![Ok(22), Err(false)]);
880 fn filter_ok
<F
, T
, E
>(self, f
: F
) -> FilterOk
<Self, F
>
881 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
882 F
: FnMut(&T
) -> bool
,
884 adaptors
::filter_ok(self, f
)
887 /// Return an iterator adaptor that filters and transforms every
888 /// `Result::Ok` value with the provided closure. `Result::Err`
889 /// values are unchanged.
892 /// use itertools::Itertools;
894 /// let input = vec![Ok(22), Err(false), Ok(11)];
895 /// let it = input.into_iter().filter_map_ok(|i| if i > 20 { Some(i * 2) } else { None });
896 /// itertools::assert_equal(it, vec![Ok(44), Err(false)]);
898 fn filter_map_ok
<F
, T
, U
, E
>(self, f
: F
) -> FilterMapOk
<Self, F
>
899 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
900 F
: FnMut(T
) -> Option
<U
>,
902 adaptors
::filter_map_ok(self, f
)
905 /// Return an iterator adaptor that flattens every `Result::Ok` value into
906 /// a series of `Result::Ok` values. `Result::Err` values are unchanged.
908 /// This is useful when you have some common error type for your crate and
909 /// need to propagate it upwards, but the `Result::Ok` case needs to be flattened.
912 /// use itertools::Itertools;
914 /// let input = vec![Ok(0..2), Err(false), Ok(2..4)];
915 /// let it = input.iter().cloned().flatten_ok();
916 /// itertools::assert_equal(it.clone(), vec![Ok(0), Ok(1), Err(false), Ok(2), Ok(3)]);
918 /// // This can also be used to propagate errors when collecting.
919 /// let output_result: Result<Vec<i32>, bool> = it.collect();
920 /// assert_eq!(output_result, Err(false));
922 fn flatten_ok
<T
, E
>(self) -> FlattenOk
<Self, T
, E
>
923 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
926 flatten_ok
::flatten_ok(self)
929 /// Return an iterator adaptor that merges the two base iterators in
930 /// ascending order. If both base iterators are sorted (ascending), the
931 /// result is sorted.
933 /// Iterator element type is `Self::Item`.
936 /// use itertools::Itertools;
938 /// let a = (0..11).step(3);
939 /// let b = (0..11).step(5);
940 /// let it = a.merge(b);
941 /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]);
943 fn merge
<J
>(self, other
: J
) -> Merge
<Self, J
::IntoIter
>
945 Self::Item
: PartialOrd
,
946 J
: IntoIterator
<Item
= Self::Item
>
951 /// Return an iterator adaptor that merges the two base iterators in order.
952 /// This is much like [`.merge()`](Itertools::merge) but allows for a custom ordering.
954 /// This can be especially useful for sequences of tuples.
956 /// Iterator element type is `Self::Item`.
959 /// use itertools::Itertools;
961 /// let a = (0..).zip("bc".chars());
962 /// let b = (0..).zip("ad".chars());
963 /// let it = a.merge_by(b, |x, y| x.1 <= y.1);
964 /// itertools::assert_equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]);
967 fn merge_by
<J
, F
>(self, other
: J
, is_first
: F
) -> MergeBy
<Self, J
::IntoIter
, F
>
969 J
: IntoIterator
<Item
= Self::Item
>,
970 F
: FnMut(&Self::Item
, &Self::Item
) -> bool
972 adaptors
::merge_by_new(self, other
.into_iter(), is_first
)
975 /// Create an iterator that merges items from both this and the specified
976 /// iterator in ascending order.
978 /// It chooses whether to pair elements based on the `Ordering` returned by the
979 /// specified compare function. At any point, inspecting the tip of the
980 /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
981 /// `J::Item` respectively, the resulting iterator will:
983 /// - Emit `EitherOrBoth::Left(i)` when `i < j`,
984 /// and remove `i` from its source iterator
985 /// - Emit `EitherOrBoth::Right(j)` when `i > j`,
986 /// and remove `j` from its source iterator
987 /// - Emit `EitherOrBoth::Both(i, j)` when `i == j`,
988 /// and remove both `i` and `j` from their respective source iterators
991 /// use itertools::Itertools;
992 /// use itertools::EitherOrBoth::{Left, Right, Both};
994 /// let multiples_of_2 = (0..10).step(2);
995 /// let multiples_of_3 = (0..10).step(3);
997 /// itertools::assert_equal(
998 /// multiples_of_2.merge_join_by(multiples_of_3, |i, j| i.cmp(j)),
999 /// vec![Both(0, 0), Left(2), Right(3), Left(4), Both(6, 6), Left(8), Right(9)]
1003 fn merge_join_by
<J
, F
>(self, other
: J
, cmp_fn
: F
) -> MergeJoinBy
<Self, J
::IntoIter
, F
>
1004 where J
: IntoIterator
,
1005 F
: FnMut(&Self::Item
, &J
::Item
) -> std
::cmp
::Ordering
,
1008 merge_join_by(self, other
, cmp_fn
)
1011 /// Return an iterator adaptor that flattens an iterator of iterators by
1012 /// merging them in ascending order.
1014 /// If all base iterators are sorted (ascending), the result is sorted.
1016 /// Iterator element type is `Self::Item`.
1019 /// use itertools::Itertools;
1021 /// let a = (0..6).step(3);
1022 /// let b = (1..6).step(3);
1023 /// let c = (2..6).step(3);
1024 /// let it = vec![a, b, c].into_iter().kmerge();
1025 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5]);
1027 #[cfg(feature = "use_alloc")]
1028 fn kmerge(self) -> KMerge
<<Self::Item
as IntoIterator
>::IntoIter
>
1030 Self::Item
: IntoIterator
,
1031 <Self::Item
as IntoIterator
>::Item
: PartialOrd
,
1036 /// Return an iterator adaptor that flattens an iterator of iterators by
1037 /// merging them according to the given closure.
1039 /// The closure `first` is called with two elements *a*, *b* and should
1040 /// return `true` if *a* is ordered before *b*.
1042 /// If all base iterators are sorted according to `first`, the result is
1045 /// Iterator element type is `Self::Item`.
1048 /// use itertools::Itertools;
1050 /// let a = vec![-1f64, 2., 3., -5., 6., -7.];
1051 /// let b = vec![0., 2., -4.];
1052 /// let mut it = vec![a, b].into_iter().kmerge_by(|a, b| a.abs() < b.abs());
1053 /// assert_eq!(it.next(), Some(0.));
1054 /// assert_eq!(it.last(), Some(-7.));
1056 #[cfg(feature = "use_alloc")]
1057 fn kmerge_by
<F
>(self, first
: F
)
1058 -> KMergeBy
<<Self::Item
as IntoIterator
>::IntoIter
, F
>
1060 Self::Item
: IntoIterator
,
1061 F
: FnMut(&<Self::Item
as IntoIterator
>::Item
,
1062 &<Self::Item
as IntoIterator
>::Item
) -> bool
1064 kmerge_by(self, first
)
1067 /// Return an iterator adaptor that iterates over the cartesian product of
1068 /// the element sets of two iterators `self` and `J`.
1070 /// Iterator element type is `(Self::Item, J::Item)`.
1073 /// use itertools::Itertools;
1075 /// let it = (0..2).cartesian_product("αβ".chars());
1076 /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]);
1078 fn cartesian_product
<J
>(self, other
: J
) -> Product
<Self, J
::IntoIter
>
1084 adaptors
::cartesian_product(self, other
.into_iter())
1087 /// Return an iterator adaptor that iterates over the cartesian product of
1088 /// all subiterators returned by meta-iterator `self`.
1090 /// All provided iterators must yield the same `Item` type. To generate
1091 /// the product of iterators yielding multiple types, use the
1092 /// [`iproduct`] macro instead.
1095 /// The iterator element type is `Vec<T>`, where `T` is the iterator element
1096 /// of the subiterators.
1099 /// use itertools::Itertools;
1100 /// let mut multi_prod = (0..3).map(|i| (i * 2)..(i * 2 + 2))
1101 /// .multi_cartesian_product();
1102 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 4]));
1103 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 5]));
1104 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 4]));
1105 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 5]));
1106 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 4]));
1107 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 5]));
1108 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 4]));
1109 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 5]));
1110 /// assert_eq!(multi_prod.next(), None);
1112 #[cfg(feature = "use_alloc")]
1113 fn multi_cartesian_product(self) -> MultiProduct
<<Self::Item
as IntoIterator
>::IntoIter
>
1115 Self::Item
: IntoIterator
,
1116 <Self::Item
as IntoIterator
>::IntoIter
: Clone
,
1117 <Self::Item
as IntoIterator
>::Item
: Clone
1119 adaptors
::multi_cartesian_product(self)
1122 /// Return an iterator adaptor that uses the passed-in closure to
1123 /// optionally merge together consecutive elements.
1125 /// The closure `f` is passed two elements, `previous` and `current` and may
1126 /// return either (1) `Ok(combined)` to merge the two values or
1127 /// (2) `Err((previous', current'))` to indicate they can't be merged.
1128 /// In (2), the value `previous'` is emitted by the iterator.
1129 /// Either (1) `combined` or (2) `current'` becomes the previous value
1130 /// when coalesce continues with the next pair of elements to merge. The
1131 /// value that remains at the end is also emitted by the iterator.
1133 /// Iterator element type is `Self::Item`.
1135 /// This iterator is *fused*.
1138 /// use itertools::Itertools;
1140 /// // sum same-sign runs together
1141 /// let data = vec![-1., -2., -3., 3., 1., 0., -1.];
1142 /// itertools::assert_equal(data.into_iter().coalesce(|x, y|
1143 /// if (x >= 0.) == (y >= 0.) {
1148 /// vec![-6., 4., -1.]);
1150 fn coalesce
<F
>(self, f
: F
) -> Coalesce
<Self, F
>
1152 F
: FnMut(Self::Item
, Self::Item
)
1153 -> Result
<Self::Item
, (Self::Item
, Self::Item
)>
1155 adaptors
::coalesce(self, f
)
1158 /// Remove duplicates from sections of consecutive identical elements.
1159 /// If the iterator is sorted, all elements will be unique.
1161 /// Iterator element type is `Self::Item`.
1163 /// This iterator is *fused*.
1166 /// use itertools::Itertools;
1168 /// let data = vec![1., 1., 2., 3., 3., 2., 2.];
1169 /// itertools::assert_equal(data.into_iter().dedup(),
1170 /// vec![1., 2., 3., 2.]);
1172 fn dedup(self) -> Dedup
<Self>
1174 Self::Item
: PartialEq
,
1176 adaptors
::dedup(self)
1179 /// Remove duplicates from sections of consecutive identical elements,
1180 /// determining equality using a comparison function.
1181 /// If the iterator is sorted, all elements will be unique.
1183 /// Iterator element type is `Self::Item`.
1185 /// This iterator is *fused*.
1188 /// use itertools::Itertools;
1190 /// let data = vec![(0, 1.), (1, 1.), (0, 2.), (0, 3.), (1, 3.), (1, 2.), (2, 2.)];
1191 /// itertools::assert_equal(data.into_iter().dedup_by(|x, y| x.1 == y.1),
1192 /// vec![(0, 1.), (0, 2.), (0, 3.), (1, 2.)]);
1194 fn dedup_by
<Cmp
>(self, cmp
: Cmp
) -> DedupBy
<Self, Cmp
>
1196 Cmp
: FnMut(&Self::Item
, &Self::Item
)->bool
,
1198 adaptors
::dedup_by(self, cmp
)
1201 /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1202 /// how many repeated elements were present.
1203 /// If the iterator is sorted, all elements will be unique.
1205 /// Iterator element type is `(usize, Self::Item)`.
1207 /// This iterator is *fused*.
1210 /// use itertools::Itertools;
1212 /// let data = vec!['a', 'a', 'b', 'c', 'c', 'b', 'b'];
1213 /// itertools::assert_equal(data.into_iter().dedup_with_count(),
1214 /// vec![(2, 'a'), (1, 'b'), (2, 'c'), (2, 'b')]);
1216 fn dedup_with_count(self) -> DedupWithCount
<Self>
1220 adaptors
::dedup_with_count(self)
1223 /// Remove duplicates from sections of consecutive identical elements, while keeping a count of
1224 /// how many repeated elements were present.
1225 /// This will determine equality using a comparison function.
1226 /// If the iterator is sorted, all elements will be unique.
1228 /// Iterator element type is `(usize, Self::Item)`.
1230 /// This iterator is *fused*.
1233 /// use itertools::Itertools;
1235 /// let data = vec![(0, 'a'), (1, 'a'), (0, 'b'), (0, 'c'), (1, 'c'), (1, 'b'), (2, 'b')];
1236 /// itertools::assert_equal(data.into_iter().dedup_by_with_count(|x, y| x.1 == y.1),
1237 /// vec![(2, (0, 'a')), (1, (0, 'b')), (2, (0, 'c')), (2, (1, 'b'))]);
1239 fn dedup_by_with_count
<Cmp
>(self, cmp
: Cmp
) -> DedupByWithCount
<Self, Cmp
>
1242 Cmp
: FnMut(&Self::Item
, &Self::Item
) -> bool
,
1244 adaptors
::dedup_by_with_count(self, cmp
)
1247 /// Return an iterator adaptor that produces elements that appear more than once during the
1248 /// iteration. Duplicates are detected using hash and equality.
1250 /// The iterator is stable, returning the duplicate items in the order in which they occur in
1251 /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1252 /// than twice, the second item is the item retained and the rest are discarded.
1255 /// use itertools::Itertools;
1257 /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1258 /// itertools::assert_equal(data.into_iter().duplicates(),
1261 #[cfg(feature = "use_std")]
1262 fn duplicates(self) -> Duplicates
<Self>
1264 Self::Item
: Eq
+ Hash
1266 duplicates_impl
::duplicates(self)
1269 /// Return an iterator adaptor that produces elements that appear more than once during the
1270 /// iteration. Duplicates are detected using hash and equality.
1272 /// Duplicates are detected by comparing the key they map to with the keying function `f` by
1273 /// hash and equality. The keys are stored in a hash map in the iterator.
1275 /// The iterator is stable, returning the duplicate items in the order in which they occur in
1276 /// the adapted iterator. Each duplicate item is returned exactly once. If an item appears more
1277 /// than twice, the second item is the item retained and the rest are discarded.
1280 /// use itertools::Itertools;
1282 /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1283 /// itertools::assert_equal(data.into_iter().duplicates_by(|s| s.len()),
1284 /// vec!["aa", "c"]);
1286 #[cfg(feature = "use_std")]
1287 fn duplicates_by
<V
, F
>(self, f
: F
) -> DuplicatesBy
<Self, V
, F
>
1290 F
: FnMut(&Self::Item
) -> V
1292 duplicates_impl
::duplicates_by(self, f
)
1295 /// Return an iterator adaptor that filters out elements that have
1296 /// already been produced once during the iteration. Duplicates
1297 /// are detected using hash and equality.
1299 /// Clones of visited elements are stored in a hash set in the
1302 /// The iterator is stable, returning the non-duplicate items in the order
1303 /// in which they occur in the adapted iterator. In a set of duplicate
1304 /// items, the first item encountered is the item retained.
1307 /// use itertools::Itertools;
1309 /// let data = vec![10, 20, 30, 20, 40, 10, 50];
1310 /// itertools::assert_equal(data.into_iter().unique(),
1311 /// vec![10, 20, 30, 40, 50]);
1313 #[cfg(feature = "use_std")]
1314 fn unique(self) -> Unique
<Self>
1316 Self::Item
: Clone
+ Eq
+ Hash
1318 unique_impl
::unique(self)
1321 /// Return an iterator adaptor that filters out elements that have
1322 /// already been produced once during the iteration.
1324 /// Duplicates are detected by comparing the key they map to
1325 /// with the keying function `f` by hash and equality.
1326 /// The keys are stored in a hash set in the iterator.
1328 /// The iterator is stable, returning the non-duplicate items in the order
1329 /// in which they occur in the adapted iterator. In a set of duplicate
1330 /// items, the first item encountered is the item retained.
1333 /// use itertools::Itertools;
1335 /// let data = vec!["a", "bb", "aa", "c", "ccc"];
1336 /// itertools::assert_equal(data.into_iter().unique_by(|s| s.len()),
1337 /// vec!["a", "bb", "ccc"]);
1339 #[cfg(feature = "use_std")]
1340 fn unique_by
<V
, F
>(self, f
: F
) -> UniqueBy
<Self, V
, F
>
1343 F
: FnMut(&Self::Item
) -> V
1345 unique_impl
::unique_by(self, f
)
1348 /// Return an iterator adaptor that borrows from this iterator and
1349 /// takes items while the closure `accept` returns `true`.
1351 /// This adaptor can only be used on iterators that implement `PeekingNext`
1352 /// like `.peekable()`, `put_back` and a few other collection iterators.
1354 /// The last and rejected element (first `false`) is still available when
1355 /// `peeking_take_while` is done.
1358 /// See also [`.take_while_ref()`](Itertools::take_while_ref)
1359 /// which is a similar adaptor.
1360 fn peeking_take_while
<F
>(&mut self, accept
: F
) -> PeekingTakeWhile
<Self, F
>
1361 where Self: Sized
+ PeekingNext
,
1362 F
: FnMut(&Self::Item
) -> bool
,
1364 peeking_take_while
::peeking_take_while(self, accept
)
1367 /// Return an iterator adaptor that borrows from a `Clone`-able iterator
1368 /// to only pick off elements while the predicate `accept` returns `true`.
1370 /// It uses the `Clone` trait to restore the original iterator so that the
1371 /// last and rejected element (first `false`) is still available when
1372 /// `take_while_ref` is done.
1375 /// use itertools::Itertools;
1377 /// let mut hexadecimals = "0123456789abcdef".chars();
1379 /// let decimals = hexadecimals.take_while_ref(|c| c.is_numeric())
1380 /// .collect::<String>();
1381 /// assert_eq!(decimals, "0123456789");
1382 /// assert_eq!(hexadecimals.next(), Some('a'));
1385 fn take_while_ref
<F
>(&mut self, accept
: F
) -> TakeWhileRef
<Self, F
>
1387 F
: FnMut(&Self::Item
) -> bool
1389 adaptors
::take_while_ref(self, accept
)
1392 /// Return an iterator adaptor that filters `Option<A>` iterator elements
1393 /// and produces `A`. Stops on the first `None` encountered.
1395 /// Iterator element type is `A`, the unwrapped element.
1398 /// use itertools::Itertools;
1400 /// // List all hexadecimal digits
1401 /// itertools::assert_equal(
1402 /// (0..).map(|i| std::char::from_digit(i, 16)).while_some(),
1403 /// "0123456789abcdef".chars());
1406 fn while_some
<A
>(self) -> WhileSome
<Self>
1407 where Self: Sized
+ Iterator
<Item
= Option
<A
>>
1409 adaptors
::while_some(self)
1412 /// Return an iterator adaptor that iterates over the combinations of the
1413 /// elements from an iterator.
1415 /// Iterator element can be any homogeneous tuple of type `Self::Item` with
1419 /// use itertools::Itertools;
1421 /// let mut v = Vec::new();
1422 /// for (a, b) in (1..5).tuple_combinations() {
1425 /// assert_eq!(v, vec![(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]);
1427 /// let mut it = (1..5).tuple_combinations();
1428 /// assert_eq!(Some((1, 2, 3)), it.next());
1429 /// assert_eq!(Some((1, 2, 4)), it.next());
1430 /// assert_eq!(Some((1, 3, 4)), it.next());
1431 /// assert_eq!(Some((2, 3, 4)), it.next());
1432 /// assert_eq!(None, it.next());
1434 /// // this requires a type hint
1435 /// let it = (1..5).tuple_combinations::<(_, _, _)>();
1436 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1438 /// // you can also specify the complete type
1439 /// use itertools::TupleCombinations;
1440 /// use std::ops::Range;
1442 /// let it: TupleCombinations<Range<u32>, (u32, u32, u32)> = (1..5).tuple_combinations();
1443 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1445 fn tuple_combinations
<T
>(self) -> TupleCombinations
<Self, T
>
1446 where Self: Sized
+ Clone
,
1448 T
: adaptors
::HasCombination
<Self>,
1450 adaptors
::tuple_combinations(self)
1453 /// Return an iterator adaptor that iterates over the `k`-length combinations of
1454 /// the elements from an iterator.
1456 /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1457 /// and clones the iterator elements.
1460 /// use itertools::Itertools;
1462 /// let it = (1..5).combinations(3);
1463 /// itertools::assert_equal(it, vec![
1471 /// Note: Combinations does not take into account the equality of the iterated values.
1473 /// use itertools::Itertools;
1475 /// let it = vec![1, 2, 2].into_iter().combinations(2);
1476 /// itertools::assert_equal(it, vec![
1477 /// vec![1, 2], // Note: these are the same
1478 /// vec![1, 2], // Note: these are the same
1482 #[cfg(feature = "use_alloc")]
1483 fn combinations(self, k
: usize) -> Combinations
<Self>
1487 combinations
::combinations(self, k
)
1490 /// Return an iterator that iterates over the `k`-length combinations of
1491 /// the elements from an iterator, with replacement.
1493 /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1494 /// and clones the iterator elements.
1497 /// use itertools::Itertools;
1499 /// let it = (1..4).combinations_with_replacement(2);
1500 /// itertools::assert_equal(it, vec![
1509 #[cfg(feature = "use_alloc")]
1510 fn combinations_with_replacement(self, k
: usize) -> CombinationsWithReplacement
<Self>
1515 combinations_with_replacement
::combinations_with_replacement(self, k
)
1518 /// Return an iterator adaptor that iterates over all k-permutations of the
1519 /// elements from an iterator.
1521 /// Iterator element type is `Vec<Self::Item>` with length `k`. The iterator
1522 /// produces a new Vec per iteration, and clones the iterator elements.
1524 /// If `k` is greater than the length of the input iterator, the resultant
1525 /// iterator adaptor will be empty.
1528 /// use itertools::Itertools;
1530 /// let perms = (5..8).permutations(2);
1531 /// itertools::assert_equal(perms, vec![
1541 /// Note: Permutations does not take into account the equality of the iterated values.
1544 /// use itertools::Itertools;
1546 /// let it = vec![2, 2].into_iter().permutations(2);
1547 /// itertools::assert_equal(it, vec![
1548 /// vec![2, 2], // Note: these are the same
1549 /// vec![2, 2], // Note: these are the same
1553 /// Note: The source iterator is collected lazily, and will not be
1554 /// re-iterated if the permutations adaptor is completed and re-iterated.
1555 #[cfg(feature = "use_alloc")]
1556 fn permutations(self, k
: usize) -> Permutations
<Self>
1560 permutations
::permutations(self, k
)
1563 /// Return an iterator that iterates through the powerset of the elements from an
1566 /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new `Vec`
1567 /// per iteration, and clones the iterator elements.
1569 /// The powerset of a set contains all subsets including the empty set and the full
1570 /// input set. A powerset has length _2^n_ where _n_ is the length of the input
1573 /// Each `Vec` produced by this iterator represents a subset of the elements
1574 /// produced by the source iterator.
1577 /// use itertools::Itertools;
1579 /// let sets = (1..4).powerset().collect::<Vec<_>>();
1580 /// itertools::assert_equal(sets, vec![
1591 #[cfg(feature = "use_alloc")]
1592 fn powerset(self) -> Powerset
<Self>
1596 powerset
::powerset(self)
1599 /// Return an iterator adaptor that pads the sequence to a minimum length of
1600 /// `min` by filling missing elements using a closure `f`.
1602 /// Iterator element type is `Self::Item`.
1605 /// use itertools::Itertools;
1607 /// let it = (0..5).pad_using(10, |i| 2*i);
1608 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 10, 12, 14, 16, 18]);
1610 /// let it = (0..10).pad_using(5, |i| 2*i);
1611 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1613 /// let it = (0..5).pad_using(10, |i| 2*i).rev();
1614 /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]);
1616 fn pad_using
<F
>(self, min
: usize, f
: F
) -> PadUsing
<Self, F
>
1618 F
: FnMut(usize) -> Self::Item
1620 pad_tail
::pad_using(self, min
, f
)
1623 /// Return an iterator adaptor that wraps each element in a `Position` to
1624 /// ease special-case handling of the first or last elements.
1626 /// Iterator element type is
1627 /// [`Position<Self::Item>`](Position)
1630 /// use itertools::{Itertools, Position};
1632 /// let it = (0..4).with_position();
1633 /// itertools::assert_equal(it,
1634 /// vec![Position::First(0),
1635 /// Position::Middle(1),
1636 /// Position::Middle(2),
1637 /// Position::Last(3)]);
1639 /// let it = (0..1).with_position();
1640 /// itertools::assert_equal(it, vec![Position::Only(0)]);
1642 fn with_position(self) -> WithPosition
<Self>
1645 with_position
::with_position(self)
1648 /// Return an iterator adaptor that yields the indices of all elements
1649 /// satisfying a predicate, counted from the start of the iterator.
1651 /// Equivalent to `iter.enumerate().filter(|(_, v)| predicate(v)).map(|(i, _)| i)`.
1654 /// use itertools::Itertools;
1656 /// let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
1657 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 0), vec![1, 4, 5]);
1659 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]);
1661 fn positions
<P
>(self, predicate
: P
) -> Positions
<Self, P
>
1663 P
: FnMut(Self::Item
) -> bool
,
1665 adaptors
::positions(self, predicate
)
1668 /// Return an iterator adaptor that applies a mutating function
1669 /// to each element before yielding it.
1672 /// use itertools::Itertools;
1674 /// let input = vec![vec![1], vec![3, 2, 1]];
1675 /// let it = input.into_iter().update(|mut v| v.push(0));
1676 /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]);
1678 fn update
<F
>(self, updater
: F
) -> Update
<Self, F
>
1680 F
: FnMut(&mut Self::Item
),
1682 adaptors
::update(self, updater
)
1685 // non-adaptor methods
1686 /// Advances the iterator and returns the next items grouped in a tuple of
1687 /// a specific size (up to 12).
1689 /// If there are enough elements to be grouped in a tuple, then the tuple is
1690 /// returned inside `Some`, otherwise `None` is returned.
1693 /// use itertools::Itertools;
1695 /// let mut iter = 1..5;
1697 /// assert_eq!(Some((1, 2)), iter.next_tuple());
1699 fn next_tuple
<T
>(&mut self) -> Option
<T
>
1700 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
1701 T
: traits
::HomogeneousTuple
1703 T
::collect_from_iter_no_buf(self)
1706 /// Collects all items from the iterator into a tuple of a specific size
1709 /// If the number of elements inside the iterator is **exactly** equal to
1710 /// the tuple size, then the tuple is returned inside `Some`, otherwise
1711 /// `None` is returned.
1714 /// use itertools::Itertools;
1716 /// let iter = 1..3;
1718 /// if let Some((x, y)) = iter.collect_tuple() {
1719 /// assert_eq!((x, y), (1, 2))
1721 /// panic!("Expected two elements")
1724 fn collect_tuple
<T
>(mut self) -> Option
<T
>
1725 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
1726 T
: traits
::HomogeneousTuple
1728 match self.next_tuple() {
1729 elt @
Some(_
) => match self.next() {
1738 /// Find the position and value of the first element satisfying a predicate.
1740 /// The iterator is not advanced past the first element found.
1743 /// use itertools::Itertools;
1745 /// let text = "Hα";
1746 /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α')));
1748 fn find_position
<P
>(&mut self, mut pred
: P
) -> Option
<(usize, Self::Item
)>
1749 where P
: FnMut(&Self::Item
) -> bool
1751 for (index
, elt
) in self.enumerate() {
1753 return Some((index
, elt
));
1758 /// Find the value of the first element satisfying a predicate or return the last element, if any.
1760 /// The iterator is not advanced past the first element found.
1763 /// use itertools::Itertools;
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);
1770 fn find_or_last
<P
>(mut self, mut predicate
: P
) -> Option
<Self::Item
>
1772 P
: FnMut(&Self::Item
) -> bool
,
1774 let mut prev
= None
;
1775 self.find_map(|x
| if predicate(&x
) { Some(x) }
else { prev = Some(x); None }
)
1778 /// Find the value of the first element satisfying a predicate or return the first element, if any.
1780 /// The iterator is not advanced past the first element found.
1783 /// use itertools::Itertools;
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);
1790 fn find_or_first
<P
>(mut self, mut predicate
: P
) -> Option
<Self::Item
>
1792 P
: FnMut(&Self::Item
) -> bool
,
1794 let first
= self.next()?
;
1795 Some(if predicate(&first
) {
1798 self.find(|x
| predicate(x
)).unwrap_or(first
)
1801 /// Returns `true` if the given item is present in this iterator.
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.
1809 /// use itertools::Itertools;
1811 /// #[derive(PartialEq, Debug)]
1812 /// enum Enum { A, B, C, D, E, }
1814 /// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter();
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));
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);
1826 fn contains
<Q
>(&mut self, query
: &Q
) -> bool
1829 Self::Item
: Borrow
<Q
>,
1832 self.any(|x
| x
.borrow() == query
)
1835 /// Check whether all elements compare equal.
1837 /// Empty iterators are considered to have equal elements:
1840 /// use itertools::Itertools;
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());
1848 /// let data : Option<usize> = None;
1849 /// assert!(data.into_iter().all_equal());
1851 fn all_equal(&mut self) -> bool
1853 Self::Item
: PartialEq
,
1857 Some(a
) => self.all(|x
| a
== x
),
1861 /// Check whether all elements are unique (non equal).
1863 /// Empty iterators are considered to have unique elements:
1866 /// use itertools::Itertools;
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());
1873 /// let data : Option<usize> = None;
1874 /// assert!(data.into_iter().all_unique());
1876 #[cfg(feature = "use_std")]
1877 fn all_unique(&mut self) -> bool
1879 Self::Item
: Eq
+ Hash
1881 let mut used
= HashSet
::new();
1882 self.all(move |elt
| used
.insert(elt
))
1885 /// Consume the first `n` elements from the iterator eagerly,
1886 /// and return the same iterator again.
1888 /// It works similarly to *.skip(* `n` *)* except it is eager and
1889 /// preserves the iterator type.
1892 /// use itertools::Itertools;
1894 /// let mut iter = "αβγ".chars().dropping(2);
1895 /// itertools::assert_equal(iter, "γ".chars());
1898 /// *Fusing notes: if the iterator is exhausted by dropping,
1899 /// the result of calling `.next()` again depends on the iterator implementation.*
1900 fn dropping(mut self, n
: usize) -> Self
1909 /// Consume the last `n` elements from the iterator eagerly,
1910 /// and return the same iterator again.
1912 /// This is only possible on double ended iterators. `n` may be
1913 /// larger than the number of elements.
1915 /// Note: This method is eager, dropping the back elements immediately and
1916 /// preserves the iterator type.
1919 /// use itertools::Itertools;
1921 /// let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
1922 /// itertools::assert_equal(init, vec![0, 3, 6]);
1924 fn dropping_back(mut self, n
: usize) -> Self
1926 Self: DoubleEndedIterator
1929 (&mut self).rev().nth(n
- 1);
1934 /// Run the closure `f` eagerly on each element of the iterator.
1936 /// Consumes the iterator until its end.
1939 /// use std::sync::mpsc::channel;
1940 /// use itertools::Itertools;
1942 /// let (tx, rx) = channel();
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(); } );
1949 /// itertools::assert_equal(rx.iter(), vec![1, 3, 5, 7, 9]);
1951 #[deprecated(note="Use .for_each() instead", since="0.8.0")]
1952 fn foreach
<F
>(self, f
: F
)
1953 where F
: FnMut(Self::Item
),
1959 /// Combine all an iterator's elements into one element by using [`Extend`].
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.
1966 /// use itertools::Itertools;
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]);
1972 fn concat(self) -> Self::Item
1974 Self::Item
: Extend
<<<Self as Iterator
>::Item
as IntoIterator
>::Item
> + IntoIterator
+ Default
1979 /// `.collect_vec()` is simply a type specialization of [`Iterator::collect`],
1980 /// for convenience.
1981 #[cfg(feature = "use_alloc")]
1982 fn collect_vec(self) -> Vec
<Self::Item
>
1988 /// `.try_collect()` is more convenient way of writing
1989 /// `.collect::<Result<_, _>>()`
1994 /// use std::{fs, io};
1995 /// use itertools::Itertools;
1997 /// fn process_dir_entries(entries: &[fs::DirEntry]) {
2001 /// fn do_stuff() -> std::io::Result<()> {
2002 /// let entries: Vec<_> = fs::read_dir(".")?.try_collect()?;
2003 /// process_dir_entries(&entries);
2008 #[cfg(feature = "use_alloc")]
2009 fn try_collect
<T
, U
, E
>(self) -> Result
<U
, E
>
2011 Self: Sized
+ Iterator
<Item
= Result
<T
, E
>>,
2012 Result
<U
, E
>: FromIterator
<Result
<T
, E
>>,
2017 /// Assign to each reference in `self` from the `from` iterator,
2018 /// stopping at the shortest of the two iterators.
2020 /// The `from` iterator is queried for its next element before the `self`
2021 /// iterator, and if either is exhausted the method is done.
2023 /// Return the number of elements written.
2026 /// use itertools::Itertools;
2028 /// let mut xs = [0; 4];
2029 /// xs.iter_mut().set_from(1..);
2030 /// assert_eq!(xs, [1, 2, 3, 4]);
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
>
2041 Some(ptr
) => *ptr
= elt
,
2048 /// Combine all iterator elements into one String, separated by `sep`.
2050 /// Use the `Display` implementation of each element.
2053 /// use itertools::Itertools;
2055 /// assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
2056 /// assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");
2058 #[cfg(feature = "use_alloc")]
2059 fn join(&mut self, sep
: &str) -> String
2060 where Self::Item
: std
::fmt
::Display
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();
2078 /// Format all iterator elements, separated by `sep`.
2080 /// All elements are formatted (any formatting trait)
2081 /// with `sep` inserted between each element.
2083 /// **Panics** if the formatter helper is formatted more than once.
2086 /// use itertools::Itertools;
2088 /// let data = [1.1, 2.71828, -3.];
2090 /// format!("{:.2}", data.iter().format(", ")),
2091 /// "1.10, 2.72, -3.00");
2093 fn format(self, sep
: &str) -> Format
<Self>
2096 format
::new_format_default(self, sep
)
2099 /// Format all iterator elements, separated by `sep`.
2101 /// This is a customizable version of [`.format()`](Itertools::format).
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`.
2107 /// Using `&format_args!(...)` is the most versatile way to apply custom
2108 /// element formatting. The callback can be called multiple times if needed.
2110 /// **Panics** if the formatter helper is formatted more than once.
2113 /// use itertools::Itertools;
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");
2120 /// // .format_with() is recursively composable
2121 /// let matrix = [[1., 2., 3.],
2123 /// let matrix_formatter = matrix.iter().format_with("\n", |row, f| {
2124 /// f(&row.iter().format_with(", ", |elt, g| g(&elt)))
2126 /// assert_eq!(format!("{}", matrix_formatter),
2127 /// "1, 2, 3\n4, 5, 6");
2131 fn format_with
<F
>(self, sep
: &str, format
: F
) -> FormatWith
<Self, F
>
2133 F
: FnMut(Self::Item
, &mut dyn FnMut(&dyn fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
,
2135 format
::new_format(self, sep
, format
)
2138 /// See [`.fold_ok()`](Itertools::fold_ok).
2139 #[deprecated(note="Use .fold_ok() instead", since="0.10.0")]
2140 fn fold_results
<A
, E
, B
, F
>(&mut self, start
: B
, f
: F
) -> Result
<B
, E
>
2141 where Self: Iterator
<Item
= Result
<A
, E
>>,
2144 self.fold_ok(start
, f
)
2147 /// Fold `Result` values from an iterator.
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.
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.
2158 /// For example the sequence *Ok(1), Ok(2), Ok(3)* will result in a
2159 /// computation like this:
2162 /// let mut accum = start;
2163 /// accum = f(accum, 1);
2164 /// accum = f(accum, 2);
2165 /// accum = f(accum, 3);
2168 /// With a `start` value of 0 and an addition as folding function,
2169 /// this effectively results in *((0 + 1) + 2) + 3*
2172 /// use std::ops::Add;
2173 /// use itertools::Itertools;
2175 /// let values = [1, 2, -2, -1, 2, 1];
2178 /// .map(Ok::<_, ()>)
2179 /// .fold_ok(0, Add::add),
2184 /// .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
2185 /// .fold_ok(0, Add::add)
2189 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
>>,
2195 Ok(v
) => start
= f(start
, v
),
2196 Err(u
) => return Err(u
),
2202 /// Fold `Option` values from an iterator.
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`.
2208 /// This is the `Option` equivalent to [`fold_ok`](Itertools::fold_ok).
2211 /// use std::ops::Add;
2212 /// use itertools::Itertools;
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));
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));
2221 fn fold_options
<A
, B
, F
>(&mut self, mut start
: B
, mut f
: F
) -> Option
<B
>
2222 where Self: Iterator
<Item
= Option
<A
>>,
2227 Some(v
) => start
= f(start
, v
),
2228 None
=> return None
,
2234 /// Accumulator of the elements in the iterator.
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`.
2241 /// use itertools::Itertools;
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);
2246 #[deprecated(since = "0.10.2", note = "Use `Iterator::reduce` instead")]
2247 fn fold1
<F
>(mut self, f
: F
) -> Option
<Self::Item
>
2248 where F
: FnMut(Self::Item
, Self::Item
) -> Self::Item
,
2251 self.next().map(move |x
| self.fold(x
, f
))
2254 /// Accumulate the elements in the iterator in a tree-like manner.
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.
2260 /// This produces a call tree like the following (where the calls under
2261 /// an item are done after reading that item):
2273 /// Which, for non-associative functions, will typically produce a different
2274 /// result than the linear call tree used by [`Iterator::reduce`]:
2282 /// If `f` is associative, prefer the normal [`Iterator::reduce`] instead.
2285 /// use itertools::Itertools;
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))")));
2292 /// // Like fold1, an empty iterator produces None
2293 /// assert_eq!((0..0).tree_fold1(|x, y| x * y), None);
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));
2302 fn tree_fold1
<F
>(mut self, mut f
: F
) -> Option
<Self::Item
>
2303 where F
: FnMut(Self::Item
, Self::Item
) -> Self::Item
,
2306 type State
<T
> = Result
<T
, Option
<T
>>;
2308 fn inner0
<T
, II
, FF
>(it
: &mut II
, f
: &mut FF
) -> State
<T
>
2310 II
: Iterator
<Item
= T
>,
2311 FF
: FnMut(T
, T
) -> T
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.
2318 if let Some(v
) = it
.next() { v }
2319 else { return Err(None) }
;
2321 if let Some(v
) = it
.next() { v }
2322 else { return Err(Some(a)) }
;
2326 fn inner
<T
, II
, FF
>(stop
: usize, it
: &mut II
, f
: &mut FF
) -> State
<T
>
2328 II
: Iterator
<Item
= T
>,
2329 FF
: FnMut(T
, T
) -> T
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.
2339 inner(height
, it
, f
)
2342 Ok(y
) => x
= f(x
, y
),
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
))),
2355 match inner(usize::max_value(), &mut self, &mut f
) {
2357 _
=> unreachable
!(),
2361 /// An iterator method that applies a function, producing a single, final value.
2363 /// `fold_while()` is basically equivalent to [`Iterator::fold`] but with additional support for
2364 /// early exit via short-circuiting.
2367 /// use itertools::Itertools;
2368 /// use itertools::FoldWhile::{Continue, Done};
2370 /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2372 /// let mut result = 0;
2375 /// for i in &numbers {
2379 /// result = result + i;
2383 /// let result2 = numbers.iter().fold(0, |acc, x| {
2384 /// if *x > 5 { acc } else { acc + x }
2388 /// let result3 = numbers.iter().fold_while(0, |acc, x| {
2389 /// if *x > 5 { Done(acc) } else { Continue(acc + x) }
2390 /// }).into_inner();
2392 /// // they're the same
2393 /// assert_eq!(result, result2);
2394 /// assert_eq!(result2, result3);
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(_)`.
2400 fn fold_while
<B
, F
>(&mut self, init
: B
, mut f
: F
) -> FoldWhile
<B
>
2402 F
: FnMut(B
, Self::Item
) -> FoldWhile
<B
>
2409 let result
= self.try_fold(init
, #[inline(always)] |acc, v|
2411 FoldWhile
::Continue(acc
) => Continue(acc
),
2412 FoldWhile
::Done(acc
) => Break(acc
),
2417 Continue(acc
) => FoldWhile
::Continue(acc
),
2418 Break(acc
) => FoldWhile
::Done(acc
),
2422 /// Iterate over the entire iterator and add all the elements.
2424 /// An empty iterator returns `None`, otherwise `Some(sum)`.
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
2435 /// use itertools::Itertools;
2437 /// let empty_sum = (1..1).sum1::<i32>();
2438 /// assert_eq!(empty_sum, None);
2440 /// let nonempty_sum = (1..11).sum1::<i32>();
2441 /// assert_eq!(nonempty_sum, Some(55));
2443 fn sum1
<S
>(mut self) -> Option
<S
>
2445 S
: std
::iter
::Sum
<Self::Item
>,
2448 .map(|first
| once(first
).chain(self).sum())
2451 /// Iterate over the entire iterator and multiply all the elements.
2453 /// An empty iterator returns `None`, otherwise `Some(product)`.
2457 /// When calling `product1()` and a primitive integer type is being returned,
2458 /// method will panic if the computation overflows and debug assertions are
2463 /// use itertools::Itertools;
2465 /// let empty_product = (1..1).product1::<i32>();
2466 /// assert_eq!(empty_product, None);
2468 /// let nonempty_product = (1..11).product1::<i32>();
2469 /// assert_eq!(nonempty_product, Some(3628800));
2471 fn product1
<P
>(mut self) -> Option
<P
>
2473 P
: std
::iter
::Product
<Self::Item
>,
2476 .map(|first
| once(first
).chain(self).product())
2479 /// Sort all iterator elements into a new iterator in ascending order.
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.
2485 /// The sorted iterator, if directly collected to a `Vec`, is converted
2486 /// without any extra copying or allocation cost.
2489 /// use itertools::Itertools;
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());
2496 #[cfg(feature = "use_alloc")]
2497 fn sorted_unstable(self) -> VecIntoIter
<Self::Item
>
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);
2508 /// Sort all iterator elements into a new iterator in ascending order.
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.
2514 /// The sorted iterator, if directly collected to a `Vec`, is converted
2515 /// without any extra copying or allocation cost.
2518 /// use itertools::Itertools;
2520 /// // sort people in descending order by age
2521 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2523 /// let oldest_people_first = people
2525 /// .sorted_unstable_by(|a, b| Ord::cmp(&b.1, &a.1))
2526 /// .map(|(person, _age)| person);
2528 /// itertools::assert_equal(oldest_people_first,
2529 /// vec!["Jill", "Jack", "Jane", "John"]);
2531 #[cfg(feature = "use_alloc")]
2532 fn sorted_unstable_by
<F
>(self, cmp
: F
) -> VecIntoIter
<Self::Item
>
2534 F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2536 let mut v
= Vec
::from_iter(self);
2537 v
.sort_unstable_by(cmp
);
2541 /// Sort all iterator elements into a new iterator in ascending order.
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.
2547 /// The sorted iterator, if directly collected to a `Vec`, is converted
2548 /// without any extra copying or allocation cost.
2551 /// use itertools::Itertools;
2553 /// // sort people in descending order by age
2554 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2556 /// let oldest_people_first = people
2558 /// .sorted_unstable_by_key(|x| -x.1)
2559 /// .map(|(person, _age)| person);
2561 /// itertools::assert_equal(oldest_people_first,
2562 /// vec!["Jill", "Jack", "Jane", "John"]);
2564 #[cfg(feature = "use_alloc")]
2565 fn sorted_unstable_by_key
<K
, F
>(self, f
: F
) -> VecIntoIter
<Self::Item
>
2568 F
: FnMut(&Self::Item
) -> K
,
2570 let mut v
= Vec
::from_iter(self);
2571 v
.sort_unstable_by_key(f
);
2575 /// Sort all iterator elements into a new iterator in ascending order.
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.
2581 /// The sorted iterator, if directly collected to a `Vec`, is converted
2582 /// without any extra copying or allocation cost.
2585 /// use itertools::Itertools;
2587 /// // sort the letters of the text in ascending order
2588 /// let text = "bdacfe";
2589 /// itertools::assert_equal(text.chars().sorted(),
2590 /// "abcdef".chars());
2592 #[cfg(feature = "use_alloc")]
2593 fn sorted(self) -> VecIntoIter
<Self::Item
>
2597 // Use .sort() directly since it is not quite identical with
2598 // .sort_by(Ord::cmp)
2599 let mut v
= Vec
::from_iter(self);
2604 /// Sort all iterator elements into a new iterator in ascending order.
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.
2610 /// The sorted iterator, if directly collected to a `Vec`, is converted
2611 /// without any extra copying or allocation cost.
2614 /// use itertools::Itertools;
2616 /// // sort people in descending order by age
2617 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2619 /// let oldest_people_first = people
2621 /// .sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
2622 /// .map(|(person, _age)| person);
2624 /// itertools::assert_equal(oldest_people_first,
2625 /// vec!["Jill", "Jack", "Jane", "John"]);
2627 #[cfg(feature = "use_alloc")]
2628 fn sorted_by
<F
>(self, cmp
: F
) -> VecIntoIter
<Self::Item
>
2630 F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2632 let mut v
= Vec
::from_iter(self);
2637 /// Sort all iterator elements into a new iterator in ascending order.
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.
2643 /// The sorted iterator, if directly collected to a `Vec`, is converted
2644 /// without any extra copying or allocation cost.
2647 /// use itertools::Itertools;
2649 /// // sort people in descending order by age
2650 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2652 /// let oldest_people_first = people
2654 /// .sorted_by_key(|x| -x.1)
2655 /// .map(|(person, _age)| person);
2657 /// itertools::assert_equal(oldest_people_first,
2658 /// vec!["Jill", "Jack", "Jane", "John"]);
2660 #[cfg(feature = "use_alloc")]
2661 fn sorted_by_key
<K
, F
>(self, f
: F
) -> VecIntoIter
<Self::Item
>
2664 F
: FnMut(&Self::Item
) -> K
,
2666 let mut v
= Vec
::from_iter(self);
2671 /// Sort all iterator elements into a new iterator in ascending order. The key function is
2672 /// called exactly once per key.
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.
2678 /// The sorted iterator, if directly collected to a `Vec`, is converted
2679 /// without any extra copying or allocation cost.
2682 /// use itertools::Itertools;
2684 /// // sort people in descending order by age
2685 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
2687 /// let oldest_people_first = people
2689 /// .sorted_by_cached_key(|x| -x.1)
2690 /// .map(|(person, _age)| person);
2692 /// itertools::assert_equal(oldest_people_first,
2693 /// vec!["Jill", "Jack", "Jane", "John"]);
2695 #[cfg(feature = "use_alloc")]
2696 fn sorted_by_cached_key
<K
, F
>(self, f
: F
) -> VecIntoIter
<Self::Item
>
2700 F
: FnMut(&Self::Item
) -> K
,
2702 let mut v
= Vec
::from_iter(self);
2703 v
.sort_by_cached_key(f
);
2707 /// Sort the k smallest elements into a new iterator, in ascending order.
2709 /// **Note:** This consumes the entire iterator, and returns the result
2710 /// as a new iterator that owns its elements. If the input contains
2711 /// less than k elements, the result is equivalent to `self.sorted()`.
2713 /// This is guaranteed to use `k * sizeof(Self::Item) + O(1)` memory
2714 /// and `O(n log k)` time, with `n` the number of elements in the input.
2716 /// The sorted iterator, if directly collected to a `Vec`, is converted
2717 /// without any extra copying or allocation cost.
2719 /// **Note:** This is functionally-equivalent to `self.sorted().take(k)`
2720 /// but much more efficient.
2723 /// use itertools::Itertools;
2725 /// // A random permutation of 0..15
2726 /// let numbers = vec![6, 9, 1, 14, 0, 4, 8, 7, 11, 2, 10, 3, 13, 12, 5];
2728 /// let five_smallest = numbers
2732 /// itertools::assert_equal(five_smallest, 0..5);
2734 #[cfg(feature = "use_alloc")]
2735 fn k_smallest(self, k
: usize) -> VecIntoIter
<Self::Item
>
2739 crate::k_smallest
::k_smallest(self, k
)
2744 /// Collect all iterator elements into one of two
2745 /// partitions. Unlike [`Iterator::partition`], each partition may
2746 /// have a distinct type.
2749 /// use itertools::{Itertools, Either};
2751 /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
2753 /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
2755 /// .partition_map(|r| {
2757 /// Ok(v) => Either::Left(v),
2758 /// Err(v) => Either::Right(v),
2762 /// assert_eq!(successes, [1, 2]);
2763 /// assert_eq!(failures, [false, true]);
2765 fn partition_map
<A
, B
, F
, L
, R
>(self, mut predicate
: F
) -> (A
, B
)
2767 F
: FnMut(Self::Item
) -> Either
<L
, R
>,
2768 A
: Default
+ Extend
<L
>,
2769 B
: Default
+ Extend
<R
>,
2771 let mut left
= A
::default();
2772 let mut right
= B
::default();
2774 self.for_each(|val
| match predicate(val
) {
2775 Either
::Left(v
) => left
.extend(Some(v
)),
2776 Either
::Right(v
) => right
.extend(Some(v
)),
2782 /// Partition a sequence of `Result`s into one list of all the `Ok` elements
2783 /// and another list of all the `Err` elements.
2786 /// use itertools::Itertools;
2788 /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
2790 /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
2792 /// .partition_result();
2794 /// assert_eq!(successes, [1, 2]);
2795 /// assert_eq!(failures, [false, true]);
2797 fn partition_result
<A
, B
, T
, E
>(self) -> (A
, B
)
2799 Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
2800 A
: Default
+ Extend
<T
>,
2801 B
: Default
+ Extend
<E
>,
2803 self.partition_map(|r
| match r
{
2804 Ok(v
) => Either
::Left(v
),
2805 Err(v
) => Either
::Right(v
),
2809 /// Return a `HashMap` of keys mapped to `Vec`s of values. Keys and values
2810 /// are taken from `(Key, Value)` tuple pairs yielded by the input iterator.
2812 /// Essentially a shorthand for `.into_grouping_map().collect::<Vec<_>>()`.
2815 /// use itertools::Itertools;
2817 /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
2818 /// let lookup = data.into_iter().into_group_map();
2820 /// assert_eq!(lookup[&0], vec![10, 20]);
2821 /// assert_eq!(lookup.get(&1), None);
2822 /// assert_eq!(lookup[&2], vec![12, 42]);
2823 /// assert_eq!(lookup[&3], vec![13, 33]);
2825 #[cfg(feature = "use_std")]
2826 fn into_group_map
<K
, V
>(self) -> HashMap
<K
, Vec
<V
>>
2827 where Self: Iterator
<Item
=(K
, V
)> + Sized
,
2830 group_map
::into_group_map(self)
2833 /// Return an `Iterator` on a `HashMap`. Keys mapped to `Vec`s of values. The key is specified
2836 /// Essentially a shorthand for `.into_grouping_map_by(f).collect::<Vec<_>>()`.
2839 /// use itertools::Itertools;
2840 /// use std::collections::HashMap;
2842 /// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
2843 /// let lookup: HashMap<u32,Vec<(u32, u32)>> =
2844 /// data.clone().into_iter().into_group_map_by(|a| a.0);
2846 /// assert_eq!(lookup[&0], vec![(0,10),(0,20)]);
2847 /// assert_eq!(lookup.get(&1), None);
2848 /// assert_eq!(lookup[&2], vec![(2,12), (2,42)]);
2849 /// assert_eq!(lookup[&3], vec![(3,13), (3,33)]);
2852 /// data.into_iter()
2853 /// .into_group_map_by(|x| x.0)
2855 /// .map(|(key, values)| (key, values.into_iter().fold(0,|acc, (_,v)| acc + v )))
2856 /// .collect::<HashMap<u32,u32>>()[&0],
2860 #[cfg(feature = "use_std")]
2861 fn into_group_map_by
<K
, V
, F
>(self, f
: F
) -> HashMap
<K
, Vec
<V
>>
2863 Self: Iterator
<Item
=V
> + Sized
,
2867 group_map
::into_group_map_by(self, f
)
2870 /// Constructs a `GroupingMap` to be used later with one of the efficient
2871 /// group-and-fold operations it allows to perform.
2873 /// The input iterator must yield item in the form of `(K, V)` where the
2874 /// value of type `K` will be used as key to identify the groups and the
2875 /// value of type `V` as value for the folding operation.
2877 /// See [`GroupingMap`] for more informations
2878 /// on what operations are available.
2879 #[cfg(feature = "use_std")]
2880 fn into_grouping_map
<K
, V
>(self) -> GroupingMap
<Self>
2881 where Self: Iterator
<Item
=(K
, V
)> + Sized
,
2884 grouping_map
::new(self)
2887 /// Constructs a `GroupingMap` to be used later with one of the efficient
2888 /// group-and-fold operations it allows to perform.
2890 /// The values from this iterator will be used as values for the folding operation
2891 /// while the keys will be obtained from the values by calling `key_mapper`.
2893 /// See [`GroupingMap`] for more informations
2894 /// on what operations are available.
2895 #[cfg(feature = "use_std")]
2896 fn into_grouping_map_by
<K
, V
, F
>(self, key_mapper
: F
) -> GroupingMapBy
<Self, F
>
2897 where Self: Iterator
<Item
=V
> + Sized
,
2901 grouping_map
::new(grouping_map
::MapForGrouping
::new(self, key_mapper
))
2904 /// Return all minimum elements of an iterator.
2909 /// use itertools::Itertools;
2911 /// let a: [i32; 0] = [];
2912 /// assert_eq!(a.iter().min_set(), Vec::<&i32>::new());
2915 /// assert_eq!(a.iter().min_set(), vec![&1]);
2917 /// let a = [1, 2, 3, 4, 5];
2918 /// assert_eq!(a.iter().min_set(), vec![&1]);
2920 /// let a = [1, 1, 1, 1];
2921 /// assert_eq!(a.iter().min_set(), vec![&1, &1, &1, &1]);
2924 /// The elements can be floats but no particular result is guaranteed
2925 /// if an element is NaN.
2926 #[cfg(feature = "use_std")]
2927 fn min_set(self) -> Vec
<Self::Item
>
2928 where Self: Sized
, Self::Item
: Ord
2930 extrema_set
::min_set_impl(self, |_
| (), |x
, y
, _
, _
| x
.cmp(y
))
2933 /// Return all minimum elements of an iterator, as determined by
2934 /// the specified function.
2939 /// # use std::cmp::Ordering;
2940 /// use itertools::Itertools;
2942 /// let a: [(i32, i32); 0] = [];
2943 /// assert_eq!(a.iter().min_set_by(|_, _| Ordering::Equal), Vec::<&(i32, i32)>::new());
2945 /// let a = [(1, 2)];
2946 /// assert_eq!(a.iter().min_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2)]);
2948 /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
2949 /// assert_eq!(a.iter().min_set_by(|&&(_,k1), &&(_,k2)| k1.cmp(&k2)), vec![&(1, 2), &(2, 2)]);
2951 /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
2952 /// assert_eq!(a.iter().min_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
2955 /// The elements can be floats but no particular result is guaranteed
2956 /// if an element is NaN.
2957 #[cfg(feature = "use_std")]
2958 fn min_set_by
<F
>(self, mut compare
: F
) -> Vec
<Self::Item
>
2959 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
2961 extrema_set
::min_set_impl(
2964 |x
, y
, _
, _
| compare(x
, y
)
2968 /// Return all minimum elements of an iterator, as determined by
2969 /// the specified function.
2974 /// use itertools::Itertools;
2976 /// let a: [(i32, i32); 0] = [];
2977 /// assert_eq!(a.iter().min_set_by_key(|_| ()), Vec::<&(i32, i32)>::new());
2979 /// let a = [(1, 2)];
2980 /// assert_eq!(a.iter().min_set_by_key(|&&(k,_)| k), vec![&(1, 2)]);
2982 /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
2983 /// assert_eq!(a.iter().min_set_by_key(|&&(_, k)| k), vec![&(1, 2), &(2, 2)]);
2985 /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
2986 /// assert_eq!(a.iter().min_set_by_key(|&&(k, _)| k), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
2989 /// The elements can be floats but no particular result is guaranteed
2990 /// if an element is NaN.
2991 #[cfg(feature = "use_std")]
2992 fn min_set_by_key
<K
, F
>(self, key
: F
) -> Vec
<Self::Item
>
2993 where Self: Sized
, K
: Ord
, F
: FnMut(&Self::Item
) -> K
2995 extrema_set
::min_set_impl(self, key
, |_
, _
, kx
, ky
| kx
.cmp(ky
))
2998 /// Return all maximum elements of an iterator.
3003 /// use itertools::Itertools;
3005 /// let a: [i32; 0] = [];
3006 /// assert_eq!(a.iter().max_set(), Vec::<&i32>::new());
3009 /// assert_eq!(a.iter().max_set(), vec![&1]);
3011 /// let a = [1, 2, 3, 4, 5];
3012 /// assert_eq!(a.iter().max_set(), vec![&5]);
3014 /// let a = [1, 1, 1, 1];
3015 /// assert_eq!(a.iter().max_set(), vec![&1, &1, &1, &1]);
3018 /// The elements can be floats but no particular result is guaranteed
3019 /// if an element is NaN.
3020 #[cfg(feature = "use_std")]
3021 fn max_set(self) -> Vec
<Self::Item
>
3022 where Self: Sized
, Self::Item
: Ord
3024 extrema_set
::max_set_impl(self, |_
| (), |x
, y
, _
, _
| x
.cmp(y
))
3027 /// Return all maximum elements of an iterator, as determined by
3028 /// the specified function.
3033 /// # use std::cmp::Ordering;
3034 /// use itertools::Itertools;
3036 /// let a: [(i32, i32); 0] = [];
3037 /// assert_eq!(a.iter().max_set_by(|_, _| Ordering::Equal), Vec::<&(i32, i32)>::new());
3039 /// let a = [(1, 2)];
3040 /// assert_eq!(a.iter().max_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2)]);
3042 /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3043 /// assert_eq!(a.iter().max_set_by(|&&(_,k1), &&(_,k2)| k1.cmp(&k2)), vec![&(3, 9), &(5, 9)]);
3045 /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3046 /// assert_eq!(a.iter().max_set_by(|&&(k1,_), &&(k2, _)| k1.cmp(&k2)), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3049 /// The elements can be floats but no particular result is guaranteed
3050 /// if an element is NaN.
3051 #[cfg(feature = "use_std")]
3052 fn max_set_by
<F
>(self, mut compare
: F
) -> Vec
<Self::Item
>
3053 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
3055 extrema_set
::max_set_impl(
3058 |x
, y
, _
, _
| compare(x
, y
)
3062 /// Return all minimum elements of an iterator, as determined by
3063 /// the specified function.
3068 /// use itertools::Itertools;
3070 /// let a: [(i32, i32); 0] = [];
3071 /// assert_eq!(a.iter().max_set_by_key(|_| ()), Vec::<&(i32, i32)>::new());
3073 /// let a = [(1, 2)];
3074 /// assert_eq!(a.iter().max_set_by_key(|&&(k,_)| k), vec![&(1, 2)]);
3076 /// let a = [(1, 2), (2, 2), (3, 9), (4, 8), (5, 9)];
3077 /// assert_eq!(a.iter().max_set_by_key(|&&(_, k)| k), vec![&(3, 9), &(5, 9)]);
3079 /// let a = [(1, 2), (1, 3), (1, 4), (1, 5)];
3080 /// assert_eq!(a.iter().max_set_by_key(|&&(k, _)| k), vec![&(1, 2), &(1, 3), &(1, 4), &(1, 5)]);
3083 /// The elements can be floats but no particular result is guaranteed
3084 /// if an element is NaN.
3085 #[cfg(feature = "use_std")]
3086 fn max_set_by_key
<K
, F
>(self, key
: F
) -> Vec
<Self::Item
>
3087 where Self: Sized
, K
: Ord
, F
: FnMut(&Self::Item
) -> K
3089 extrema_set
::max_set_impl(self, key
, |_
, _
, kx
, ky
| kx
.cmp(ky
))
3092 /// Return the minimum and maximum elements in the iterator.
3094 /// The return type `MinMaxResult` is an enum of three variants:
3096 /// - `NoElements` if the iterator is empty.
3097 /// - `OneElement(x)` if the iterator has exactly one element.
3098 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
3099 /// values are equal if and only if there is more than one
3100 /// element in the iterator and all elements are equal.
3102 /// On an iterator of length `n`, `minmax` does `1.5 * n` comparisons,
3103 /// and so is faster than calling `min` and `max` separately which does
3104 /// `2 * n` comparisons.
3109 /// use itertools::Itertools;
3110 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3112 /// let a: [i32; 0] = [];
3113 /// assert_eq!(a.iter().minmax(), NoElements);
3116 /// assert_eq!(a.iter().minmax(), OneElement(&1));
3118 /// let a = [1, 2, 3, 4, 5];
3119 /// assert_eq!(a.iter().minmax(), MinMax(&1, &5));
3121 /// let a = [1, 1, 1, 1];
3122 /// assert_eq!(a.iter().minmax(), MinMax(&1, &1));
3125 /// The elements can be floats but no particular result is guaranteed
3126 /// if an element is NaN.
3127 fn minmax(self) -> MinMaxResult
<Self::Item
>
3128 where Self: Sized
, Self::Item
: PartialOrd
3130 minmax
::minmax_impl(self, |_
| (), |x
, y
, _
, _
| x
< y
)
3133 /// Return the minimum and maximum element of an iterator, as determined by
3134 /// the specified function.
3136 /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
3138 /// For the minimum, the first minimal element is returned. For the maximum,
3139 /// the last maximal element wins. This matches the behavior of the standard
3140 /// [`Iterator::min`] and [`Iterator::max`] methods.
3142 /// The keys can be floats but no particular result is guaranteed
3143 /// if a key is NaN.
3144 fn minmax_by_key
<K
, F
>(self, key
: F
) -> MinMaxResult
<Self::Item
>
3145 where Self: Sized
, K
: PartialOrd
, F
: FnMut(&Self::Item
) -> K
3147 minmax
::minmax_impl(self, key
, |_
, _
, xk
, yk
| xk
< yk
)
3150 /// Return the minimum and maximum element of an iterator, as determined by
3151 /// the specified comparison function.
3153 /// The return value is a variant of [`MinMaxResult`] like for [`.minmax()`](Itertools::minmax).
3155 /// For the minimum, the first minimal element is returned. For the maximum,
3156 /// the last maximal element wins. This matches the behavior of the standard
3157 /// [`Iterator::min`] and [`Iterator::max`] methods.
3158 fn minmax_by
<F
>(self, mut compare
: F
) -> MinMaxResult
<Self::Item
>
3159 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
3161 minmax
::minmax_impl(
3164 |x
, y
, _
, _
| Ordering
::Less
== compare(x
, y
)
3168 /// Return the position of the maximum element in the iterator.
3170 /// If several elements are equally maximum, the position of the
3171 /// last of them is returned.
3176 /// use itertools::Itertools;
3178 /// let a: [i32; 0] = [];
3179 /// assert_eq!(a.iter().position_max(), None);
3181 /// let a = [-3, 0, 1, 5, -10];
3182 /// assert_eq!(a.iter().position_max(), Some(3));
3184 /// let a = [1, 1, -1, -1];
3185 /// assert_eq!(a.iter().position_max(), Some(1));
3187 fn position_max(self) -> Option
<usize>
3188 where Self: Sized
, Self::Item
: Ord
3191 .max_by(|x
, y
| Ord
::cmp(&x
.1, &y
.1))
3195 /// Return the position of the maximum element in the iterator, as
3196 /// determined by the specified function.
3198 /// If several elements are equally maximum, the position of the
3199 /// last of them is returned.
3204 /// use itertools::Itertools;
3206 /// let a: [i32; 0] = [];
3207 /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), None);
3209 /// let a = [-3_i32, 0, 1, 5, -10];
3210 /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(4));
3212 /// let a = [1_i32, 1, -1, -1];
3213 /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(3));
3215 fn position_max_by_key
<K
, F
>(self, mut key
: F
) -> Option
<usize>
3216 where Self: Sized
, K
: Ord
, F
: FnMut(&Self::Item
) -> K
3219 .max_by(|x
, y
| Ord
::cmp(&key(&x
.1), &key(&y
.1)))
3223 /// Return the position of the maximum element in the iterator, as
3224 /// determined by the specified comparison function.
3226 /// If several elements are equally maximum, the position of the
3227 /// last of them is returned.
3232 /// use itertools::Itertools;
3234 /// let a: [i32; 0] = [];
3235 /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), None);
3237 /// let a = [-3_i32, 0, 1, 5, -10];
3238 /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(3));
3240 /// let a = [1_i32, 1, -1, -1];
3241 /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(1));
3243 fn position_max_by
<F
>(self, mut compare
: F
) -> Option
<usize>
3244 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
3247 .max_by(|x
, y
| compare(&x
.1, &y
.1))
3251 /// Return the position of the minimum element in the iterator.
3253 /// If several elements are equally minimum, the position of the
3254 /// first of them is returned.
3259 /// use itertools::Itertools;
3261 /// let a: [i32; 0] = [];
3262 /// assert_eq!(a.iter().position_min(), None);
3264 /// let a = [-3, 0, 1, 5, -10];
3265 /// assert_eq!(a.iter().position_min(), Some(4));
3267 /// let a = [1, 1, -1, -1];
3268 /// assert_eq!(a.iter().position_min(), Some(2));
3270 fn position_min(self) -> Option
<usize>
3271 where Self: Sized
, Self::Item
: Ord
3274 .min_by(|x
, y
| Ord
::cmp(&x
.1, &y
.1))
3278 /// Return the position of the minimum element in the iterator, as
3279 /// determined by the specified function.
3281 /// If several elements are equally minimum, the position of the
3282 /// first of them is returned.
3287 /// use itertools::Itertools;
3289 /// let a: [i32; 0] = [];
3290 /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), None);
3292 /// let a = [-3_i32, 0, 1, 5, -10];
3293 /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(1));
3295 /// let a = [1_i32, 1, -1, -1];
3296 /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(0));
3298 fn position_min_by_key
<K
, F
>(self, mut key
: F
) -> Option
<usize>
3299 where Self: Sized
, K
: Ord
, F
: FnMut(&Self::Item
) -> K
3302 .min_by(|x
, y
| Ord
::cmp(&key(&x
.1), &key(&y
.1)))
3306 /// Return the position of the minimum element in the iterator, as
3307 /// determined by the specified comparison function.
3309 /// If several elements are equally minimum, the position of the
3310 /// first of them is returned.
3315 /// use itertools::Itertools;
3317 /// let a: [i32; 0] = [];
3318 /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), None);
3320 /// let a = [-3_i32, 0, 1, 5, -10];
3321 /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(4));
3323 /// let a = [1_i32, 1, -1, -1];
3324 /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(2));
3326 fn position_min_by
<F
>(self, mut compare
: F
) -> Option
<usize>
3327 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
3330 .min_by(|x
, y
| compare(&x
.1, &y
.1))
3334 /// Return the positions of the minimum and maximum elements in
3337 /// The return type [`MinMaxResult`] is an enum of three variants:
3339 /// - `NoElements` if the iterator is empty.
3340 /// - `OneElement(xpos)` if the iterator has exactly one element.
3341 /// - `MinMax(xpos, ypos)` is returned otherwise, where the
3342 /// element at `xpos` ≤ the element at `ypos`. While the
3343 /// referenced elements themselves may be equal, `xpos` cannot
3344 /// be equal to `ypos`.
3346 /// On an iterator of length `n`, `position_minmax` does `1.5 * n`
3347 /// comparisons, and so is faster than calling `position_min` and
3348 /// `position_max` separately which does `2 * n` comparisons.
3350 /// For the minimum, if several elements are equally minimum, the
3351 /// position of the first of them is returned. For the maximum, if
3352 /// several elements are equally maximum, the position of the last
3353 /// of them is returned.
3355 /// The elements can be floats but no particular result is
3356 /// guaranteed if an element is NaN.
3361 /// use itertools::Itertools;
3362 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3364 /// let a: [i32; 0] = [];
3365 /// assert_eq!(a.iter().position_minmax(), NoElements);
3368 /// assert_eq!(a.iter().position_minmax(), OneElement(0));
3370 /// let a = [-3, 0, 1, 5, -10];
3371 /// assert_eq!(a.iter().position_minmax(), MinMax(4, 3));
3373 /// let a = [1, 1, -1, -1];
3374 /// assert_eq!(a.iter().position_minmax(), MinMax(2, 1));
3376 fn position_minmax(self) -> MinMaxResult
<usize>
3377 where Self: Sized
, Self::Item
: PartialOrd
3379 use crate::MinMaxResult
::{NoElements, OneElement, MinMax}
;
3380 match minmax
::minmax_impl(self.enumerate(), |_
| (), |x
, y
, _
, _
| x
.1 < y
.1) {
3381 NoElements
=> NoElements
,
3382 OneElement(x
) => OneElement(x
.0),
3383 MinMax(x
, y
) => MinMax(x
.0, y
.0),
3387 /// Return the postions of the minimum and maximum elements of an
3388 /// iterator, as determined by the specified function.
3390 /// The return value is a variant of [`MinMaxResult`] like for
3391 /// [`position_minmax`].
3393 /// For the minimum, if several elements are equally minimum, the
3394 /// position of the first of them is returned. For the maximum, if
3395 /// several elements are equally maximum, the position of the last
3396 /// of them is returned.
3398 /// The keys can be floats but no particular result is guaranteed
3399 /// if a key is NaN.
3404 /// use itertools::Itertools;
3405 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3407 /// let a: [i32; 0] = [];
3408 /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), NoElements);
3410 /// let a = [10_i32];
3411 /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), OneElement(0));
3413 /// let a = [-3_i32, 0, 1, 5, -10];
3414 /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(1, 4));
3416 /// let a = [1_i32, 1, -1, -1];
3417 /// assert_eq!(a.iter().position_minmax_by_key(|x| x.abs()), MinMax(0, 3));
3420 /// [`position_minmax`]: Self::position_minmax
3421 fn position_minmax_by_key
<K
, F
>(self, mut key
: F
) -> MinMaxResult
<usize>
3422 where Self: Sized
, K
: PartialOrd
, F
: FnMut(&Self::Item
) -> K
3424 use crate::MinMaxResult
::{NoElements, OneElement, MinMax}
;
3425 match self.enumerate().minmax_by_key(|e
| key(&e
.1)) {
3426 NoElements
=> NoElements
,
3427 OneElement(x
) => OneElement(x
.0),
3428 MinMax(x
, y
) => MinMax(x
.0, y
.0),
3432 /// Return the postions of the minimum and maximum elements of an
3433 /// iterator, as determined by the specified comparison function.
3435 /// The return value is a variant of [`MinMaxResult`] like for
3436 /// [`position_minmax`].
3438 /// For the minimum, if several elements are equally minimum, the
3439 /// position of the first of them is returned. For the maximum, if
3440 /// several elements are equally maximum, the position of the last
3441 /// of them is returned.
3446 /// use itertools::Itertools;
3447 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
3449 /// let a: [i32; 0] = [];
3450 /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), NoElements);
3452 /// let a = [10_i32];
3453 /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), OneElement(0));
3455 /// let a = [-3_i32, 0, 1, 5, -10];
3456 /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(4, 3));
3458 /// let a = [1_i32, 1, -1, -1];
3459 /// assert_eq!(a.iter().position_minmax_by(|x, y| x.cmp(y)), MinMax(2, 1));
3462 /// [`position_minmax`]: Self::position_minmax
3463 fn position_minmax_by
<F
>(self, mut compare
: F
) -> MinMaxResult
<usize>
3464 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
3466 use crate::MinMaxResult
::{NoElements, OneElement, MinMax}
;
3467 match self.enumerate().minmax_by(|x
, y
| compare(&x
.1, &y
.1)) {
3468 NoElements
=> NoElements
,
3469 OneElement(x
) => OneElement(x
.0),
3470 MinMax(x
, y
) => MinMax(x
.0, y
.0),
3474 /// If the iterator yields exactly one element, that element will be returned, otherwise
3475 /// an error will be returned containing an iterator that has the same output as the input
3478 /// This provides an additional layer of validation over just calling `Iterator::next()`.
3479 /// If your assumption that there should only be one element yielded is false this provides
3480 /// the opportunity to detect and handle that, preventing errors at a distance.
3484 /// use itertools::Itertools;
3486 /// assert_eq!((0..10).filter(|&x| x == 2).exactly_one().unwrap(), 2);
3487 /// assert!((0..10).filter(|&x| x > 1 && x < 4).exactly_one().unwrap_err().eq(2..4));
3488 /// assert!((0..10).filter(|&x| x > 1 && x < 5).exactly_one().unwrap_err().eq(2..5));
3489 /// assert!((0..10).filter(|&_| false).exactly_one().unwrap_err().eq(0..0));
3491 fn exactly_one(mut self) -> Result
<Self::Item
, ExactlyOneError
<Self>>
3499 Err(ExactlyOneError
::new(Some(Either
::Left([first
, second
])), self))
3506 None
=> Err(ExactlyOneError
::new(None
, self)),
3510 /// If the iterator yields no elements, Ok(None) will be returned. If the iterator yields
3511 /// exactly one element, that element will be returned, otherwise an error will be returned
3512 /// containing an iterator that has the same output as the input iterator.
3514 /// This provides an additional layer of validation over just calling `Iterator::next()`.
3515 /// If your assumption that there should be at most one element yielded is false this provides
3516 /// the opportunity to detect and handle that, preventing errors at a distance.
3520 /// use itertools::Itertools;
3522 /// assert_eq!((0..10).filter(|&x| x == 2).at_most_one().unwrap(), Some(2));
3523 /// assert!((0..10).filter(|&x| x > 1 && x < 4).at_most_one().unwrap_err().eq(2..4));
3524 /// assert!((0..10).filter(|&x| x > 1 && x < 5).at_most_one().unwrap_err().eq(2..5));
3525 /// assert_eq!((0..10).filter(|&_| false).at_most_one().unwrap(), None);
3527 fn at_most_one(mut self) -> Result
<Option
<Self::Item
>, ExactlyOneError
<Self>>
3535 Err(ExactlyOneError
::new(Some(Either
::Left([first
, second
])), self))
3546 /// An iterator adaptor that allows the user to peek at multiple `.next()`
3547 /// values without advancing the base iterator.
3551 /// use itertools::Itertools;
3553 /// let mut iter = (0..10).multipeek();
3554 /// assert_eq!(iter.peek(), Some(&0));
3555 /// assert_eq!(iter.peek(), Some(&1));
3556 /// assert_eq!(iter.peek(), Some(&2));
3557 /// assert_eq!(iter.next(), Some(0));
3558 /// assert_eq!(iter.peek(), Some(&1));
3560 #[cfg(feature = "use_alloc")]
3561 fn multipeek(self) -> MultiPeek
<Self>
3565 multipeek_impl
::multipeek(self)
3568 /// Collect the items in this iterator and return a `HashMap` which
3569 /// contains each item that appears in the iterator and the number
3570 /// of times it appears.
3574 /// # use itertools::Itertools;
3575 /// let counts = [1, 1, 1, 3, 3, 5].into_iter().counts();
3576 /// assert_eq!(counts[&1], 3);
3577 /// assert_eq!(counts[&3], 2);
3578 /// assert_eq!(counts[&5], 1);
3579 /// assert_eq!(counts.get(&0), None);
3581 #[cfg(feature = "use_std")]
3582 fn counts(self) -> HashMap
<Self::Item
, usize>
3585 Self::Item
: Eq
+ Hash
,
3587 let mut counts
= HashMap
::new();
3588 self.for_each(|item
| *counts
.entry(item
).or_default() += 1);
3592 /// Collect the items in this iterator and return a `HashMap` which
3593 /// contains each item that appears in the iterator and the number
3594 /// of times it appears,
3595 /// determining identity using a keying function.
3598 /// # use itertools::Itertools;
3599 /// struct Character {
3600 /// first_name: &'static str,
3601 /// last_name: &'static str,
3604 /// let characters =
3606 /// Character { first_name: "Amy", last_name: "Pond" },
3607 /// Character { first_name: "Amy", last_name: "Wong" },
3608 /// Character { first_name: "Amy", last_name: "Santiago" },
3609 /// Character { first_name: "James", last_name: "Bond" },
3610 /// Character { first_name: "James", last_name: "Sullivan" },
3611 /// Character { first_name: "James", last_name: "Norington" },
3612 /// Character { first_name: "James", last_name: "Kirk" },
3615 /// let first_name_frequency =
3618 /// .counts_by(|c| c.first_name);
3620 /// assert_eq!(first_name_frequency["Amy"], 3);
3621 /// assert_eq!(first_name_frequency["James"], 4);
3622 /// assert_eq!(first_name_frequency.contains_key("Asha"), false);
3624 #[cfg(feature = "use_std")]
3625 fn counts_by
<K
, F
>(self, f
: F
) -> HashMap
<K
, usize>
3629 F
: FnMut(Self::Item
) -> K
,
3631 self.map(f
).counts()
3634 /// Converts an iterator of tuples into a tuple of containers.
3636 /// `unzip()` consumes an entire iterator of n-ary tuples, producing `n` collections, one for each
3639 /// This function is, in some sense, the opposite of [`multizip`].
3642 /// use itertools::Itertools;
3644 /// let inputs = vec![(1, 2, 3), (4, 5, 6), (7, 8, 9)];
3646 /// let (a, b, c): (Vec<_>, Vec<_>, Vec<_>) = inputs
3650 /// assert_eq!(a, vec![1, 4, 7]);
3651 /// assert_eq!(b, vec![2, 5, 8]);
3652 /// assert_eq!(c, vec![3, 6, 9]);
3654 fn multiunzip
<FromI
>(self) -> FromI
3656 Self: Sized
+ MultiUnzip
<FromI
>,
3658 MultiUnzip
::multiunzip(self)
3662 impl<T
: ?Sized
> Itertools
for T
where T
: Iterator { }
3664 /// Return `true` if both iterables produce equal sequences
3665 /// (elements pairwise equal and sequences of the same length),
3666 /// `false` otherwise.
3668 /// [`IntoIterator`] enabled version of [`Iterator::eq`].
3671 /// assert!(itertools::equal(vec![1, 2, 3], 1..4));
3672 /// assert!(!itertools::equal(&[0, 0], &[0, 0, 0]));
3674 pub fn equal
<I
, J
>(a
: I
, b
: J
) -> bool
3675 where I
: IntoIterator
,
3677 I
::Item
: PartialEq
<J
::Item
>
3682 /// Assert that two iterables produce equal sequences, with the same
3683 /// semantics as [`equal(a, b)`](equal).
3685 /// **Panics** on assertion failure with a message that shows the
3686 /// two iteration elements.
3689 /// assert_equal("exceed".split('c'), "excess".split('c'));
3690 /// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1',
3692 pub fn assert_equal
<I
, J
>(a
: I
, b
: J
)
3693 where I
: IntoIterator
,
3695 I
::Item
: fmt
::Debug
+ PartialEq
<J
::Item
>,
3696 J
::Item
: fmt
::Debug
,
3698 let mut ia
= a
.into_iter();
3699 let mut ib
= b
.into_iter();
3702 match (ia
.next(), ib
.next()) {
3703 (None
, None
) => return,
3705 let equal
= match (&a
, &b
) {
3706 (&Some(ref a
), &Some(ref b
)) => a
== b
,
3709 assert
!(equal
, "Failed assertion {a:?} == {b:?} for iteration {i}",
3717 /// Partition a sequence using predicate `pred` so that elements
3718 /// that map to `true` are placed before elements which map to `false`.
3720 /// The order within the partitions is arbitrary.
3722 /// Return the index of the split point.
3725 /// use itertools::partition;
3727 /// # // use repeated numbers to not promise any ordering
3728 /// let mut data = [7, 1, 1, 7, 1, 1, 7];
3729 /// let split_index = partition(&mut data, |elt| *elt >= 3);
3731 /// assert_eq!(data, [7, 7, 7, 1, 1, 1, 1]);
3732 /// assert_eq!(split_index, 3);
3734 pub fn partition
<'a
, A
: 'a
, I
, F
>(iter
: I
, mut pred
: F
) -> usize
3735 where I
: IntoIterator
<Item
= &'a
mut A
>,
3736 I
::IntoIter
: DoubleEndedIterator
,
3737 F
: FnMut(&A
) -> bool
3739 let mut split_index
= 0;
3740 let mut iter
= iter
.into_iter();
3741 'main
: while let Some(front
) = iter
.next() {
3744 match iter
.next_back() {
3745 Some(back
) => if pred(back
) {
3746 std
::mem
::swap(front
, back
);
3749 None
=> break 'main
,
3758 /// An enum used for controlling the execution of `fold_while`.
3760 /// See [`.fold_while()`](Itertools::fold_while) for more information.
3761 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3762 pub enum FoldWhile
<T
> {
3763 /// Continue folding with this value
3765 /// Fold is complete and will return this value
3769 impl<T
> FoldWhile
<T
> {
3770 /// Return the value in the continue or done.
3771 pub fn into_inner(self) -> T
{
3773 FoldWhile
::Continue(x
) | FoldWhile
::Done(x
) => x
,
3777 /// Return true if `self` is `Done`, false if it is `Continue`.
3778 pub fn is_done(&self) -> bool
{
3780 FoldWhile
::Continue(_
) => false,
3781 FoldWhile
::Done(_
) => true,