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