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