]> git.proxmox.com Git - rustc.git/blob - src/vendor/itertools/src/lib.rs
New upstream version 1.25.0+dfsg1
[rustc.git] / src / vendor / itertools / src / lib.rs
1 #![warn(missing_docs)]
2 #![crate_name="itertools"]
3 #![cfg_attr(not(feature = "use_std"), no_std)]
4
5 //! Itertools — extra iterator adaptors, functions and macros.
6 //!
7 //! To use the iterator methods in this crate, import the [`Itertools` trait](./trait.Itertools.html):
8 //!
9 //! ```
10 //! use itertools::Itertools;
11 //! ```
12 //!
13 //! ## Crate Features
14 //!
15 //! - `use_std`
16 //! - Enabled by default.
17 //! - Disable to compile itertools using `#![no_std]`. This disables
18 //! any items that depend on collections (like `group_by`, `unique`,
19 //! `kmerge`, `join` and many more).
20 //!
21 //! ## Rust Version
22 //!
23 //! This version of itertools requires Rust 1.12 or later.
24 //!
25 #![doc(html_root_url="https://docs.rs/itertools/0.7/")]
26
27 extern crate either;
28
29 #[cfg(not(feature = "use_std"))]
30 extern crate core as std;
31
32 pub use either::Either;
33
34 use std::iter::{IntoIterator};
35 use std::cmp::Ordering;
36 use std::fmt;
37 #[cfg(feature = "use_std")]
38 use std::hash::Hash;
39 #[cfg(feature = "use_std")]
40 use std::fmt::Write;
41
42 #[macro_use]
43 mod impl_macros;
44
45 // for compatibility with no std and macros
46 #[doc(hidden)]
47 pub use std::iter as __std_iter;
48
49 /// The concrete iterator types.
50 pub mod structs {
51 pub use adaptors::{
52 Dedup,
53 Interleave,
54 InterleaveShortest,
55 Product,
56 PutBack,
57 Batching,
58 Step,
59 MapResults,
60 Merge,
61 MergeBy,
62 TakeWhileRef,
63 WhileSome,
64 Coalesce,
65 TupleCombinations,
66 Flatten,
67 Positions,
68 Update,
69 };
70 #[cfg(feature = "use_std")]
71 pub use adaptors::MultiProduct;
72 #[cfg(feature = "use_std")]
73 pub use combinations::Combinations;
74 pub use cons_tuples_impl::ConsTuples;
75 pub use format::{Format, FormatWith};
76 #[cfg(feature = "use_std")]
77 pub use groupbylazy::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups};
78 pub use intersperse::Intersperse;
79 #[cfg(feature = "use_std")]
80 pub use kmerge_impl::{KMerge, KMergeBy};
81 pub use merge_join::MergeJoinBy;
82 #[cfg(feature = "use_std")]
83 pub use multipeek_impl::MultiPeek;
84 pub use pad_tail::PadUsing;
85 pub use peeking_take_while::PeekingTakeWhile;
86 pub use process_results_impl::ProcessResults;
87 #[cfg(feature = "use_std")]
88 pub use put_back_n_impl::PutBackN;
89 #[cfg(feature = "use_std")]
90 pub use rciter_impl::RcIter;
91 pub use repeatn::RepeatN;
92 pub use sources::{RepeatCall, Unfold, Iterate};
93 #[cfg(feature = "use_std")]
94 pub use tee::Tee;
95 pub use tuple_impl::{TupleBuffer, TupleWindows, Tuples};
96 #[cfg(feature = "use_std")]
97 pub use unique_impl::{Unique, UniqueBy};
98 pub use with_position::WithPosition;
99 pub use zip_eq_impl::ZipEq;
100 pub use zip_longest::ZipLongest;
101 pub use ziptuple::Zip;
102 }
103 pub use structs::*;
104 pub use concat_impl::concat;
105 pub use cons_tuples_impl::cons_tuples;
106 pub use diff::diff_with;
107 pub use diff::Diff;
108 #[cfg(feature = "use_std")]
109 pub use kmerge_impl::{kmerge_by};
110 pub use minmax::MinMaxResult;
111 pub use peeking_take_while::PeekingNext;
112 pub use process_results_impl::process_results;
113 pub use repeatn::repeat_n;
114 pub use sources::{repeat_call, unfold, iterate};
115 pub use with_position::Position;
116 pub use ziptuple::multizip;
117 mod adaptors;
118 mod either_or_both;
119 pub use either_or_both::EitherOrBoth;
120 #[doc(hidden)]
121 pub mod free;
122 #[doc(inline)]
123 pub use free::*;
124 mod concat_impl;
125 mod cons_tuples_impl;
126 #[cfg(feature = "use_std")]
127 mod combinations;
128 mod diff;
129 mod format;
130 #[cfg(feature = "use_std")]
131 mod groupbylazy;
132 mod intersperse;
133 #[cfg(feature = "use_std")]
134 mod kmerge_impl;
135 mod merge_join;
136 mod minmax;
137 #[cfg(feature = "use_std")]
138 mod multipeek_impl;
139 mod pad_tail;
140 mod peeking_take_while;
141 mod process_results_impl;
142 #[cfg(feature = "use_std")]
143 mod put_back_n_impl;
144 #[cfg(feature = "use_std")]
145 mod rciter_impl;
146 mod repeatn;
147 mod size_hint;
148 mod sources;
149 #[cfg(feature = "use_std")]
150 mod tee;
151 mod tuple_impl;
152 #[cfg(feature = "use_std")]
153 mod unique_impl;
154 mod with_position;
155 mod zip_eq_impl;
156 mod zip_longest;
157 mod ziptuple;
158
159 #[macro_export]
160 /// Create an iterator over the “cartesian product” of iterators.
161 ///
162 /// Iterator element type is like `(A, B, ..., E)` if formed
163 /// from iterators `(I, J, ..., M)` with element types `I::Item = A`, `J::Item = B`, etc.
164 ///
165 /// ```
166 /// #[macro_use] extern crate itertools;
167 /// # fn main() {
168 /// // Iterate over the coordinates of a 4 x 4 x 4 grid
169 /// // from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
170 /// for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
171 /// // ..
172 /// }
173 /// # }
174 /// ```
175 ///
176 /// **Note:** To enable the macros in this crate, use the `#[macro_use]`
177 /// attribute when importing the crate:
178 ///
179 /// ```
180 /// #[macro_use] extern crate itertools;
181 /// # fn main() { }
182 /// ```
183 macro_rules! iproduct {
184 (@flatten $I:expr,) => (
185 $I
186 );
187 (@flatten $I:expr, $J:expr, $($K:expr,)*) => (
188 iproduct!(@flatten $crate::cons_tuples(iproduct!($I, $J)), $($K,)*)
189 );
190 ($I:expr) => (
191 $crate::__std_iter::IntoIterator::into_iter($I)
192 );
193 ($I:expr, $J:expr) => (
194 $crate::Itertools::cartesian_product(iproduct!($I), iproduct!($J))
195 );
196 ($I:expr, $J:expr, $($K:expr),+) => (
197 iproduct!(@flatten iproduct!($I, $J), $($K,)+)
198 );
199 }
200
201 #[macro_export]
202 /// Create an iterator running multiple iterators in lockstep.
203 ///
204 /// The `izip!` iterator yields elements until any subiterator
205 /// returns `None`.
206 ///
207 /// This is a version of the standard ``.zip()`` that's supporting more than
208 /// two iterators. The iterator elment type is a tuple with one element
209 /// from each of the input iterators. Just like ``.zip()``, the iteration stops
210 /// when the shortest of the inputs reaches its end.
211 ///
212 /// **Note:** The result of this macro is an iterator composed of
213 /// repeated `.zip()` and a `.map()`; it has an anonymous type.
214 /// Prefer this macro `izip!()` over [`multizip`] for the performance benefits
215 /// of using the standard library `.zip()`.
216 ///
217 /// [`multizip`]: fn.multizip.html
218 ///
219 /// ```
220 /// #[macro_use] extern crate itertools;
221 /// # fn main() {
222 ///
223 /// // iterate over three sequences side-by-side
224 /// let mut results = [0, 0, 0, 0];
225 /// let inputs = [3, 7, 9, 6];
226 ///
227 /// for (r, index, input) in izip!(&mut results, 0..10, &inputs) {
228 /// *r = index * 10 + input;
229 /// }
230 ///
231 /// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]);
232 /// # }
233 /// ```
234 ///
235 /// **Note:** To enable the macros in this crate, use the `#[macro_use]`
236 /// attribute when importing the crate:
237 ///
238 /// ```
239 /// #[macro_use] extern crate itertools;
240 /// # fn main() { }
241 /// ```
242 macro_rules! izip {
243 // @closure creates a tuple-flattening closure for .map() call. usage:
244 // @closure partial_pattern => partial_tuple , rest , of , iterators
245 // eg. izip!( @closure ((a, b), c) => (a, b, c) , dd , ee )
246 ( @closure $p:pat => $tup:expr ) => {
247 |$p| $tup
248 };
249
250 // The "b" identifier is a different identifier on each recursion level thanks to hygiene.
251 ( @closure $p:pat => ( $($tup:tt)* ) , $_iter:expr $( , $tail:expr )* ) => {
252 izip!(@closure ($p, b) => ( $($tup)*, b ) $( , $tail )*)
253 };
254
255 ( $first:expr $( , $rest:expr )* $(,)* ) => {
256 $crate::__std_iter::IntoIterator::into_iter($first)
257 $(
258 .zip($rest)
259 )*
260 .map(
261 izip!(@closure a => (a) $( , $rest )*)
262 )
263 };
264 }
265
266 /// The trait `Itertools`: extra iterator adaptors and methods for iterators.
267 ///
268 /// This trait defines a number of methods. They are divided into two groups:
269 ///
270 /// * *Adaptors* take an iterator and parameter as input, and return
271 /// a new iterator value. These are listed first in the trait. An example
272 /// of an adaptor is [`.interleave()`](#method.interleave)
273 ///
274 /// * *Regular methods* are those that don't return iterators and instead
275 /// return a regular value of some other kind.
276 /// [`.next_tuple()`](#method.next_tuple) is an example and the first regular
277 /// method in the list.
278 pub trait Itertools : Iterator {
279 // adaptors
280
281 /// Alternate elements from two iterators until both have run out.
282 ///
283 /// Iterator element type is `Self::Item`.
284 ///
285 /// This iterator is *fused*.
286 ///
287 /// ```
288 /// use itertools::Itertools;
289 ///
290 /// let it = (1..7).interleave(vec![-1, -2]);
291 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
292 /// ```
293 fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter>
294 where J: IntoIterator<Item = Self::Item>,
295 Self: Sized
296 {
297 interleave(self, other)
298 }
299
300 /// Alternate elements from two iterators until at least one of them has run
301 /// out.
302 ///
303 /// Iterator element type is `Self::Item`.
304 ///
305 /// ```
306 /// use itertools::Itertools;
307 ///
308 /// let it = (1..7).interleave_shortest(vec![-1, -2]);
309 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]);
310 /// ```
311 fn interleave_shortest<J>(self, other: J) -> InterleaveShortest<Self, J::IntoIter>
312 where J: IntoIterator<Item = Self::Item>,
313 Self: Sized
314 {
315 adaptors::interleave_shortest(self, other.into_iter())
316 }
317
318 /// An iterator adaptor to insert a particular value
319 /// between each element of the adapted iterator.
320 ///
321 /// Iterator element type is `Self::Item`.
322 ///
323 /// This iterator is *fused*.
324 ///
325 /// ```
326 /// use itertools::Itertools;
327 ///
328 /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]);
329 /// ```
330 fn intersperse(self, element: Self::Item) -> Intersperse<Self>
331 where Self: Sized,
332 Self::Item: Clone
333 {
334 intersperse::intersperse(self, element)
335 }
336
337 /// Create an iterator which iterates over both this and the specified
338 /// iterator simultaneously, yielding pairs of two optional elements.
339 ///
340 /// This iterator is *fused*.
341 ///
342 /// As long as neither input iterator is exhausted yet, it yields two values
343 /// via `EitherOrBoth::Both`.
344 ///
345 /// When the parameter iterator is exhausted, it only yields a value from the
346 /// `self` iterator via `EitherOrBoth::Left`.
347 ///
348 /// When the `self` iterator is exhausted, it only yields a value from the
349 /// parameter iterator via `EitherOrBoth::Right`.
350 ///
351 /// When both iterators return `None`, all further invocations of `.next()`
352 /// will return `None`.
353 ///
354 /// Iterator element type is
355 /// [`EitherOrBoth<Self::Item, J::Item>`](enum.EitherOrBoth.html).
356 ///
357 /// ```rust
358 /// use itertools::EitherOrBoth::{Both, Right};
359 /// use itertools::Itertools;
360 /// let it = (0..1).zip_longest(1..3);
361 /// itertools::assert_equal(it, vec![Both(0, 1), Right(2)]);
362 /// ```
363 #[inline]
364 fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter>
365 where J: IntoIterator,
366 Self: Sized
367 {
368 zip_longest::zip_longest(self, other.into_iter())
369 }
370
371 /// Create an iterator which iterates over both this and the specified
372 /// iterator simultaneously, yielding pairs of elements.
373 ///
374 /// **Panics** if the iterators reach an end and they are not of equal
375 /// lengths.
376 #[inline]
377 fn zip_eq<J>(self, other: J) -> ZipEq<Self, J::IntoIter>
378 where J: IntoIterator,
379 Self: Sized
380 {
381 zip_eq(self, other)
382 }
383
384 /// A “meta iterator adaptor”. Its closure recives a reference to the
385 /// iterator and may pick off as many elements as it likes, to produce the
386 /// next iterator element.
387 ///
388 /// Iterator element type is `B`.
389 ///
390 /// ```
391 /// use itertools::Itertools;
392 ///
393 /// // An adaptor that gathers elements in pairs
394 /// let pit = (0..4).batching(|it| {
395 /// match it.next() {
396 /// None => None,
397 /// Some(x) => match it.next() {
398 /// None => None,
399 /// Some(y) => Some((x, y)),
400 /// }
401 /// }
402 /// });
403 ///
404 /// itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
405 /// ```
406 ///
407 fn batching<B, F>(self, f: F) -> Batching<Self, F>
408 where F: FnMut(&mut Self) -> Option<B>,
409 Self: Sized
410 {
411 adaptors::batching(self, f)
412 }
413
414 /// Return an *iterable* that can group iterator elements.
415 /// Consecutive elements that map to the same key (“runs”), are assigned
416 /// to the same group.
417 ///
418 /// `GroupBy` is the storage for the lazy grouping operation.
419 ///
420 /// If the groups are consumed in order, or if each group's iterator is
421 /// dropped without keeping it around, then `GroupBy` uses no
422 /// allocations. It needs allocations only if several group iterators
423 /// are alive at the same time.
424 ///
425 /// This type implements `IntoIterator` (it is **not** an iterator
426 /// itself), because the group iterators need to borrow from this
427 /// value. It should be stored in a local variable or temporary and
428 /// iterated.
429 ///
430 /// Iterator element type is `(K, Group)`: the group's key and the
431 /// group iterator.
432 ///
433 /// ```
434 /// use itertools::Itertools;
435 ///
436 /// // group data into runs of larger than zero or not.
437 /// let data = vec![1, 3, -2, -2, 1, 0, 1, 2];
438 /// // groups: |---->|------>|--------->|
439 ///
440 /// // Note: The `&` is significant here, `GroupBy` is iterable
441 /// // only by reference. You can also call `.into_iter()` explicitly.
442 /// for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) {
443 /// // Check that the sum of each group is +/- 4.
444 /// assert_eq!(4, group.sum::<i32>().abs());
445 /// }
446 /// ```
447 #[cfg(feature = "use_std")]
448 fn group_by<K, F>(self, key: F) -> GroupBy<K, Self, F>
449 where Self: Sized,
450 F: FnMut(&Self::Item) -> K,
451 K: PartialEq,
452 {
453 groupbylazy::new(self, key)
454 }
455
456 /// Return an *iterable* that can chunk the iterator.
457 ///
458 /// Yield subiterators (chunks) that each yield a fixed number elements,
459 /// determined by `size`. The last chunk will be shorter if there aren't
460 /// enough elements.
461 ///
462 /// `IntoChunks` is based on `GroupBy`: it is iterable (implements
463 /// `IntoIterator`, **not** `Iterator`), and it only buffers if several
464 /// chunk iterators are alive at the same time.
465 ///
466 /// Iterator element type is `Chunk`, each chunk's iterator.
467 ///
468 /// **Panics** if `size` is 0.
469 ///
470 /// ```
471 /// use itertools::Itertools;
472 ///
473 /// let data = vec![1, 1, 2, -2, 6, 0, 3, 1];
474 /// //chunk size=3 |------->|-------->|--->|
475 ///
476 /// // Note: The `&` is significant here, `IntoChunks` is iterable
477 /// // only by reference. You can also call `.into_iter()` explicitly.
478 /// for chunk in &data.into_iter().chunks(3) {
479 /// // Check that the sum of each chunk is 4.
480 /// assert_eq!(4, chunk.sum());
481 /// }
482 /// ```
483 #[cfg(feature = "use_std")]
484 fn chunks(self, size: usize) -> IntoChunks<Self>
485 where Self: Sized,
486 {
487 assert!(size != 0);
488 groupbylazy::new_chunks(self, size)
489 }
490
491 /// Return an iterator over all contiguous windows producing tuples of
492 /// a specific size (up to 4).
493 ///
494 /// `tuple_windows` clones the iterator elements so that they can be
495 /// part of successive windows, this makes it most suited for iterators
496 /// of references and other values that are cheap to copy.
497 ///
498 /// ```
499 /// use itertools::Itertools;
500 /// let mut v = Vec::new();
501 /// for (a, b) in (1..5).tuple_windows() {
502 /// v.push((a, b));
503 /// }
504 /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4)]);
505 ///
506 /// let mut it = (1..5).tuple_windows();
507 /// assert_eq!(Some((1, 2, 3)), it.next());
508 /// assert_eq!(Some((2, 3, 4)), it.next());
509 /// assert_eq!(None, it.next());
510 ///
511 /// // this requires a type hint
512 /// let it = (1..5).tuple_windows::<(_, _, _)>();
513 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
514 ///
515 /// // you can also specify the complete type
516 /// use itertools::TupleWindows;
517 /// use std::ops::Range;
518 ///
519 /// let it: TupleWindows<Range<u32>, (u32, u32, u32)> = (1..5).tuple_windows();
520 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
521 /// ```
522 fn tuple_windows<T>(self) -> TupleWindows<Self, T>
523 where Self: Sized + Iterator<Item = T::Item>,
524 T: tuple_impl::TupleCollect,
525 T::Item: Clone
526 {
527 tuple_impl::tuple_windows(self)
528 }
529
530 /// Return an iterator that groups the items in tuples of a specific size
531 /// (up to 4).
532 ///
533 /// See also the method [`.next_tuple()`](#method.next_tuple).
534 ///
535 /// ```
536 /// use itertools::Itertools;
537 /// let mut v = Vec::new();
538 /// for (a, b) in (1..5).tuples() {
539 /// v.push((a, b));
540 /// }
541 /// assert_eq!(v, vec![(1, 2), (3, 4)]);
542 ///
543 /// let mut it = (1..7).tuples();
544 /// assert_eq!(Some((1, 2, 3)), it.next());
545 /// assert_eq!(Some((4, 5, 6)), it.next());
546 /// assert_eq!(None, it.next());
547 ///
548 /// // this requires a type hint
549 /// let it = (1..7).tuples::<(_, _, _)>();
550 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
551 ///
552 /// // you can also specify the complete type
553 /// use itertools::Tuples;
554 /// use std::ops::Range;
555 ///
556 /// let it: Tuples<Range<u32>, (u32, u32, u32)> = (1..7).tuples();
557 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
558 /// ```
559 ///
560 /// See also [`Tuples::into_buffer`](structs/struct.Tuples.html#method.into_buffer).
561 fn tuples<T>(self) -> Tuples<Self, T>
562 where Self: Sized + Iterator<Item = T::Item>,
563 T: tuple_impl::TupleCollect
564 {
565 tuple_impl::tuples(self)
566 }
567
568 /// Split into an iterator pair that both yield all elements from
569 /// the original iterator.
570 ///
571 /// **Note:** If the iterator is clonable, prefer using that instead
572 /// of using this method. It is likely to be more efficient.
573 ///
574 /// Iterator element type is `Self::Item`.
575 ///
576 /// ```
577 /// use itertools::Itertools;
578 /// let xs = vec![0, 1, 2, 3];
579 ///
580 /// let (mut t1, t2) = xs.into_iter().tee();
581 /// itertools::assert_equal(t1.next(), Some(0));
582 /// itertools::assert_equal(t2, 0..4);
583 /// itertools::assert_equal(t1, 1..4);
584 /// ```
585 #[cfg(feature = "use_std")]
586 fn tee(self) -> (Tee<Self>, Tee<Self>)
587 where Self: Sized,
588 Self::Item: Clone
589 {
590 tee::new(self)
591 }
592
593 /// Return an iterator adaptor that steps `n` elements in the base iterator
594 /// for each iteration.
595 ///
596 /// The iterator steps by yielding the next element from the base iterator,
597 /// then skipping forward `n - 1` elements.
598 ///
599 /// Iterator element type is `Self::Item`.
600 ///
601 /// **Panics** if the step is 0.
602 ///
603 /// ```
604 /// use itertools::Itertools;
605 ///
606 /// let it = (0..8).step(3);
607 /// itertools::assert_equal(it, vec![0, 3, 6]);
608 /// ```
609 fn step(self, n: usize) -> Step<Self>
610 where Self: Sized
611 {
612 adaptors::step(self, n)
613 }
614
615 /// Return an iterator adaptor that applies the provided closure
616 /// to every `Result::Ok` value. `Result::Err` values are
617 /// unchanged.
618 ///
619 /// ```
620 /// use itertools::Itertools;
621 ///
622 /// let input = vec![Ok(41), Err(false), Ok(11)];
623 /// let it = input.into_iter().map_results(|i| i + 1);
624 /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
625 /// ```
626 fn map_results<F, T, U, E>(self, f: F) -> MapResults<Self, F>
627 where Self: Iterator<Item = Result<T, E>> + Sized,
628 F: FnMut(T) -> U,
629 {
630 adaptors::map_results(self, f)
631 }
632
633 /// Return an iterator adaptor that merges the two base iterators in
634 /// ascending order. If both base iterators are sorted (ascending), the
635 /// result is sorted.
636 ///
637 /// Iterator element type is `Self::Item`.
638 ///
639 /// ```
640 /// use itertools::Itertools;
641 ///
642 /// let a = (0..11).step(3);
643 /// let b = (0..11).step(5);
644 /// let it = a.merge(b);
645 /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]);
646 /// ```
647 fn merge<J>(self, other: J) -> Merge<Self, J::IntoIter>
648 where Self: Sized,
649 Self::Item: PartialOrd,
650 J: IntoIterator<Item = Self::Item>
651 {
652 merge(self, other)
653 }
654
655 /// Return an iterator adaptor that merges the two base iterators in order.
656 /// This is much like `.merge()` but allows for a custom ordering.
657 ///
658 /// This can be especially useful for sequences of tuples.
659 ///
660 /// Iterator element type is `Self::Item`.
661 ///
662 /// ```
663 /// use itertools::Itertools;
664 ///
665 /// let a = (0..).zip("bc".chars());
666 /// let b = (0..).zip("ad".chars());
667 /// let it = a.merge_by(b, |x, y| x.1 <= y.1);
668 /// itertools::assert_equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]);
669 /// ```
670
671 fn merge_by<J, F>(self, other: J, is_first: F) -> MergeBy<Self, J::IntoIter, F>
672 where Self: Sized,
673 J: IntoIterator<Item = Self::Item>,
674 F: FnMut(&Self::Item, &Self::Item) -> bool
675 {
676 adaptors::merge_by_new(self, other.into_iter(), is_first)
677 }
678
679 /// Create an iterator that merges items from both this and the specified
680 /// iterator in ascending order.
681 ///
682 /// It chooses whether to pair elements based on the `Ordering` returned by the
683 /// specified compare function. At any point, inspecting the tip of the
684 /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
685 /// `J::Item` respectively, the resulting iterator will:
686 ///
687 /// - Emit `EitherOrBoth::Left(i)` when `i < j`,
688 /// and remove `i` from its source iterator
689 /// - Emit `EitherOrBoth::Right(j)` when `i > j`,
690 /// and remove `j` from its source iterator
691 /// - Emit `EitherOrBoth::Both(i, j)` when `i == j`,
692 /// and remove both `i` and `j` from their respective source iterators
693 ///
694 /// ```
695 /// use itertools::Itertools;
696 /// use itertools::EitherOrBoth::{Left, Right, Both};
697 ///
698 /// let ki = (0..10).step(3);
699 /// let ku = (0..10).step(5);
700 /// let ki_ku = ki.merge_join_by(ku, |i, j| i.cmp(j)).map(|either| {
701 /// match either {
702 /// Left(_) => "Ki",
703 /// Right(_) => "Ku",
704 /// Both(_, _) => "KiKu"
705 /// }
706 /// });
707 ///
708 /// itertools::assert_equal(ki_ku, vec!["KiKu", "Ki", "Ku", "Ki", "Ki"]);
709 /// ```
710 #[inline]
711 fn merge_join_by<J, F>(self, other: J, cmp_fn: F) -> MergeJoinBy<Self, J::IntoIter, F>
712 where J: IntoIterator,
713 F: FnMut(&Self::Item, &J::Item) -> std::cmp::Ordering,
714 Self: Sized
715 {
716 merge_join_by(self, other, cmp_fn)
717 }
718
719
720 /// Return an iterator adaptor that flattens an iterator of iterators by
721 /// merging them in ascending order.
722 ///
723 /// If all base iterators are sorted (ascending), the result is sorted.
724 ///
725 /// Iterator element type is `Self::Item`.
726 ///
727 /// ```
728 /// use itertools::Itertools;
729 ///
730 /// let a = (0..6).step(3);
731 /// let b = (1..6).step(3);
732 /// let c = (2..6).step(3);
733 /// let it = vec![a, b, c].into_iter().kmerge();
734 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5]);
735 /// ```
736 #[cfg(feature = "use_std")]
737 fn kmerge(self) -> KMerge<<Self::Item as IntoIterator>::IntoIter>
738 where Self: Sized,
739 Self::Item: IntoIterator,
740 <Self::Item as IntoIterator>::Item: PartialOrd,
741 {
742 kmerge(self)
743 }
744
745 /// Return an iterator adaptor that flattens an iterator of iterators by
746 /// merging them according to the given closure.
747 ///
748 /// The closure `first` is called with two elements *a*, *b* and should
749 /// return `true` if *a* is ordered before *b*.
750 ///
751 /// If all base iterators are sorted according to `first`, the result is
752 /// sorted.
753 ///
754 /// Iterator element type is `Self::Item`.
755 ///
756 /// ```
757 /// use itertools::Itertools;
758 ///
759 /// let a = vec![-1f64, 2., 3., -5., 6., -7.];
760 /// let b = vec![0., 2., -4.];
761 /// let mut it = vec![a, b].into_iter().kmerge_by(|a, b| a.abs() < b.abs());
762 /// assert_eq!(it.next(), Some(0.));
763 /// assert_eq!(it.last(), Some(-7.));
764 /// ```
765 #[cfg(feature = "use_std")]
766 fn kmerge_by<F>(self, first: F)
767 -> KMergeBy<<Self::Item as IntoIterator>::IntoIter, F>
768 where Self: Sized,
769 Self::Item: IntoIterator,
770 F: FnMut(&<Self::Item as IntoIterator>::Item,
771 &<Self::Item as IntoIterator>::Item) -> bool
772 {
773 kmerge_by(self, first)
774 }
775
776 /// Return an iterator adaptor that iterates over the cartesian product of
777 /// the element sets of two iterators `self` and `J`.
778 ///
779 /// Iterator element type is `(Self::Item, J::Item)`.
780 ///
781 /// ```
782 /// use itertools::Itertools;
783 ///
784 /// let it = (0..2).cartesian_product("αβ".chars());
785 /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]);
786 /// ```
787 fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter>
788 where Self: Sized,
789 Self::Item: Clone,
790 J: IntoIterator,
791 J::IntoIter: Clone
792 {
793 adaptors::cartesian_product(self, other.into_iter())
794 }
795
796 /// Return an iterator adaptor that iterates over the cartesian product of
797 /// all subiterators returned by meta-iterator `self`.
798 ///
799 /// All provided iterators must yield the same `Item` type. To generate
800 /// the product of iterators yielding multiple types, use the
801 /// [`iproduct`](macro.iproduct.html) macro instead.
802 ///
803 ///
804 /// The iterator element type is `Vec<T>`, where `T` is the iterator element
805 /// of the subiterators.
806 ///
807 /// ```
808 /// use itertools::Itertools;
809 /// let mut multi_prod = (0..3).map(|i| (i * 2)..(i * 2 + 2))
810 /// .multi_cartesian_product();
811 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 4]));
812 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 5]));
813 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 4]));
814 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 5]));
815 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 4]));
816 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 5]));
817 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 4]));
818 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 5]));
819 /// assert_eq!(multi_prod.next(), None);
820 /// ```
821 #[cfg(feature = "use_std")]
822 fn multi_cartesian_product(self) -> MultiProduct<<Self::Item as IntoIterator>::IntoIter>
823 where Self: Iterator + Sized,
824 Self::Item: IntoIterator,
825 <Self::Item as IntoIterator>::IntoIter: Clone,
826 <Self::Item as IntoIterator>::Item: Clone
827 {
828 adaptors::multi_cartesian_product(self)
829 }
830
831 /// Return an iterator adaptor that uses the passed-in closure to
832 /// optionally merge together consecutive elements.
833 ///
834 /// The closure `f` is passed two elements, `previous` and `current` and may
835 /// return either (1) `Ok(combined)` to merge the two values or
836 /// (2) `Err((previous', current'))` to indicate they can't be merged.
837 /// In (2), the value `previous'` is emitted by the iterator.
838 /// Either (1) `combined` or (2) `current'` becomes the previous value
839 /// when coalesce continues with the next pair of elements to merge. The
840 /// value that remains at the end is also emitted by the iterator.
841 ///
842 /// Iterator element type is `Self::Item`.
843 ///
844 /// This iterator is *fused*.
845 ///
846 /// ```
847 /// use itertools::Itertools;
848 ///
849 /// // sum same-sign runs together
850 /// let data = vec![-1., -2., -3., 3., 1., 0., -1.];
851 /// itertools::assert_equal(data.into_iter().coalesce(|x, y|
852 /// if (x >= 0.) == (y >= 0.) {
853 /// Ok(x + y)
854 /// } else {
855 /// Err((x, y))
856 /// }),
857 /// vec![-6., 4., -1.]);
858 /// ```
859 fn coalesce<F>(self, f: F) -> Coalesce<Self, F>
860 where Self: Sized,
861 F: FnMut(Self::Item, Self::Item)
862 -> Result<Self::Item, (Self::Item, Self::Item)>
863 {
864 adaptors::coalesce(self, f)
865 }
866
867 /// Remove duplicates from sections of consecutive identical elements.
868 /// If the iterator is sorted, all elements will be unique.
869 ///
870 /// Iterator element type is `Self::Item`.
871 ///
872 /// This iterator is *fused*.
873 ///
874 /// ```
875 /// use itertools::Itertools;
876 ///
877 /// let data = vec![1., 1., 2., 3., 3., 2., 2.];
878 /// itertools::assert_equal(data.into_iter().dedup(),
879 /// vec![1., 2., 3., 2.]);
880 /// ```
881 fn dedup(self) -> Dedup<Self>
882 where Self: Sized,
883 Self::Item: PartialEq,
884 {
885 adaptors::dedup(self)
886 }
887
888 /// Return an iterator adaptor that filters out elements that have
889 /// already been produced once during the iteration. Duplicates
890 /// are detected using hash and equality.
891 ///
892 /// Clones of visited elements are stored in a hash set in the
893 /// iterator.
894 ///
895 /// ```
896 /// use itertools::Itertools;
897 ///
898 /// let data = vec![10, 20, 30, 20, 40, 10, 50];
899 /// itertools::assert_equal(data.into_iter().unique(),
900 /// vec![10, 20, 30, 40, 50]);
901 /// ```
902 #[cfg(feature = "use_std")]
903 fn unique(self) -> Unique<Self>
904 where Self: Sized,
905 Self::Item: Clone + Eq + Hash
906 {
907 unique_impl::unique(self)
908 }
909
910 /// Return an iterator adaptor that filters out elements that have
911 /// already been produced once during the iteration.
912 ///
913 /// Duplicates are detected by comparing the key they map to
914 /// with the keying function `f` by hash and equality.
915 /// The keys are stored in a hash set in the iterator.
916 ///
917 /// ```
918 /// use itertools::Itertools;
919 ///
920 /// let data = vec!["a", "bb", "aa", "c", "ccc"];
921 /// itertools::assert_equal(data.into_iter().unique_by(|s| s.len()),
922 /// vec!["a", "bb", "ccc"]);
923 /// ```
924 #[cfg(feature = "use_std")]
925 fn unique_by<V, F>(self, f: F) -> UniqueBy<Self, V, F>
926 where Self: Sized,
927 V: Eq + Hash,
928 F: FnMut(&Self::Item) -> V
929 {
930 unique_impl::unique_by(self, f)
931 }
932
933 /// Return an iterator adaptor that borrows from this iterator and
934 /// takes items while the closure `accept` returns `true`.
935 ///
936 /// This adaptor can only be used on iterators that implement `PeekingNext`
937 /// like `.peekable()`, `put_back` and a few other collection iterators.
938 ///
939 /// The last and rejected element (first `false`) is still available when
940 /// `peeking_take_while` is done.
941 ///
942 ///
943 /// See also [`.take_while_ref()`](#method.take_while_ref)
944 /// which is a similar adaptor.
945 fn peeking_take_while<F>(&mut self, accept: F) -> PeekingTakeWhile<Self, F>
946 where Self: Sized + PeekingNext,
947 F: FnMut(&Self::Item) -> bool,
948 {
949 peeking_take_while::peeking_take_while(self, accept)
950 }
951
952 /// Return an iterator adaptor that borrows from a `Clone`-able iterator
953 /// to only pick off elements while the predicate `accept` returns `true`.
954 ///
955 /// It uses the `Clone` trait to restore the original iterator so that the
956 /// last and rejected element (first `false`) is still available when
957 /// `take_while_ref` is done.
958 ///
959 /// ```
960 /// use itertools::Itertools;
961 ///
962 /// let mut hexadecimals = "0123456789abcdef".chars();
963 ///
964 /// let decimals = hexadecimals.take_while_ref(|c| c.is_numeric())
965 /// .collect::<String>();
966 /// assert_eq!(decimals, "0123456789");
967 /// assert_eq!(hexadecimals.next(), Some('a'));
968 ///
969 /// ```
970 fn take_while_ref<F>(&mut self, accept: F) -> TakeWhileRef<Self, F>
971 where Self: Clone,
972 F: FnMut(&Self::Item) -> bool
973 {
974 adaptors::take_while_ref(self, accept)
975 }
976
977 /// Return an iterator adaptor that filters `Option<A>` iterator elements
978 /// and produces `A`. Stops on the first `None` encountered.
979 ///
980 /// Iterator element type is `A`, the unwrapped element.
981 ///
982 /// ```
983 /// use itertools::Itertools;
984 ///
985 /// // List all hexadecimal digits
986 /// itertools::assert_equal(
987 /// (0..).map(|i| std::char::from_digit(i, 16)).while_some(),
988 /// "0123456789abcdef".chars());
989 ///
990 /// ```
991 fn while_some<A>(self) -> WhileSome<Self>
992 where Self: Sized + Iterator<Item = Option<A>>
993 {
994 adaptors::while_some(self)
995 }
996
997 /// Return an iterator adaptor that iterates over the combinations of the
998 /// elements from an iterator.
999 ///
1000 /// Iterator element can be any homogeneous tuple of type `Self::Item` with
1001 /// size up to 4.
1002 ///
1003 /// ```
1004 /// use itertools::Itertools;
1005 ///
1006 /// let mut v = Vec::new();
1007 /// for (a, b) in (1..5).tuple_combinations() {
1008 /// v.push((a, b));
1009 /// }
1010 /// assert_eq!(v, vec![(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]);
1011 ///
1012 /// let mut it = (1..5).tuple_combinations();
1013 /// assert_eq!(Some((1, 2, 3)), it.next());
1014 /// assert_eq!(Some((1, 2, 4)), it.next());
1015 /// assert_eq!(Some((1, 3, 4)), it.next());
1016 /// assert_eq!(Some((2, 3, 4)), it.next());
1017 /// assert_eq!(None, it.next());
1018 ///
1019 /// // this requires a type hint
1020 /// let it = (1..5).tuple_combinations::<(_, _, _)>();
1021 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1022 ///
1023 /// // you can also specify the complete type
1024 /// use itertools::TupleCombinations;
1025 /// use std::ops::Range;
1026 ///
1027 /// let it: TupleCombinations<Range<u32>, (u32, u32, u32)> = (1..5).tuple_combinations();
1028 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1029 /// ```
1030 fn tuple_combinations<T>(self) -> TupleCombinations<Self, T>
1031 where Self: Sized + Clone,
1032 Self::Item: Clone,
1033 T: adaptors::HasCombination<Self>,
1034 {
1035 adaptors::tuple_combinations(self)
1036 }
1037
1038 /// Return an iterator adaptor that iterates over the `n`-length combinations of
1039 /// the elements from an iterator.
1040 ///
1041 /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1042 /// and clones the iterator elements.
1043 ///
1044 /// ```
1045 /// use itertools::Itertools;
1046 ///
1047 /// let it = (1..5).combinations(3);
1048 /// itertools::assert_equal(it, vec![
1049 /// vec![1, 2, 3],
1050 /// vec![1, 2, 4],
1051 /// vec![1, 3, 4],
1052 /// vec![2, 3, 4],
1053 /// ]);
1054 /// ```
1055 #[cfg(feature = "use_std")]
1056 fn combinations(self, n: usize) -> Combinations<Self>
1057 where Self: Sized,
1058 Self::Item: Clone
1059 {
1060 combinations::combinations(self, n)
1061 }
1062
1063 /// Return an iterator adaptor that pads the sequence to a minimum length of
1064 /// `min` by filling missing elements using a closure `f`.
1065 ///
1066 /// Iterator element type is `Self::Item`.
1067 ///
1068 /// ```
1069 /// use itertools::Itertools;
1070 ///
1071 /// let it = (0..5).pad_using(10, |i| 2*i);
1072 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 10, 12, 14, 16, 18]);
1073 ///
1074 /// let it = (0..10).pad_using(5, |i| 2*i);
1075 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1076 ///
1077 /// let it = (0..5).pad_using(10, |i| 2*i).rev();
1078 /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]);
1079 /// ```
1080 fn pad_using<F>(self, min: usize, f: F) -> PadUsing<Self, F>
1081 where Self: Sized,
1082 F: FnMut(usize) -> Self::Item
1083 {
1084 pad_tail::pad_using(self, min, f)
1085 }
1086
1087 /// Unravel a nested iterator.
1088 ///
1089 /// This is more or less equivalent to `.flat_map` with an identity
1090 /// function.
1091 ///
1092 /// ```
1093 /// use itertools::Itertools;
1094 ///
1095 /// let data = vec![vec![1, 2, 3], vec![4, 5, 6]];
1096 /// let flattened = data.iter().flatten();
1097 ///
1098 /// itertools::assert_equal(flattened, &[1, 2, 3, 4, 5, 6]);
1099 /// ```
1100 fn flatten(self) -> Flatten<Self, <Self::Item as IntoIterator>::IntoIter>
1101 where Self: Sized,
1102 Self::Item: IntoIterator
1103 {
1104 adaptors::flatten(self)
1105 }
1106
1107 /// Return an iterator adaptor that wraps each element in a `Position` to
1108 /// ease special-case handling of the first or last elements.
1109 ///
1110 /// Iterator element type is
1111 /// [`Position<Self::Item>`](enum.Position.html)
1112 ///
1113 /// ```
1114 /// use itertools::{Itertools, Position};
1115 ///
1116 /// let it = (0..4).with_position();
1117 /// itertools::assert_equal(it,
1118 /// vec![Position::First(0),
1119 /// Position::Middle(1),
1120 /// Position::Middle(2),
1121 /// Position::Last(3)]);
1122 ///
1123 /// let it = (0..1).with_position();
1124 /// itertools::assert_equal(it, vec![Position::Only(0)]);
1125 /// ```
1126 fn with_position(self) -> WithPosition<Self>
1127 where Self: Sized,
1128 {
1129 with_position::with_position(self)
1130 }
1131
1132 /// Return an iterator adaptor that yields the indices of all elements
1133 /// satisfying a predicate, counted from the start of the iterator.
1134 ///
1135 /// Equivalent to `iter.enumerate().filter(|(_, v)| predicate(v)).map(|(i, _)| i)`.
1136 ///
1137 /// ```
1138 /// use itertools::Itertools;
1139 ///
1140 /// let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
1141 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 0), vec![1, 4, 5]);
1142 ///
1143 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]);
1144 /// ```
1145 fn positions<P>(self, predicate: P) -> Positions<Self, P>
1146 where Self: Sized,
1147 P: FnMut(Self::Item) -> bool,
1148 {
1149 adaptors::positions(self, predicate)
1150 }
1151
1152 /// Return an iterator adaptor that applies a mutating function
1153 /// to each element before yielding it.
1154 ///
1155 /// ```
1156 /// use itertools::Itertools;
1157 ///
1158 /// let input = vec![vec![1], vec![3, 2, 1]];
1159 /// let it = input.into_iter().update(|mut v| v.push(0));
1160 /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]);
1161 /// ```
1162 fn update<F>(self, updater: F) -> Update<Self, F>
1163 where Self: Sized,
1164 F: FnMut(&mut Self::Item),
1165 {
1166 adaptors::update(self, updater)
1167 }
1168
1169 // non-adaptor methods
1170 /// Advances the iterator and returns the next items grouped in a tuple of
1171 /// a specific size (up to 4).
1172 ///
1173 /// If there are enough elements to be grouped in a tuple, then the tuple is
1174 /// returned inside `Some`, otherwise `None` is returned.
1175 ///
1176 /// ```
1177 /// use itertools::Itertools;
1178 ///
1179 /// let mut iter = 1..5;
1180 ///
1181 /// assert_eq!(Some((1, 2)), iter.next_tuple());
1182 /// ```
1183 fn next_tuple<T>(&mut self) -> Option<T>
1184 where Self: Sized + Iterator<Item = T::Item>,
1185 T: tuple_impl::TupleCollect
1186 {
1187 T::collect_from_iter_no_buf(self)
1188 }
1189
1190 /// Collects all items from the iterator into a tuple of a specific size
1191 /// (up to 4).
1192 ///
1193 /// If the number of elements inside the iterator is **exactly** equal to
1194 /// the tuple size, then the tuple is returned inside `Some`, otherwise
1195 /// `None` is returned.
1196 ///
1197 /// ```
1198 /// use itertools::Itertools;
1199 ///
1200 /// let iter = 1..3;
1201 ///
1202 /// if let Some((x, y)) = iter.collect_tuple() {
1203 /// assert_eq!((x, y), (1, 2))
1204 /// } else {
1205 /// panic!("Expected two elements")
1206 /// }
1207 /// ```
1208 fn collect_tuple<T>(mut self) -> Option<T>
1209 where Self: Sized + Iterator<Item = T::Item>,
1210 T: tuple_impl::TupleCollect
1211 {
1212 match self.next_tuple() {
1213 elt @ Some(_) => match self.next() {
1214 Some(_) => None,
1215 None => elt,
1216 },
1217 _ => None
1218 }
1219 }
1220
1221
1222 /// Find the position and value of the first element satisfying a predicate.
1223 ///
1224 /// The iterator is not advanced past the first element found.
1225 ///
1226 /// ```
1227 /// use itertools::Itertools;
1228 ///
1229 /// let text = "Hα";
1230 /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α')));
1231 /// ```
1232 fn find_position<P>(&mut self, mut pred: P) -> Option<(usize, Self::Item)>
1233 where P: FnMut(&Self::Item) -> bool
1234 {
1235 let mut index = 0usize;
1236 for elt in self {
1237 if pred(&elt) {
1238 return Some((index, elt));
1239 }
1240 index += 1;
1241 }
1242 None
1243 }
1244
1245 /// Check whether all elements compare equal.
1246 ///
1247 /// Empty iterators are considered to have equal elements:
1248 ///
1249 /// ```
1250 /// use itertools::Itertools;
1251 ///
1252 /// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
1253 /// assert!(!data.iter().all_equal());
1254 /// assert!(data[0..3].iter().all_equal());
1255 /// assert!(data[3..5].iter().all_equal());
1256 /// assert!(data[5..8].iter().all_equal());
1257 ///
1258 /// let data : Option<usize> = None;
1259 /// assert!(data.into_iter().all_equal());
1260 /// ```
1261 fn all_equal(&mut self) -> bool
1262 where Self::Item: PartialEq,
1263 {
1264 self.dedup().nth(1).is_none()
1265 }
1266
1267 /// Consume the first `n` elements from the iterator eagerly,
1268 /// and return the same iterator again.
1269 ///
1270 /// It works similarly to *.skip(* `n` *)* except it is eager and
1271 /// preserves the iterator type.
1272 ///
1273 /// ```
1274 /// use itertools::Itertools;
1275 ///
1276 /// let mut iter = "αβγ".chars().dropping(2);
1277 /// itertools::assert_equal(iter, "γ".chars());
1278 /// ```
1279 ///
1280 /// *Fusing notes: if the iterator is exhausted by dropping,
1281 /// the result of calling `.next()` again depends on the iterator implementation.*
1282 fn dropping(mut self, n: usize) -> Self
1283 where Self: Sized
1284 {
1285 if n > 0 {
1286 self.nth(n - 1);
1287 }
1288 self
1289 }
1290
1291 /// Consume the last `n` elements from the iterator eagerly,
1292 /// and return the same iterator again.
1293 ///
1294 /// This is only possible on double ended iterators. `n` may be
1295 /// larger than the number of elements.
1296 ///
1297 /// Note: This method is eager, dropping the back elements immediately and
1298 /// preserves the iterator type.
1299 ///
1300 /// ```
1301 /// use itertools::Itertools;
1302 ///
1303 /// let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
1304 /// itertools::assert_equal(init, vec![0, 3, 6]);
1305 /// ```
1306 fn dropping_back(mut self, n: usize) -> Self
1307 where Self: Sized,
1308 Self: DoubleEndedIterator
1309 {
1310 if n > 0 {
1311 (&mut self).rev().nth(n - 1);
1312 }
1313 self
1314 }
1315
1316 /// Run the closure `f` eagerly on each element of the iterator.
1317 ///
1318 /// Consumes the iterator until its end.
1319 ///
1320 /// ```
1321 /// use std::sync::mpsc::channel;
1322 /// use itertools::Itertools;
1323 ///
1324 /// let (tx, rx) = channel();
1325 ///
1326 /// // use .foreach() to apply a function to each value -- sending it
1327 /// (0..5).map(|x| x * 2 + 1).foreach(|x| { tx.send(x).unwrap(); } );
1328 ///
1329 /// drop(tx);
1330 ///
1331 /// itertools::assert_equal(rx.iter(), vec![1, 3, 5, 7, 9]);
1332 /// ```
1333 fn foreach<F>(self, mut f: F)
1334 where F: FnMut(Self::Item),
1335 Self: Sized,
1336 {
1337 self.fold((), move |(), element| f(element))
1338 }
1339
1340 /// Combine all an iterator's elements into one element by using `Extend`.
1341 ///
1342 /// This combinator will extend the first item with each of the rest of the
1343 /// items of the iterator. If the iterator is empty, the default value of
1344 /// `I::Item` is returned.
1345 ///
1346 /// ```rust
1347 /// use itertools::Itertools;
1348 ///
1349 /// let input = vec![vec![1], vec![2, 3], vec![4, 5, 6]];
1350 /// assert_eq!(input.into_iter().concat(),
1351 /// vec![1, 2, 3, 4, 5, 6]);
1352 /// ```
1353 fn concat(self) -> Self::Item
1354 where Self: Sized,
1355 Self::Item: Extend<<<Self as Iterator>::Item as IntoIterator>::Item> + IntoIterator + Default
1356 {
1357 concat(self)
1358 }
1359
1360 /// `.collect_vec()` is simply a type specialization of `.collect()`,
1361 /// for convenience.
1362 #[cfg(feature = "use_std")]
1363 fn collect_vec(self) -> Vec<Self::Item>
1364 where Self: Sized
1365 {
1366 self.collect()
1367 }
1368
1369 /// Assign to each reference in `self` from the `from` iterator,
1370 /// stopping at the shortest of the two iterators.
1371 ///
1372 /// The `from` iterator is queried for its next element before the `self`
1373 /// iterator, and if either is exhausted the method is done.
1374 ///
1375 /// Return the number of elements written.
1376 ///
1377 /// ```
1378 /// use itertools::Itertools;
1379 ///
1380 /// let mut xs = [0; 4];
1381 /// xs.iter_mut().set_from(1..);
1382 /// assert_eq!(xs, [1, 2, 3, 4]);
1383 /// ```
1384 #[inline]
1385 fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize
1386 where Self: Iterator<Item = &'a mut A>,
1387 J: IntoIterator<Item = A>
1388 {
1389 let mut count = 0;
1390 for elt in from {
1391 match self.next() {
1392 None => break,
1393 Some(ptr) => *ptr = elt,
1394 }
1395 count += 1;
1396 }
1397 count
1398 }
1399
1400 /// Combine all iterator elements into one String, seperated by `sep`.
1401 ///
1402 /// Use the `Display` implementation of each element.
1403 ///
1404 /// ```
1405 /// use itertools::Itertools;
1406 ///
1407 /// assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
1408 /// assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");
1409 /// ```
1410 #[cfg(feature = "use_std")]
1411 fn join(&mut self, sep: &str) -> String
1412 where Self::Item: std::fmt::Display
1413 {
1414 match self.next() {
1415 None => String::new(),
1416 Some(first_elt) => {
1417 // estimate lower bound of capacity needed
1418 let (lower, _) = self.size_hint();
1419 let mut result = String::with_capacity(sep.len() * lower);
1420 write!(&mut result, "{}", first_elt).unwrap();
1421 for elt in self {
1422 result.push_str(sep);
1423 write!(&mut result, "{}", elt).unwrap();
1424 }
1425 result
1426 }
1427 }
1428 }
1429
1430 /// Format all iterator elements, separated by `sep`.
1431 ///
1432 /// All elements are formatted (any formatting trait)
1433 /// with `sep` inserted between each element.
1434 ///
1435 /// **Panics** if the formatter helper is formatted more than once.
1436 ///
1437 /// ```
1438 /// use itertools::Itertools;
1439 ///
1440 /// let data = [1.1, 2.71828, -3.];
1441 /// assert_eq!(
1442 /// format!("{:.2}", data.iter().format(", ")),
1443 /// "1.10, 2.72, -3.00");
1444 /// ```
1445 fn format(self, sep: &str) -> Format<Self>
1446 where Self: Sized,
1447 {
1448 format::new_format_default(self, sep)
1449 }
1450
1451 /// Format all iterator elements, separated by `sep`.
1452 ///
1453 /// This is a customizable version of `.format()`.
1454 ///
1455 /// The supplied closure `format` is called once per iterator element,
1456 /// with two arguments: the element and a callback that takes a
1457 /// `&Display` value, i.e. any reference to type that implements `Display`.
1458 ///
1459 /// Using `&format_args!(...)` is the most versatile way to apply custom
1460 /// element formatting. The callback can be called multiple times if needed.
1461 ///
1462 /// **Panics** if the formatter helper is formatted more than once.
1463 ///
1464 /// ```
1465 /// use itertools::Itertools;
1466 ///
1467 /// let data = [1.1, 2.71828, -3.];
1468 /// let data_formatter = data.iter().format_with(", ", |elt, f| f(&format_args!("{:.2}", elt)));
1469 /// assert_eq!(format!("{}", data_formatter),
1470 /// "1.10, 2.72, -3.00");
1471 ///
1472 /// // .format_with() is recursively composable
1473 /// let matrix = [[1., 2., 3.],
1474 /// [4., 5., 6.]];
1475 /// let matrix_formatter = matrix.iter().format_with("\n", |row, f| {
1476 /// f(&row.iter().format_with(", ", |elt, g| g(&elt)))
1477 /// });
1478 /// assert_eq!(format!("{}", matrix_formatter),
1479 /// "1, 2, 3\n4, 5, 6");
1480 ///
1481 ///
1482 /// ```
1483 fn format_with<F>(self, sep: &str, format: F) -> FormatWith<Self, F>
1484 where Self: Sized,
1485 F: FnMut(Self::Item, &mut FnMut(&fmt::Display) -> fmt::Result) -> fmt::Result,
1486 {
1487 format::new_format(self, sep, format)
1488 }
1489
1490 /// Fold `Result` values from an iterator.
1491 ///
1492 /// Only `Ok` values are folded. If no error is encountered, the folded
1493 /// value is returned inside `Ok`. Otherwise, the operation terminates
1494 /// and returns the first `Err` value it encounters. No iterator elements are
1495 /// consumed after the first error.
1496 ///
1497 /// The first accumulator value is the `start` parameter.
1498 /// Each iteration passes the accumulator value and the next value inside `Ok`
1499 /// to the fold function `f` and its return value becomes the new accumulator value.
1500 ///
1501 /// For example the sequence *Ok(1), Ok(2), Ok(3)* will result in a
1502 /// computation like this:
1503 ///
1504 /// ```ignore
1505 /// let mut accum = start;
1506 /// accum = f(accum, 1);
1507 /// accum = f(accum, 2);
1508 /// accum = f(accum, 3);
1509 /// ```
1510 ///
1511 /// With a `start` value of 0 and an addition as folding function,
1512 /// this effetively results in *((0 + 1) + 2) + 3*
1513 ///
1514 /// ```
1515 /// use std::ops::Add;
1516 /// use itertools::Itertools;
1517 ///
1518 /// let values = [1, 2, -2, -1, 2, 1];
1519 /// assert_eq!(
1520 /// values.iter()
1521 /// .map(Ok::<_, ()>)
1522 /// .fold_results(0, Add::add),
1523 /// Ok(3)
1524 /// );
1525 /// assert!(
1526 /// values.iter()
1527 /// .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
1528 /// .fold_results(0, Add::add)
1529 /// .is_err()
1530 /// );
1531 /// ```
1532 fn fold_results<A, E, B, F>(&mut self, mut start: B, mut f: F) -> Result<B, E>
1533 where Self: Iterator<Item = Result<A, E>>,
1534 F: FnMut(B, A) -> B
1535 {
1536 for elt in self {
1537 match elt {
1538 Ok(v) => start = f(start, v),
1539 Err(u) => return Err(u),
1540 }
1541 }
1542 Ok(start)
1543 }
1544
1545 /// Fold `Option` values from an iterator.
1546 ///
1547 /// Only `Some` values are folded. If no `None` is encountered, the folded
1548 /// value is returned inside `Some`. Otherwise, the operation terminates
1549 /// and returns `None`. No iterator elements are consumed after the `None`.
1550 ///
1551 /// This is the `Option` equivalent to `fold_results`.
1552 ///
1553 /// ```
1554 /// use std::ops::Add;
1555 /// use itertools::Itertools;
1556 ///
1557 /// let mut values = vec![Some(1), Some(2), Some(-2)].into_iter();
1558 /// assert_eq!(values.fold_options(5, Add::add), Some(5 + 1 + 2 - 2));
1559 ///
1560 /// let mut more_values = vec![Some(2), None, Some(0)].into_iter();
1561 /// assert!(more_values.fold_options(0, Add::add).is_none());
1562 /// assert_eq!(more_values.next().unwrap(), Some(0));
1563 /// ```
1564 fn fold_options<A, B, F>(&mut self, mut start: B, mut f: F) -> Option<B>
1565 where Self: Iterator<Item = Option<A>>,
1566 F: FnMut(B, A) -> B
1567 {
1568 for elt in self {
1569 match elt {
1570 Some(v) => start = f(start, v),
1571 None => return None,
1572 }
1573 }
1574 Some(start)
1575 }
1576
1577 /// Accumulator of the elements in the iterator.
1578 ///
1579 /// Like `.fold()`, without a base case. If the iterator is
1580 /// empty, return `None`. With just one element, return it.
1581 /// Otherwise elements are accumulated in sequence using the closure `f`.
1582 ///
1583 /// ```
1584 /// use itertools::Itertools;
1585 ///
1586 /// assert_eq!((0..10).fold1(|x, y| x + y).unwrap_or(0), 45);
1587 /// assert_eq!((0..0).fold1(|x, y| x * y), None);
1588 /// ```
1589 fn fold1<F>(mut self, f: F) -> Option<Self::Item>
1590 where F: FnMut(Self::Item, Self::Item) -> Self::Item,
1591 Self: Sized,
1592 {
1593 self.next().map(move |x| self.fold(x, f))
1594 }
1595
1596 /// An iterator method that applies a function, producing a single, final value.
1597 ///
1598 /// `fold_while()` is basically equivalent to `fold()` but with additional support for
1599 /// early exit via short-circuiting.
1600 ///
1601 /// ```
1602 /// use itertools::Itertools;
1603 /// use itertools::FoldWhile::{Continue, Done};
1604 ///
1605 /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1606 ///
1607 /// let mut result = 0;
1608 ///
1609 /// // for loop:
1610 /// for i in &numbers {
1611 /// if *i > 5 {
1612 /// break;
1613 /// }
1614 /// result = result + i;
1615 /// }
1616 ///
1617 /// // fold:
1618 /// let result2 = numbers.iter().fold(0, |acc, x| {
1619 /// if *x > 5 { acc } else { acc + x }
1620 /// });
1621 ///
1622 /// // fold_while:
1623 /// let result3 = numbers.iter().fold_while(0, |acc, x| {
1624 /// if *x > 5 { Done(acc) } else { Continue(acc + x) }
1625 /// }).into_inner();
1626 ///
1627 /// // they're the same
1628 /// assert_eq!(result, result2);
1629 /// assert_eq!(result2, result3);
1630 /// ```
1631 ///
1632 /// The big difference between the computations of `result2` and `result3` is that while
1633 /// `fold()` called the provided closure for every item of the callee iterator,
1634 /// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`.
1635 fn fold_while<B, F>(&mut self, init: B, mut f: F) -> FoldWhile<B>
1636 where Self: Sized,
1637 F: FnMut(B, Self::Item) -> FoldWhile<B>
1638 {
1639 let mut acc = init;
1640 while let Some(item) = self.next() {
1641 match f(acc, item) {
1642 FoldWhile::Continue(res) => acc = res,
1643 res @ FoldWhile::Done(_) => return res,
1644 }
1645 }
1646 FoldWhile::Continue(acc)
1647 }
1648
1649 /// Collect all iterator elements into a sorted vector in ascending order.
1650 ///
1651 /// **Note:** This consumes the entire iterator, uses the
1652 /// `slice::sort_by()` method and returns the sorted vector.
1653 ///
1654 /// ```
1655 /// use itertools::Itertools;
1656 ///
1657 /// // sort the letters of the text in ascending order
1658 /// let text = "bdacfe";
1659 /// itertools::assert_equal(text.chars().sorted(),
1660 /// "abcdef".chars());
1661 /// ```
1662 #[cfg(feature = "use_std")]
1663 fn sorted(self) -> Vec<Self::Item>
1664 where Self: Sized,
1665 Self::Item: Ord
1666 {
1667 self.sorted_by(Ord::cmp)
1668 }
1669
1670 /// Collect all iterator elements into a sorted vector.
1671 ///
1672 /// **Note:** This consumes the entire iterator, uses the
1673 /// `slice::sort_by()` method and returns the sorted vector.
1674 ///
1675 /// ```
1676 /// use itertools::Itertools;
1677 ///
1678 /// // sort people in descending order by age
1679 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
1680 ///
1681 /// let oldest_people_first = people
1682 /// .into_iter()
1683 /// .sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
1684 /// .into_iter()
1685 /// .map(|(person, _age)| person);
1686 ///
1687 /// itertools::assert_equal(oldest_people_first,
1688 /// vec!["Jill", "Jack", "Jane", "John"]);
1689 /// ```
1690 #[cfg(feature = "use_std")]
1691 fn sorted_by<F>(self, cmp: F) -> Vec<Self::Item>
1692 where Self: Sized,
1693 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1694 {
1695 let mut v: Vec<Self::Item> = self.collect();
1696
1697 v.sort_by(cmp);
1698 v
1699 }
1700
1701 /// Collect all iterator elements into a sorted vector.
1702 ///
1703 /// **Note:** This consumes the entire iterator, uses the
1704 /// `slice::sort_by_key()` method and returns the sorted vector.
1705 ///
1706 /// ```
1707 /// use itertools::Itertools;
1708 ///
1709 /// // sort people in descending order by age
1710 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
1711 ///
1712 /// let oldest_people_first = people
1713 /// .into_iter()
1714 /// .sorted_by_key(|x| -x.1)
1715 /// .into_iter()
1716 /// .map(|(person, _age)| person);
1717 ///
1718 /// itertools::assert_equal(oldest_people_first,
1719 /// vec!["Jill", "Jack", "Jane", "John"]);
1720 /// ```
1721 #[cfg(feature = "use_std")]
1722 fn sorted_by_key<K, F>(self, f: F) -> Vec<Self::Item>
1723 where Self: Sized,
1724 K: Ord,
1725 F: FnMut(&Self::Item) -> K,
1726 {
1727 let mut v: Vec<Self::Item> = self.collect();
1728
1729 v.sort_by_key(f);
1730 v
1731 }
1732
1733 /// Collect all iterator elements into one of two
1734 /// partitions. Unlike `Iterator::partition`, each partition may
1735 /// have a distinct type.
1736 ///
1737 /// ```
1738 /// use itertools::{Itertools, Either};
1739 ///
1740 /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
1741 ///
1742 /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
1743 /// .into_iter()
1744 /// .partition_map(|r| {
1745 /// match r {
1746 /// Ok(v) => Either::Left(v),
1747 /// Err(v) => Either::Right(v),
1748 /// }
1749 /// });
1750 ///
1751 /// assert_eq!(successes, [1, 2]);
1752 /// assert_eq!(failures, [false, true]);
1753 /// ```
1754 fn partition_map<A, B, F, L, R>(self, predicate: F) -> (A, B)
1755 where Self: Sized,
1756 F: Fn(Self::Item) -> Either<L, R>,
1757 A: Default + Extend<L>,
1758 B: Default + Extend<R>,
1759 {
1760 let mut left = A::default();
1761 let mut right = B::default();
1762
1763 for val in self {
1764 match predicate(val) {
1765 Either::Left(v) => left.extend(Some(v)),
1766 Either::Right(v) => right.extend(Some(v)),
1767 }
1768 }
1769
1770 (left, right)
1771 }
1772
1773 /// Return the minimum and maximum elements in the iterator.
1774 ///
1775 /// The return type `MinMaxResult` is an enum of three variants:
1776 ///
1777 /// - `NoElements` if the iterator is empty.
1778 /// - `OneElement(x)` if the iterator has exactly one element.
1779 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
1780 /// values are equal if and only if there is more than one
1781 /// element in the iterator and all elements are equal.
1782 ///
1783 /// On an iterator of length `n`, `minmax` does `1.5 * n` comparisons,
1784 /// and so is faster than calling `min` and `max` separately which does
1785 /// `2 * n` comparisons.
1786 ///
1787 /// # Examples
1788 ///
1789 /// ```
1790 /// use itertools::Itertools;
1791 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
1792 ///
1793 /// let a: [i32; 0] = [];
1794 /// assert_eq!(a.iter().minmax(), NoElements);
1795 ///
1796 /// let a = [1];
1797 /// assert_eq!(a.iter().minmax(), OneElement(&1));
1798 ///
1799 /// let a = [1, 2, 3, 4, 5];
1800 /// assert_eq!(a.iter().minmax(), MinMax(&1, &5));
1801 ///
1802 /// let a = [1, 1, 1, 1];
1803 /// assert_eq!(a.iter().minmax(), MinMax(&1, &1));
1804 /// ```
1805 ///
1806 /// The elements can be floats but no particular result is guaranteed
1807 /// if an element is NaN.
1808 fn minmax(self) -> MinMaxResult<Self::Item>
1809 where Self: Sized, Self::Item: PartialOrd
1810 {
1811 minmax::minmax_impl(self, |_| (), |x, y, _, _| x < y)
1812 }
1813
1814 /// Return the minimum and maximum element of an iterator, as determined by
1815 /// the specified function.
1816 ///
1817 /// The return value is a variant of `MinMaxResult` like for `minmax()`.
1818 ///
1819 /// For the minimum, the first minimal element is returned. For the maximum,
1820 /// the last maximal element wins. This matches the behavior of the standard
1821 /// `Iterator::min()` and `Iterator::max()` methods.
1822 ///
1823 /// The keys can be floats but no particular result is guaranteed
1824 /// if a key is NaN.
1825 fn minmax_by_key<K, F>(self, key: F) -> MinMaxResult<Self::Item>
1826 where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K
1827 {
1828 minmax::minmax_impl(self, key, |_, _, xk, yk| xk < yk)
1829 }
1830
1831 /// Return the minimum and maximum element of an iterator, as determined by
1832 /// the specified comparison function.
1833 ///
1834 /// The return value is a variant of `MinMaxResult` like for `minmax()`.
1835 ///
1836 /// For the minimum, the first minimal element is returned. For the maximum,
1837 /// the last maximal element wins. This matches the behavior of the standard
1838 /// `Iterator::min()` and `Iterator::max()` methods.
1839 fn minmax_by<F>(self, mut compare: F) -> MinMaxResult<Self::Item>
1840 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering
1841 {
1842 minmax::minmax_impl(
1843 self,
1844 |_| (),
1845 |x, y, _, _| Ordering::Less == compare(x, y)
1846 )
1847 }
1848 }
1849
1850 impl<T: ?Sized> Itertools for T where T: Iterator { }
1851
1852 /// Return `true` if both iterables produce equal sequences
1853 /// (elements pairwise equal and sequences of the same length),
1854 /// `false` otherwise.
1855 ///
1856 /// This is an `IntoIterator` enabled function that is similar to the standard
1857 /// library method `Iterator::eq`.
1858 ///
1859 /// ```
1860 /// assert!(itertools::equal(vec![1, 2, 3], 1..4));
1861 /// assert!(!itertools::equal(&[0, 0], &[0, 0, 0]));
1862 /// ```
1863 pub fn equal<I, J>(a: I, b: J) -> bool
1864 where I: IntoIterator,
1865 J: IntoIterator,
1866 I::Item: PartialEq<J::Item>
1867 {
1868 let mut ia = a.into_iter();
1869 let mut ib = b.into_iter();
1870 loop {
1871 match ia.next() {
1872 Some(x) => match ib.next() {
1873 Some(y) => if x != y { return false; },
1874 None => return false,
1875 },
1876 None => return ib.next().is_none()
1877 }
1878 }
1879 }
1880
1881 /// Assert that two iterables produce equal sequences, with the same
1882 /// semantics as *equal(a, b)*.
1883 ///
1884 /// **Panics** on assertion failure with a message that shows the
1885 /// two iteration elements.
1886 ///
1887 /// ```ignore
1888 /// assert_equal("exceed".split('c'), "excess".split('c'));
1889 /// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1',
1890 /// ```
1891 pub fn assert_equal<I, J>(a: I, b: J)
1892 where I: IntoIterator,
1893 J: IntoIterator,
1894 I::Item: fmt::Debug + PartialEq<J::Item>,
1895 J::Item: fmt::Debug,
1896 {
1897 let mut ia = a.into_iter();
1898 let mut ib = b.into_iter();
1899 let mut i = 0;
1900 loop {
1901 match (ia.next(), ib.next()) {
1902 (None, None) => return,
1903 (a, b) => {
1904 let equal = match (&a, &b) {
1905 (&Some(ref a), &Some(ref b)) => a == b,
1906 _ => false,
1907 };
1908 assert!(equal, "Failed assertion {a:?} == {b:?} for iteration {i}",
1909 i=i, a=a, b=b);
1910 i += 1;
1911 }
1912 }
1913 }
1914 }
1915
1916 /// Partition a sequence using predicate `pred` so that elements
1917 /// that map to `true` are placed before elements which map to `false`.
1918 ///
1919 /// The order within the partitions is arbitrary.
1920 ///
1921 /// Return the index of the split point.
1922 ///
1923 /// ```
1924 /// use itertools::partition;
1925 ///
1926 /// # // use repeated numbers to not promise any ordering
1927 /// let mut data = [7, 1, 1, 7, 1, 1, 7];
1928 /// let split_index = partition(&mut data, |elt| *elt >= 3);
1929 ///
1930 /// assert_eq!(data, [7, 7, 7, 1, 1, 1, 1]);
1931 /// assert_eq!(split_index, 3);
1932 /// ```
1933 pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize
1934 where I: IntoIterator<Item = &'a mut A>,
1935 I::IntoIter: DoubleEndedIterator,
1936 F: FnMut(&A) -> bool
1937 {
1938 let mut split_index = 0;
1939 let mut iter = iter.into_iter();
1940 'main: while let Some(front) = iter.next() {
1941 if !pred(front) {
1942 loop {
1943 match iter.next_back() {
1944 Some(back) => if pred(back) {
1945 std::mem::swap(front, back);
1946 break;
1947 },
1948 None => break 'main,
1949 }
1950 }
1951 }
1952 split_index += 1;
1953 }
1954 split_index
1955 }
1956
1957 /// An enum used for controlling the execution of `.fold_while()`.
1958 ///
1959 /// See [`.fold_while()`](trait.Itertools.html#method.fold_while) for more information.
1960 #[derive(Copy, Clone, Debug)]
1961 pub enum FoldWhile<T> {
1962 /// Continue folding with this value
1963 Continue(T),
1964 /// Fold is complete and will return this value
1965 Done(T),
1966 }
1967
1968 impl<T> FoldWhile<T> {
1969 /// Return the value in the continue or done.
1970 pub fn into_inner(self) -> T {
1971 match self {
1972 FoldWhile::Continue(x) | FoldWhile::Done(x) => x,
1973 }
1974 }
1975
1976 /// Return true if `self` is `Done`, false if it is `Continue`.
1977 pub fn is_done(&self) -> bool {
1978 match *self {
1979 FoldWhile::Continue(_) => false,
1980 FoldWhile::Done(_) => true,
1981 }
1982 }
1983 }