diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 143ac2b6d..31fd24293 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,7 @@ jobs: steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@1.36.0 + - run: cargo fmt --all -- --check - run: cargo check --no-default-features - run: cargo check --no-default-features --features "use_alloc" - run: cargo check diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index 06eb57a17..000000000 --- a/.rustfmt.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Temporarily disable rustfmt completely to avoid conflicts of newly formatted -# code with old PRs. -ignore = ["/"] diff --git a/benches/bench1.rs b/benches/bench1.rs index 71278d17b..084567177 100644 --- a/benches/bench1.rs +++ b/benches/bench1.rs @@ -1,10 +1,10 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use itertools::Itertools; use itertools::free::cloned; use itertools::iproduct; +use itertools::Itertools; -use std::iter::repeat; use std::cmp; +use std::iter::repeat; use std::ops::{Add, Range}; mod extra; @@ -15,8 +15,10 @@ fn slice_iter(c: &mut Criterion) { let xs: Vec<_> = repeat(1i32).take(20).collect(); c.bench_function("slice iter", move |b| { - b.iter(|| for elt in xs.iter() { - black_box(elt); + b.iter(|| { + for elt in xs.iter() { + black_box(elt); + } }) }); } @@ -25,8 +27,10 @@ fn slice_iter_rev(c: &mut Criterion) { let xs: Vec<_> = repeat(1i32).take(20).collect(); c.bench_function("slice iter rev", move |b| { - b.iter(|| for elt in xs.iter().rev() { - black_box(elt); + b.iter(|| { + for elt in xs.iter().rev() { + black_box(elt); + } }) }); } @@ -307,10 +311,10 @@ fn zip_unchecked_counted_loop(c: &mut Criterion) { let len = cmp::min(xs.len(), ys.len()); for i in 0..len { unsafe { - let x = *xs.get_unchecked(i); - let y = *ys.get_unchecked(i); - black_box(x); - black_box(y); + let x = *xs.get_unchecked(i); + let y = *ys.get_unchecked(i); + black_box(x); + black_box(y); } } }) @@ -329,9 +333,9 @@ fn zipdot_i32_unchecked_counted_loop(c: &mut Criterion) { let mut s = 0i32; for i in 0..len { unsafe { - let x = *xs.get_unchecked(i); - let y = *ys.get_unchecked(i); - s += x * y; + let x = *xs.get_unchecked(i); + let y = *ys.get_unchecked(i); + s += x * y; } } s @@ -351,9 +355,9 @@ fn zipdot_f32_unchecked_counted_loop(c: &mut Criterion) { let mut s = 0f32; for i in 0..len { unsafe { - let x = *xs.get_unchecked(i); - let y = *ys.get_unchecked(i); - s += x * y; + let x = *xs.get_unchecked(i); + let y = *ys.get_unchecked(i); + s += x * y; } } s @@ -374,12 +378,12 @@ fn zip_unchecked_counted_loop3(c: &mut Criterion) { let len = cmp::min(xs.len(), cmp::min(ys.len(), zs.len())); for i in 0..len { unsafe { - let x = *xs.get_unchecked(i); - let y = *ys.get_unchecked(i); - let z = *zs.get_unchecked(i); - black_box(x); - black_box(y); - black_box(z); + let x = *xs.get_unchecked(i); + let y = *ys.get_unchecked(i); + let z = *zs.get_unchecked(i); + black_box(x); + black_box(y); + black_box(z); } } }) @@ -464,11 +468,7 @@ fn equal(c: &mut Criterion) { let alpha = black_box(&data[1..]); let beta = black_box(&data[..l - 1]); - c.bench_function("equal", move |b| { - b.iter(|| { - itertools::equal(alpha, beta) - }) - }); + c.bench_function("equal", move |b| b.iter(|| itertools::equal(alpha, beta))); } fn merge_default(c: &mut Criterion) { @@ -493,9 +493,7 @@ fn merge_default(c: &mut Criterion) { let data2 = black_box(data2); c.bench_function("merge default", move |b| { - b.iter(|| { - data1.iter().merge(&data2).count() - }) + b.iter(|| data1.iter().merge(&data2).count()) }); } @@ -521,9 +519,7 @@ fn merge_by_cmp(c: &mut Criterion) { let data2 = black_box(data2); c.bench_function("merge by cmp", move |b| { - b.iter(|| { - data1.iter().merge_by(&data2, PartialOrd::le).count() - }) + b.iter(|| data1.iter().merge_by(&data2, PartialOrd::le).count()) }); } @@ -549,9 +545,7 @@ fn merge_by_lt(c: &mut Criterion) { let data2 = black_box(data2); c.bench_function("merge by lt", move |b| { - b.iter(|| { - data1.iter().merge_by(&data2, |a, b| a <= b).count() - }) + b.iter(|| data1.iter().merge_by(&data2, |a, b| a <= b).count()) }); } @@ -578,9 +572,7 @@ fn kmerge_default(c: &mut Criterion) { let its = &[data1.iter(), data2.iter()]; c.bench_function("kmerge default", move |b| { - b.iter(|| { - its.iter().cloned().kmerge().count() - }) + b.iter(|| its.iter().cloned().kmerge().count()) }); } @@ -603,7 +595,7 @@ fn kmerge_tenway(c: &mut Criterion) { while rest.len() > 0 { let chunk_len = 1 + rng(&mut state) % 512; let chunk_len = cmp::min(rest.len(), chunk_len as usize); - let (fst, tail) = {rest}.split_at_mut(chunk_len); + let (fst, tail) = { rest }.split_at_mut(chunk_len); fst.sort(); chunks.push(fst.iter().cloned()); rest = tail; @@ -612,15 +604,14 @@ fn kmerge_tenway(c: &mut Criterion) { // println!("Chunk lengths: {}", chunks.iter().format_with(", ", |elt, f| f(&elt.len()))); c.bench_function("kmerge tenway", move |b| { - b.iter(|| { - chunks.iter().cloned().kmerge().count() - }) + b.iter(|| chunks.iter().cloned().kmerge().count()) }); } fn fast_integer_sum(iter: I) -> I::Item - where I: IntoIterator, - I::Item: Default + Add +where + I: IntoIterator, + I::Item: Default + Add, { iter.into_iter().fold(<_>::default(), |x, y| x + y) } @@ -629,9 +620,7 @@ fn step_vec_2(c: &mut Criterion) { let v = vec![0; 1024]; c.bench_function("step vec 2", move |b| { - b.iter(|| { - fast_integer_sum(cloned(v.iter().step_by(2))) - }) + b.iter(|| fast_integer_sum(cloned(v.iter().step_by(2)))) }); } @@ -639,9 +628,7 @@ fn step_vec_10(c: &mut Criterion) { let v = vec![0; 1024]; c.bench_function("step vec 10", move |b| { - b.iter(|| { - fast_integer_sum(cloned(v.iter().step_by(10))) - }) + b.iter(|| fast_integer_sum(cloned(v.iter().step_by(10)))) }); } @@ -649,9 +636,7 @@ fn step_range_2(c: &mut Criterion) { let v = black_box(0..1024); c.bench_function("step range 2", move |b| { - b.iter(|| { - fast_integer_sum(v.clone().step_by(2)) - }) + b.iter(|| fast_integer_sum(v.clone().step_by(2))) }); } @@ -659,9 +644,7 @@ fn step_range_10(c: &mut Criterion) { let v = black_box(0..1024); c.bench_function("step range 10", move |b| { - b.iter(|| { - fast_integer_sum(v.clone().step_by(10)) - }) + b.iter(|| fast_integer_sum(v.clone().step_by(10))) }); } @@ -753,9 +736,7 @@ fn all_equal(c: &mut Criterion) { let mut xs = vec![0; 5_000_000]; xs.extend(vec![1; 5_000_000]); - c.bench_function("all equal", move |b| { - b.iter(|| xs.iter().all_equal()) - }); + c.bench_function("all equal", move |b| b.iter(|| xs.iter().all_equal())); } fn all_equal_for(c: &mut Criterion) { @@ -797,21 +778,17 @@ fn permutations_iter(c: &mut Criterion) { } c.bench_function("permutations iter", move |b| { - b.iter(|| { - for _ in NewIterator(0..PERM_COUNT).permutations(PERM_COUNT) { - - } - }) + b.iter( + || { + for _ in NewIterator(0..PERM_COUNT).permutations(PERM_COUNT) {} + }, + ) }); } fn permutations_range(c: &mut Criterion) { c.bench_function("permutations range", move |b| { - b.iter(|| { - for _ in (0..PERM_COUNT).permutations(PERM_COUNT) { - - } - }) + b.iter(|| for _ in (0..PERM_COUNT).permutations(PERM_COUNT) {}) }); } @@ -819,11 +796,7 @@ fn permutations_slice(c: &mut Criterion) { let v = (0..PERM_COUNT).collect_vec(); c.bench_function("permutations slice", move |b| { - b.iter(|| { - for _ in v.as_slice().iter().permutations(PERM_COUNT) { - - } - }) + b.iter(|| for _ in v.as_slice().iter().permutations(PERM_COUNT) {}) }); } diff --git a/benches/combinations.rs b/benches/combinations.rs index e7433a4cb..42a452111 100644 --- a/benches/combinations.rs +++ b/benches/combinations.rs @@ -111,15 +111,7 @@ fn comb_c14(c: &mut Criterion) { } criterion_group!( - benches, - comb_for1, - comb_for2, - comb_for3, - comb_for4, - comb_c1, - comb_c2, - comb_c3, - comb_c4, + benches, comb_for1, comb_for2, comb_for3, comb_for4, comb_c1, comb_c2, comb_c3, comb_c4, comb_c14, ); criterion_main!(benches); diff --git a/benches/extra/zipslices.rs b/benches/extra/zipslices.rs index 633be5906..5476c0cb8 100644 --- a/benches/extra/zipslices.rs +++ b/benches/extra/zipslices.rs @@ -46,8 +46,9 @@ impl<'a, 'b, A, B> ZipSlices<&'a [A], &'b [B]> { } impl ZipSlices - where T: Slice, - U: Slice +where + T: Slice, + U: Slice, { /// Create a new `ZipSlices` from slices `a` and `b`. /// @@ -67,8 +68,9 @@ impl ZipSlices } impl Iterator for ZipSlices - where T: Slice, - U: Slice +where + T: Slice, + U: Slice, { type Item = (T::Item, U::Item); @@ -80,9 +82,7 @@ impl Iterator for ZipSlices } else { let i = self.index; self.index += 1; - Some(( - self.t.get_unchecked(i), - self.u.get_unchecked(i))) + Some((self.t.get_unchecked(i), self.u.get_unchecked(i))) } } } @@ -95,8 +95,9 @@ impl Iterator for ZipSlices } impl DoubleEndedIterator for ZipSlices - where T: Slice, - U: Slice +where + T: Slice, + U: Slice, { #[inline(always)] fn next_back(&mut self) -> Option { @@ -106,22 +107,23 @@ impl DoubleEndedIterator for ZipSlices } else { self.len -= 1; let i = self.len; - Some(( - self.t.get_unchecked(i), - self.u.get_unchecked(i))) + Some((self.t.get_unchecked(i), self.u.get_unchecked(i))) } } } } impl ExactSizeIterator for ZipSlices - where T: Slice, - U: Slice -{} +where + T: Slice, + U: Slice, +{ +} unsafe impl Slice for ZipSlices - where T: Slice, - U: Slice +where + T: Slice, + U: Slice, { type Item = (T::Item, U::Item); @@ -130,8 +132,7 @@ unsafe impl Slice for ZipSlices } unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { - (self.t.get_unchecked(i), - self.u.get_unchecked(i)) + (self.t.get_unchecked(i), self.u.get_unchecked(i)) } } @@ -152,7 +153,9 @@ pub unsafe trait Slice { unsafe impl<'a, T> Slice for &'a [T] { type Item = &'a T; #[inline(always)] - fn len(&self) -> usize { (**self).len() } + fn len(&self) -> usize { + (**self).len() + } #[inline(always)] unsafe fn get_unchecked(&mut self, i: usize) -> &'a T { debug_assert!(i < self.len()); @@ -163,7 +166,9 @@ unsafe impl<'a, T> Slice for &'a [T] { unsafe impl<'a, T> Slice for &'a mut [T] { type Item = &'a mut T; #[inline(always)] - fn len(&self) -> usize { (**self).len() } + fn len(&self) -> usize { + (**self).len() + } #[inline(always)] unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T { debug_assert!(i < self.len()); @@ -174,7 +179,6 @@ unsafe impl<'a, T> Slice for &'a mut [T] { #[test] fn zipslices() { - let xs = [1, 2, 3, 4, 5, 6]; let ys = [1, 2, 3, 7]; ::itertools::assert_equal(ZipSlices::new(&xs, &ys), xs.iter().zip(&ys)); diff --git a/benches/fold_specialization.rs b/benches/fold_specialization.rs index 5de4671e9..ef7f47c43 100644 --- a/benches/fold_specialization.rs +++ b/benches/fold_specialization.rs @@ -4,7 +4,8 @@ use itertools::Itertools; struct Unspecialized(I); impl Iterator for Unspecialized -where I: Iterator +where + I: Iterator, { type Item = I::Item; @@ -25,8 +26,7 @@ mod specialization { pub mod intersperse { use super::*; - pub fn external(c: &mut Criterion) - { + pub fn external(c: &mut Criterion) { let arr = [1; 1024]; c.bench_function("external", move |b| { @@ -40,25 +40,19 @@ mod specialization { }); } - pub fn internal_specialized(c: &mut Criterion) - { + pub fn internal_specialized(c: &mut Criterion) { let arr = [1; 1024]; c.bench_function("internal specialized", move |b| { - b.iter(|| { - arr.iter().intersperse(&0).fold(0, |acc, x| acc + x) - }) + b.iter(|| arr.iter().intersperse(&0).fold(0, |acc, x| acc + x)) }); } - pub fn internal_unspecialized(c: &mut Criterion) - { + pub fn internal_unspecialized(c: &mut Criterion) { let arr = [1; 1024]; c.bench_function("internal unspecialized", move |b| { - b.iter(|| { - Unspecialized(arr.iter().intersperse(&0)).fold(0, |acc, x| acc + x) - }) + b.iter(|| Unspecialized(arr.iter().intersperse(&0)).fold(0, |acc, x| acc + x)) }); } } diff --git a/benches/powerset.rs b/benches/powerset.rs index 074550bc4..f5862a416 100644 --- a/benches/powerset.rs +++ b/benches/powerset.rs @@ -20,17 +20,29 @@ fn powerset_n(c: &mut Criterion, n: usize) { }); } -fn powerset_0(c: &mut Criterion) { powerset_n(c, 0); } +fn powerset_0(c: &mut Criterion) { + powerset_n(c, 0); +} -fn powerset_1(c: &mut Criterion) { powerset_n(c, 1); } +fn powerset_1(c: &mut Criterion) { + powerset_n(c, 1); +} -fn powerset_2(c: &mut Criterion) { powerset_n(c, 2); } +fn powerset_2(c: &mut Criterion) { + powerset_n(c, 2); +} -fn powerset_4(c: &mut Criterion) { powerset_n(c, 4); } +fn powerset_4(c: &mut Criterion) { + powerset_n(c, 4); +} -fn powerset_8(c: &mut Criterion) { powerset_n(c, 8); } +fn powerset_8(c: &mut Criterion) { + powerset_n(c, 8); +} -fn powerset_12(c: &mut Criterion) { powerset_n(c, 12); } +fn powerset_12(c: &mut Criterion) { + powerset_n(c, 12); +} criterion_group!( benches, @@ -41,4 +53,4 @@ criterion_group!( powerset_8, powerset_12, ); -criterion_main!(benches); \ No newline at end of file +criterion_main!(benches); diff --git a/benches/tree_fold1.rs b/benches/tree_fold1.rs index f12995db8..77af505f1 100644 --- a/benches/tree_fold1.rs +++ b/benches/tree_fold1.rs @@ -1,12 +1,13 @@ use criterion::{criterion_group, criterion_main, Criterion}; -use itertools::{Itertools, cloned}; +use itertools::{cloned, Itertools}; -trait IterEx : Iterator { +trait IterEx: Iterator { // Another efficient implementation against which to compare, // but needs `std` so is less desirable. fn tree_fold1_vec(self, mut f: F) -> Option - where F: FnMut(Self::Item, Self::Item) -> Self::Item, - Self: Sized, + where + F: FnMut(Self::Item, Self::Item) -> Self::Item, + Self: Sized, { let hint = self.size_hint().0; let cap = std::mem::size_of::() * 8 - hint.leading_zeros() as usize; @@ -21,24 +22,23 @@ trait IterEx : Iterator { stack.into_iter().fold1(f) } } -impl IterEx for T {} +impl IterEx for T {} macro_rules! def_benchs { ($N:expr, $FUN:ident, $BENCH_NAME:ident, - ) => ( + ) => { mod $BENCH_NAME { use super::*; pub fn sum(c: &mut Criterion) { - let v: Vec = (0.. $N).collect(); + let v: Vec = (0..$N).collect(); - c.bench_function(&(stringify!($BENCH_NAME).replace('_', " ") + " sum"), move |b| { - b.iter(|| { - cloned(&v).$FUN(|x, y| x + y) - }) - }); + c.bench_function( + &(stringify!($BENCH_NAME).replace('_', " ") + " sum"), + move |b| b.iter(|| cloned(&v).$FUN(|x, y| x + y)), + ); } pub fn complex_iter(c: &mut Criterion) { @@ -46,11 +46,10 @@ macro_rules! def_benchs { let v = (5..).take($N / 2); let it = u.chain(v); - c.bench_function(&(stringify!($BENCH_NAME).replace('_', " ") + " complex iter"), move |b| { - b.iter(|| { - it.clone().map(|x| x as f32).$FUN(f32::atan2) - }) - }); + c.bench_function( + &(stringify!($BENCH_NAME).replace('_', " ") + " complex iter"), + move |b| b.iter(|| it.clone().map(|x| x as f32).$FUN(f32::atan2)), + ); } pub fn string_format(c: &mut Criterion) { @@ -58,13 +57,18 @@ macro_rules! def_benchs { // size to not waste too much time in travis. The allocations // in here are so expensive anyway that it'll still take // way longer per iteration than the other two benchmarks. - let v: Vec = (0.. ($N/4)).collect(); - - c.bench_function(&(stringify!($BENCH_NAME).replace('_', " ") + " string format"), move |b| { - b.iter(|| { - cloned(&v).map(|x| x.to_string()).$FUN(|x, y| format!("{} + {}", x, y)) - }) - }); + let v: Vec = (0..($N / 4)).collect(); + + c.bench_function( + &(stringify!($BENCH_NAME).replace('_', " ") + " string format"), + move |b| { + b.iter(|| { + cloned(&v) + .map(|x| x.to_string()) + .$FUN(|x, y| format!("{} + {}", x, y)) + }) + }, + ); } } @@ -74,58 +78,58 @@ macro_rules! def_benchs { $BENCH_NAME::complex_iter, $BENCH_NAME::string_format, ); - ) + }; } -def_benchs!{ +def_benchs! { 10_000, fold1, fold1_10k, } -def_benchs!{ +def_benchs! { 10_000, tree_fold1, tree_fold1_stack_10k, } -def_benchs!{ +def_benchs! { 10_000, tree_fold1_vec, tree_fold1_vec_10k, } -def_benchs!{ +def_benchs! { 100, fold1, fold1_100, } -def_benchs!{ +def_benchs! { 100, tree_fold1, tree_fold1_stack_100, } -def_benchs!{ +def_benchs! { 100, tree_fold1_vec, tree_fold1_vec_100, } -def_benchs!{ +def_benchs! { 8, fold1, fold1_08, } -def_benchs!{ +def_benchs! { 8, tree_fold1, tree_fold1_stack_08, } -def_benchs!{ +def_benchs! { 8, tree_fold1_vec, tree_fold1_vec_08, diff --git a/benches/tuples.rs b/benches/tuples.rs index ea50aaaee..2eca34712 100644 --- a/benches/tuples.rs +++ b/benches/tuples.rs @@ -33,7 +33,7 @@ fn sum_s4(s: &[u32]) -> u32 { s4(s[0], s[1], s[2], s[3]) } -fn sum_t1(s: &(&u32, )) -> u32 { +fn sum_t1(s: &(&u32,)) -> u32 { s1(*s.0) } @@ -60,9 +60,9 @@ macro_rules! def_benchs { $WINDOWS:ident; $FOR_CHUNKS:ident, $FOR_WINDOWS:ident - ) => ( + ) => { fn $FOR_CHUNKS(c: &mut Criterion) { - let v: Vec = (0.. $N * 1_000).collect(); + let v: Vec = (0..$N * 1_000).collect(); let mut s = 0; c.bench_function(&stringify!($FOR_CHUNKS).replace('_', " "), move |b| { b.iter(|| { @@ -90,7 +90,7 @@ macro_rules! def_benchs { } fn $TUPLES(c: &mut Criterion) { - let v: Vec = (0.. $N * 1_000).collect(); + let v: Vec = (0..$N * 1_000).collect(); let mut s = 0; c.bench_function(&stringify!($TUPLES).replace('_', " "), move |b| { b.iter(|| { @@ -103,7 +103,7 @@ macro_rules! def_benchs { } fn $CHUNKS(c: &mut Criterion) { - let v: Vec = (0.. $N * 1_000).collect(); + let v: Vec = (0..$N * 1_000).collect(); let mut s = 0; c.bench_function(&stringify!($CHUNKS).replace('_', " "), move |b| { b.iter(|| { @@ -150,10 +150,10 @@ macro_rules! def_benchs { $TUPLE_WINDOWS, $WINDOWS, ); - ) + }; } -def_benchs!{ +def_benchs! { 1; benches_1, sum_t1, @@ -166,7 +166,7 @@ def_benchs!{ for_windows_1 } -def_benchs!{ +def_benchs! { 2; benches_2, sum_t2, @@ -179,7 +179,7 @@ def_benchs!{ for_windows_2 } -def_benchs!{ +def_benchs! { 3; benches_3, sum_t3, @@ -192,7 +192,7 @@ def_benchs!{ for_windows_3 } -def_benchs!{ +def_benchs! { 4; benches_4, sum_t4, @@ -205,9 +205,4 @@ def_benchs!{ for_windows_4 } -criterion_main!( - benches_1, - benches_2, - benches_3, - benches_4, -); +criterion_main!(benches_1, benches_2, benches_3, benches_4,); diff --git a/examples/iris.rs b/examples/iris.rs index 987d9e9cb..af64322d6 100644 --- a/examples/iris.rs +++ b/examples/iris.rs @@ -3,7 +3,6 @@ /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. - use itertools::Itertools; use std::collections::HashMap; use std::iter::repeat; @@ -35,7 +34,10 @@ impl FromStr for Iris { type Err = ParseError; fn from_str(s: &str) -> Result { - let mut iris = Iris { name: "".into(), data: [0.; 4] }; + let mut iris = Iris { + name: "".into(), + data: [0.; 4], + }; let mut parts = s.split(",").map(str::trim); // using Iterator::by_ref() @@ -45,7 +47,7 @@ impl FromStr for Iris { if let Some(name) = parts.next() { iris.name = name.into(); } else { - return Err(ParseError::Other("Missing name")) + return Err(ParseError::Other("Missing name")); } Ok(iris) } @@ -53,12 +55,13 @@ impl FromStr for Iris { fn main() { // using Itertools::fold_results to create the result of parsing - let irises = DATA.lines() - .map(str::parse) - .fold_ok(Vec::new(), |mut v, iris: Iris| { - v.push(iris); - v - }); + let irises = DATA + .lines() + .map(str::parse) + .fold_ok(Vec::new(), |mut v, iris: Iris| { + v.push(iris); + v + }); let mut irises = match irises { Err(e) => { println!("Error parsing: {:?}", e); @@ -77,16 +80,15 @@ fn main() { // using Itertools::group_by for (species, species_group) in &irises.iter().group_by(|iris| &iris.name) { // assign a plot symbol - symbolmap.entry(species).or_insert_with(|| { - plot_symbols.next().unwrap() - }); + symbolmap + .entry(species) + .or_insert_with(|| plot_symbols.next().unwrap()); println!("{} (symbol={})", species, symbolmap[species]); for iris in species_group { // using Itertools::format for lazy formatting println!("{:>3.1}", iris.data.iter().format(", ")); } - } // Look at all combinations of the four columns diff --git a/src/adaptors/mod.rs b/src/adaptors/mod.rs index 19008ccf2..493aee790 100644 --- a/src/adaptors/mod.rs +++ b/src/adaptors/mod.rs @@ -8,16 +8,16 @@ mod coalesce; mod map; mod multi_product; pub use self::coalesce::*; -pub use self::map::{map_into, map_ok, MapInto, MapOk}; #[allow(deprecated)] pub use self::map::MapResults; +pub use self::map::{map_into, map_ok, MapInto, MapOk}; #[cfg(feature = "use_alloc")] pub use self::multi_product::*; +use crate::size_hint; use std::fmt; -use std::iter::{Fuse, Peekable, FromIterator, FusedIterator}; +use std::iter::{FromIterator, Fuse, FusedIterator, Peekable}; use std::marker::PhantomData; -use crate::size_hint; /// An iterator adaptor that alternates elements from two iterators until both /// run out. @@ -36,9 +36,13 @@ pub struct Interleave { /// Create an iterator that interleaves elements in `i` and `j`. /// /// [`IntoIterator`] enabled version of `[Itertools::interleave]`. -pub fn interleave(i: I, j: J) -> Interleave<::IntoIter, ::IntoIter> - where I: IntoIterator, - J: IntoIterator +pub fn interleave( + i: I, + j: J, +) -> Interleave<::IntoIter, ::IntoIter> +where + I: IntoIterator, + J: IntoIterator, { Interleave { a: i.into_iter().fuse(), @@ -48,8 +52,9 @@ pub fn interleave(i: I, j: J) -> Interleave<::IntoIter, } impl Iterator for Interleave - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { type Item = I::Item; #[inline] @@ -74,9 +79,11 @@ impl Iterator for Interleave } impl FusedIterator for Interleave - where I: Iterator, - J: Iterator -{} +where + I: Iterator, + J: Iterator, +{ +} /// An iterator adaptor that alternates elements from the two iterators until /// one of them runs out. @@ -88,8 +95,9 @@ impl FusedIterator for Interleave #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct InterleaveShortest - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { it0: I, it1: J, @@ -98,8 +106,9 @@ pub struct InterleaveShortest /// Create a new `InterleaveShortest` iterator. pub fn interleave_shortest(a: I, b: J) -> InterleaveShortest - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { InterleaveShortest { it0: a, @@ -109,14 +118,19 @@ pub fn interleave_shortest(a: I, b: J) -> InterleaveShortest } impl Iterator for InterleaveShortest - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { type Item = I::Item; #[inline] fn next(&mut self) -> Option { - let e = if self.phase { self.it1.next() } else { self.it0.next() }; + let e = if self.phase { + self.it1.next() + } else { + self.it0.next() + }; if e.is_some() { self.phase = !self.phase; } @@ -138,12 +152,11 @@ impl Iterator for InterleaveShortest let (next_lower, next_upper) = next_hint; let (combined_lower, combined_upper) = size_hint::mul_scalar(size_hint::min(curr_hint, next_hint), 2); - let lower = - if curr_lower > next_lower { - combined_lower + 1 - } else { - combined_lower - }; + let lower = if curr_lower > next_lower { + combined_lower + 1 + } else { + combined_lower + }; let upper = { let extra_elem = match (curr_upper, next_upper) { (_, None) => false, @@ -161,9 +174,11 @@ impl Iterator for InterleaveShortest } impl FusedIterator for InterleaveShortest - where I: FusedIterator, - J: FusedIterator -{} +where + I: FusedIterator, + J: FusedIterator, +{ +} #[derive(Clone, Debug)] /// An iterator adaptor that allows putting back a single @@ -171,7 +186,8 @@ impl FusedIterator for InterleaveShortest /// /// Iterator element type is `I::Item`. pub struct PutBack - where I: Iterator +where + I: Iterator, { top: Option, iter: I, @@ -179,7 +195,8 @@ pub struct PutBack /// Create an iterator where you can put back a single item pub fn put_back(iterable: I) -> PutBack - where I: IntoIterator +where + I: IntoIterator, { PutBack { top: None, @@ -188,7 +205,8 @@ pub fn put_back(iterable: I) -> PutBack } impl PutBack - where I: Iterator +where + I: Iterator, { /// put back value `value` (builder method) pub fn with_value(mut self, value: I::Item) -> Self { @@ -199,7 +217,7 @@ impl PutBack /// Split the `PutBack` into its parts. #[inline] pub fn into_parts(self) -> (Option, I) { - let PutBack{top, iter} = self; + let PutBack { top, iter } = self; (top, iter) } @@ -213,7 +231,8 @@ impl PutBack } impl Iterator for PutBack - where I: Iterator +where + I: Iterator, { type Item = I::Item; #[inline] @@ -252,7 +271,8 @@ impl Iterator for PutBack } fn all(&mut self, mut f: G) -> bool - where G: FnMut(Self::Item) -> bool + where + G: FnMut(Self::Item) -> bool, { if let Some(elt) = self.top.take() { if !f(elt) { @@ -263,7 +283,8 @@ impl Iterator for PutBack } fn fold(mut self, init: Acc, mut f: G) -> Acc - where G: FnMut(Acc, Self::Item) -> Acc, + where + G: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; if let Some(elt) = self.top.take() { @@ -282,7 +303,8 @@ impl Iterator for PutBack /// See [`.cartesian_product()`](crate::Itertools::cartesian_product) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Product - where I: Iterator +where + I: Iterator, { a: I, a_cur: Option, @@ -294,9 +316,10 @@ pub struct Product /// /// Iterator element type is `(I::Item, J::Item)`. pub fn cartesian_product(mut i: I, j: J) -> Product - where I: Iterator, - J: Clone + Iterator, - I::Item: Clone +where + I: Iterator, + J: Clone + Iterator, + I::Item: Clone, { Product { a_cur: i.next(), @@ -307,9 +330,10 @@ pub fn cartesian_product(mut i: I, j: J) -> Product } impl Iterator for Product - where I: Iterator, - J: Clone + Iterator, - I::Item: Clone +where + I: Iterator, + J: Clone + Iterator, + I::Item: Clone, { type Item = (I::Item, J::Item); @@ -325,13 +349,11 @@ impl Iterator for Product } } } - Some(x) => x + Some(x) => x, }; match self.a_cur { None => None, - Some(ref a) => { - Some((a.clone(), elt_b)) - } + Some(ref a) => Some((a.clone(), elt_b)), } } @@ -343,11 +365,13 @@ impl Iterator for Product // Compute a * b_orig + b for both lower and upper bound size_hint::add( size_hint::mul(self.a.size_hint(), self.b_orig.size_hint()), - (b_min * has_cur, b_max.map(move |x| x * has_cur))) + (b_min * has_cur, b_max.map(move |x| x * has_cur)), + ) } fn fold(mut self, mut accum: Acc, mut f: G) -> Acc - where G: FnMut(Acc, Self::Item) -> Acc, + where + G: FnMut(Acc, Self::Item) -> Acc, { // use a split loop to handle the loose a_cur as well as avoiding to // clone b_orig at the end. @@ -370,10 +394,12 @@ impl Iterator for Product } impl FusedIterator for Product - where I: FusedIterator, - J: Clone + FusedIterator, - I::Item: Clone -{} +where + I: FusedIterator, + J: Clone + FusedIterator, + I::Item: Clone, +{ +} /// A “meta iterator adaptor”. Its closure receives a reference to the iterator /// and may pick off as many elements as it likes, to produce the next iterator element. @@ -388,7 +414,10 @@ pub struct Batching { iter: I, } -impl fmt::Debug for Batching where I: fmt::Debug { +impl fmt::Debug for Batching +where + I: fmt::Debug, +{ debug_fmt_fields!(Batching, iter); } @@ -398,8 +427,9 @@ pub fn batching(iter: I, f: F) -> Batching { } impl Iterator for Batching - where I: Iterator, - F: FnMut(&mut I) -> Option +where + I: Iterator, + F: FnMut(&mut I) -> Option, { type Item = B; #[inline] @@ -415,7 +445,7 @@ impl Iterator for Batching /// then skipping forward *n-1* elements. /// /// See [`.step()`](crate::Itertools::step) for more information. -#[deprecated(note="Use std .step_by() instead", since="0.8.0")] +#[deprecated(note = "Use std .step_by() instead", since = "0.8.0")] #[allow(deprecated)] #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] @@ -429,7 +459,8 @@ pub struct Step { /// **Panics** if the step is 0. #[allow(deprecated)] pub fn step(iter: I, step: usize) -> Step - where I: Iterator +where + I: Iterator, { assert!(step != 0); Step { @@ -440,7 +471,8 @@ pub fn step(iter: I, step: usize) -> Step #[allow(deprecated)] impl Iterator for Step - where I: Iterator +where + I: Iterator, { type Item = I::Item; #[inline] @@ -467,9 +499,7 @@ impl Iterator for Step // known size #[allow(deprecated)] -impl ExactSizeIterator for Step - where I: ExactSizeIterator -{} +impl ExactSizeIterator for Step where I: ExactSizeIterator {} pub trait MergePredicate { fn merge_pred(&mut self, a: &T, b: &T) -> bool; @@ -503,10 +533,14 @@ pub type Merge = MergeBy; /// /* loop body */ /// } /// ``` -pub fn merge(i: I, j: J) -> Merge<::IntoIter, ::IntoIter> - where I: IntoIterator, - J: IntoIterator, - I::Item: PartialOrd +pub fn merge( + i: I, + j: J, +) -> Merge<::IntoIter, ::IntoIter> +where + I: IntoIterator, + J: IntoIterator, + I::Item: PartialOrd, { merge_by_new(i, j, MergeLte) } @@ -519,8 +553,9 @@ pub fn merge(i: I, j: J) -> Merge<::IntoIter, - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { a: Peekable, b: Peekable, @@ -529,13 +564,15 @@ pub struct MergeBy } impl fmt::Debug for MergeBy - where I: Iterator + fmt::Debug, J: Iterator + fmt::Debug, - I::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + J: Iterator + fmt::Debug, + I::Item: fmt::Debug, { debug_fmt_fields!(MergeBy, a, b); } -implbool> MergePredicate for F { +impl bool> MergePredicate for F { fn merge_pred(&mut self, a: &T, b: &T) -> bool { self(a, b) } @@ -543,9 +580,10 @@ implbool> MergePredicate for F { /// Create a `MergeBy` iterator. pub fn merge_by_new(a: I, b: J, cmp: F) -> MergeBy - where I: IntoIterator, - J: IntoIterator, - F: MergePredicate, +where + I: IntoIterator, + J: IntoIterator, + F: MergePredicate, { MergeBy { a: a.into_iter().peekable(), @@ -556,19 +594,21 @@ pub fn merge_by_new(a: I, b: J, cmp: F) -> MergeBy Clone for MergeBy - where I: Iterator, - J: Iterator, - Peekable: Clone, - Peekable: Clone, - F: Clone +where + I: Iterator, + J: Iterator, + Peekable: Clone, + Peekable: Clone, + F: Clone, { clone_fields!(a, b, fused, cmp); } impl Iterator for MergeBy - where I: Iterator, - J: Iterator, - F: MergePredicate +where + I: Iterator, + J: Iterator, + F: MergePredicate, { type Item = I::Item; @@ -586,7 +626,7 @@ impl Iterator for MergeBy false } (None, None) => return None, - } + }, }; if less_than { self.a.next() @@ -602,10 +642,12 @@ impl Iterator for MergeBy } impl FusedIterator for MergeBy - where I: FusedIterator, - J: FusedIterator, - F: MergePredicate -{} +where + I: FusedIterator, + J: FusedIterator, + F: MergePredicate, +{ +} /// An iterator adaptor that borrows from a `Clone`-able iterator /// to only pick off elements while the predicate returns `true`. @@ -618,21 +660,24 @@ pub struct TakeWhileRef<'a, I: 'a, F> { } impl<'a, I, F> fmt::Debug for TakeWhileRef<'a, I, F> - where I: Iterator + fmt::Debug, +where + I: Iterator + fmt::Debug, { debug_fmt_fields!(TakeWhileRef, iter); } /// Create a new `TakeWhileRef` from a reference to clonable iterator. pub fn take_while_ref(iter: &mut I, f: F) -> TakeWhileRef - where I: Iterator + Clone +where + I: Iterator + Clone, { TakeWhileRef { iter, f } } impl<'a, I, F> Iterator for TakeWhileRef<'a, I, F> - where I: Iterator + Clone, - F: FnMut(&I::Item) -> bool +where + I: Iterator + Clone, + F: FnMut(&I::Item) -> bool, { type Item = I::Item; @@ -672,7 +717,8 @@ pub fn while_some(iter: I) -> WhileSome { } impl Iterator for WhileSome - where I: Iterator> +where + I: Iterator>, { type Item = A; @@ -696,8 +742,9 @@ impl Iterator for WhileSome #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct TupleCombinations - where I: Iterator, - T: HasCombination +where + I: Iterator, + T: HasCombination, { iter: T::Combination, _mi: PhantomData, @@ -709,9 +756,10 @@ pub trait HasCombination: Sized { /// Create a new `TupleCombinations` from a clonable iterator. pub fn tuple_combinations(iter: I) -> TupleCombinations - where I: Iterator + Clone, - I::Item: Clone, - T: HasCombination, +where + I: Iterator + Clone, + I::Item: Clone, + T: HasCombination, { TupleCombinations { iter: T::Combination::from(iter), @@ -720,8 +768,9 @@ pub fn tuple_combinations(iter: I) -> TupleCombinations } impl Iterator for TupleCombinations - where I: Iterator, - T: HasCombination, +where + I: Iterator, + T: HasCombination, { type Item = T; @@ -731,9 +780,11 @@ impl Iterator for TupleCombinations } impl FusedIterator for TupleCombinations - where I: FusedIterator, - T: HasCombination, -{} +where + I: FusedIterator, + T: HasCombination, +{ +} #[derive(Clone, Debug)] pub struct Tuple1Combination { @@ -843,7 +894,7 @@ impl_tuple_combination!(Tuple12Combination Tuple11Combination; a b c d e f g h i #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct FilterOk { iter: I, - f: F + f: F, } impl fmt::Debug for FilterOk @@ -855,18 +906,17 @@ where /// Create a new `FilterOk` iterator. pub fn filter_ok(iter: I, f: F) -> FilterOk - where I: Iterator>, - F: FnMut(&T) -> bool, +where + I: Iterator>, + F: FnMut(&T) -> bool, { - FilterOk { - iter, - f, - } + FilterOk { iter, f } } impl Iterator for FilterOk - where I: Iterator>, - F: FnMut(&T) -> bool, +where + I: Iterator>, + F: FnMut(&T) -> bool, { type Item = Result; @@ -877,7 +927,7 @@ impl Iterator for FilterOk if (self.f)(&v) { return Some(Ok(v)); } - }, + } Some(Err(e)) => return Some(Err(e)), None => return None, } @@ -889,28 +939,32 @@ impl Iterator for FilterOk } fn fold(self, init: Acc, fold_f: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { let mut f = self.f; - self.iter.filter(|v| { - v.as_ref().map(&mut f).unwrap_or(true) - }).fold(init, fold_f) + self.iter + .filter(|v| v.as_ref().map(&mut f).unwrap_or(true)) + .fold(init, fold_f) } fn collect(self) -> C - where C: FromIterator + where + C: FromIterator, { let mut f = self.f; - self.iter.filter(|v| { - v.as_ref().map(&mut f).unwrap_or(true) - }).collect() + self.iter + .filter(|v| v.as_ref().map(&mut f).unwrap_or(true)) + .collect() } } impl FusedIterator for FilterOk - where I: FusedIterator>, - F: FnMut(&T) -> bool, -{} +where + I: FusedIterator>, + F: FnMut(&T) -> bool, +{ +} /// An iterator adapter to filter and apply a transformation on values within a nested `Result::Ok`. /// @@ -918,7 +972,7 @@ impl FusedIterator for FilterOk #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct FilterMapOk { iter: I, - f: F + f: F, } impl fmt::Debug for FilterMapOk @@ -938,18 +992,17 @@ fn transpose_result(result: Result, E>) -> Option> /// Create a new `FilterOk` iterator. pub fn filter_map_ok(iter: I, f: F) -> FilterMapOk - where I: Iterator>, - F: FnMut(T) -> Option, +where + I: Iterator>, + F: FnMut(T) -> Option, { - FilterMapOk { - iter, - f, - } + FilterMapOk { iter, f } } impl Iterator for FilterMapOk - where I: Iterator>, - F: FnMut(T) -> Option, +where + I: Iterator>, + F: FnMut(T) -> Option, { type Item = Result; @@ -960,7 +1013,7 @@ impl Iterator for FilterMapOk if let Some(v) = (self.f)(v) { return Some(Ok(v)); } - }, + } Some(Err(e)) => return Some(Err(e)), None => return None, } @@ -972,28 +1025,32 @@ impl Iterator for FilterMapOk } fn fold(self, init: Acc, fold_f: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { let mut f = self.f; - self.iter.filter_map(|v| { - transpose_result(v.map(&mut f)) - }).fold(init, fold_f) + self.iter + .filter_map(|v| transpose_result(v.map(&mut f))) + .fold(init, fold_f) } fn collect(self) -> C - where C: FromIterator + where + C: FromIterator, { let mut f = self.f; - self.iter.filter_map(|v| { - transpose_result(v.map(&mut f)) - }).collect() + self.iter + .filter_map(|v| transpose_result(v.map(&mut f))) + .collect() } } impl FusedIterator for FilterMapOk - where I: FusedIterator>, - F: FnMut(T) -> Option, -{} +where + I: FusedIterator>, + F: FnMut(T) -> Option, +{ +} /// An iterator adapter to get the positions of each element that matches a predicate. /// @@ -1015,19 +1072,17 @@ where /// Create a new `Positions` iterator. pub fn positions(iter: I, f: F) -> Positions - where I: Iterator, - F: FnMut(I::Item) -> bool, +where + I: Iterator, + F: FnMut(I::Item) -> bool, { - Positions { - iter, - f, - count: 0 - } + Positions { iter, f, count: 0 } } impl Iterator for Positions - where I: Iterator, - F: FnMut(I::Item) -> bool, +where + I: Iterator, + F: FnMut(I::Item) -> bool, { type Item = usize; @@ -1048,13 +1103,14 @@ impl Iterator for Positions } impl DoubleEndedIterator for Positions - where I: DoubleEndedIterator + ExactSizeIterator, - F: FnMut(I::Item) -> bool, +where + I: DoubleEndedIterator + ExactSizeIterator, + F: FnMut(I::Item) -> bool, { fn next_back(&mut self) -> Option { while let Some(v) = self.iter.next_back() { if (self.f)(v) { - return Some(self.count + self.iter.len()) + return Some(self.count + self.iter.len()); } } None @@ -1062,9 +1118,11 @@ impl DoubleEndedIterator for Positions } impl FusedIterator for Positions - where I: FusedIterator, - F: FnMut(I::Item) -> bool, -{} +where + I: FusedIterator, + F: FnMut(I::Item) -> bool, +{ +} /// An iterator adapter to apply a mutating function to each element before yielding it. /// @@ -1113,18 +1171,28 @@ where } fn fold(self, init: Acc, mut g: G) -> Acc - where G: FnMut(Acc, Self::Item) -> Acc, + where + G: FnMut(Acc, Self::Item) -> Acc, { let mut f = self.f; - self.iter.fold(init, move |acc, mut v| { f(&mut v); g(acc, v) }) + self.iter.fold(init, move |acc, mut v| { + f(&mut v); + g(acc, v) + }) } // if possible, re-use inner iterator specializations in collect fn collect(self) -> C - where C: FromIterator + where + C: FromIterator, { let mut f = self.f; - self.iter.map(move |mut v| { f(&mut v); v }).collect() + self.iter + .map(move |mut v| { + f(&mut v); + v + }) + .collect() } } @@ -1132,7 +1200,8 @@ impl ExactSizeIterator for Update where I: ExactSizeIterator, F: FnMut(&mut I::Item), -{} +{ +} impl DoubleEndedIterator for Update where @@ -1153,4 +1222,5 @@ impl FusedIterator for Update where I: FusedIterator, F: FnMut(&mut I::Item), -{} +{ +} diff --git a/src/adaptors/multi_product.rs b/src/adaptors/multi_product.rs index 30650eda6..7cf5c5010 100644 --- a/src/adaptors/multi_product.rs +++ b/src/adaptors/multi_product.rs @@ -15,8 +15,9 @@ use alloc::vec::Vec; /// for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct MultiProduct(Vec>) - where I: Iterator + Clone, - I::Item: Clone; +where + I: Iterator + Clone, + I::Item: Clone; impl std::fmt::Debug for MultiProduct where @@ -31,19 +32,25 @@ where /// /// Iterator element is of type `Vec`. pub fn multi_cartesian_product(iters: H) -> MultiProduct<::IntoIter> - where H: Iterator, - H::Item: IntoIterator, - ::IntoIter: Clone, - ::Item: Clone +where + H: Iterator, + H::Item: IntoIterator, + ::IntoIter: Clone, + ::Item: Clone, { - MultiProduct(iters.map(|i| MultiProductIter::new(i.into_iter())).collect()) + MultiProduct( + iters + .map(|i| MultiProductIter::new(i.into_iter())) + .collect(), + ) } #[derive(Clone, Debug)] /// Holds the state of a single iterator within a MultiProduct. struct MultiProductIter - where I: Iterator + Clone, - I::Item: Clone +where + I: Iterator + Clone, + I::Item: Clone, { cur: Option, iter: I, @@ -58,8 +65,9 @@ enum MultiProductIterState { } impl MultiProduct - where I: Iterator + Clone, - I::Item: Clone +where + I: Iterator + Clone, + I::Item: Clone, { /// Iterates the rightmost iterator, then recursively iterates iterators /// to the left if necessary. @@ -67,7 +75,7 @@ impl MultiProduct /// Returns true if the iteration succeeded, else false. fn iterate_last( multi_iters: &mut [MultiProductIter], - mut state: MultiProductIterState + mut state: MultiProductIterState, ) -> bool { use self::MultiProductIterState::*; @@ -77,8 +85,8 @@ impl MultiProduct let on_first_iter = !last.in_progress(); state = MidIter { on_first_iter }; on_first_iter - }, - MidIter { on_first_iter } => on_first_iter + } + MidIter { on_first_iter } => on_first_iter, }; if !on_first_iter { @@ -101,16 +109,17 @@ impl MultiProduct // At end of iteration (final iterator finishes), finish. match state { StartOfIter => false, - MidIter { on_first_iter } => on_first_iter + MidIter { on_first_iter } => on_first_iter, } } } /// Returns the unwrapped value of the next iteration. fn curr_iterator(&self) -> Vec { - self.0.iter().map(|multi_iter| { - multi_iter.cur.clone().unwrap() - }).collect() + self.0 + .iter() + .map(|multi_iter| multi_iter.cur.clone().unwrap()) + .collect() } /// Returns true if iteration has started and has not yet finished; false @@ -125,14 +134,15 @@ impl MultiProduct } impl MultiProductIter - where I: Iterator + Clone, - I::Item: Clone +where + I: Iterator + Clone, + I::Item: Clone, { fn new(iter: I) -> Self { MultiProductIter { cur: None, iter: iter.clone(), - iter_orig: iter + iter_orig: iter, } } @@ -154,16 +164,14 @@ impl MultiProductIter } impl Iterator for MultiProduct - where I: Iterator + Clone, - I::Item: Clone +where + I: Iterator + Clone, + I::Item: Clone, { type Item = Vec; fn next(&mut self) -> Option { - if MultiProduct::iterate_last( - &mut self.0, - MultiProductIterState::StartOfIter - ) { + if MultiProduct::iterate_last(&mut self.0, MultiProductIterState::StartOfIter) { Some(self.curr_iterator()) } else { None @@ -176,18 +184,24 @@ impl Iterator for MultiProduct } if !self.in_progress() { - return self.0.into_iter().fold(1, |acc, multi_iter| { - acc * multi_iter.iter.count() - }); + return self + .0 + .into_iter() + .fold(1, |acc, multi_iter| acc * multi_iter.iter.count()); } self.0.into_iter().fold( 0, - |acc, MultiProductIter { iter, iter_orig, cur: _ }| { + |acc, + MultiProductIter { + iter, + iter_orig, + cur: _, + }| { let total_count = iter_orig.count(); let cur_count = iter.count(); acc * total_count + cur_count - } + }, ) } @@ -205,18 +219,25 @@ impl Iterator for MultiProduct self.0.iter().fold( (0, Some(0)), - |acc, &MultiProductIter { ref iter, ref iter_orig, cur: _ }| { + |acc, + &MultiProductIter { + ref iter, + ref iter_orig, + cur: _, + }| { let cur_size = iter.size_hint(); let total_size = iter_orig.size_hint(); size_hint::add(size_hint::mul(acc, total_size), cur_size) - } + }, ) } fn last(self) -> Option { let iter_count = self.0.len(); - let lasts: Self::Item = self.0.into_iter() + let lasts: Self::Item = self + .0 + .into_iter() .map(|multi_iter| multi_iter.iter.last()) .while_some() .collect(); diff --git a/src/combinations.rs b/src/combinations.rs index 68a59c5e4..ba764ff33 100644 --- a/src/combinations.rs +++ b/src/combinations.rs @@ -15,22 +15,25 @@ pub struct Combinations { } impl Clone for Combinations - where I: Clone + Iterator, - I::Item: Clone, +where + I: Clone + Iterator, + I::Item: Clone, { clone_fields!(indices, pool, first); } impl fmt::Debug for Combinations - where I: Iterator + fmt::Debug, - I::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: fmt::Debug, { debug_fmt_fields!(Combinations, indices, pool, first); } /// Create a new `Combinations` from a clonable iterator. pub fn combinations(iter: I, k: usize) -> Combinations - where I: Iterator +where + I: Iterator, { let mut pool = LazyBuffer::new(iter); pool.prefill(k); @@ -45,16 +48,22 @@ pub fn combinations(iter: I, k: usize) -> Combinations impl Combinations { /// Returns the length of a combination produced by this iterator. #[inline] - pub fn k(&self) -> usize { self.indices.len() } + pub fn k(&self) -> usize { + self.indices.len() + } /// Returns the (current) length of the pool from which combination elements are /// selected. This value can change between invocations of [`next`](Combinations::next). #[inline] - pub fn n(&self) -> usize { self.pool.len() } + pub fn n(&self) -> usize { + self.pool.len() + } /// Returns a reference to the source iterator. #[inline] - pub(crate) fn src(&self) -> &I { &self.pool.it } + pub(crate) fn src(&self) -> &I { + &self.pool.it + } /// Resets this `Combinations` back to an initial state for combinations of length /// `k` over the same pool data source. If `k` is larger than the current length @@ -68,7 +77,6 @@ impl Combinations { for i in 0..k { self.indices[i] = i; } - } else { for i in 0..self.indices.len() { self.indices[i] = i; @@ -80,8 +88,9 @@ impl Combinations { } impl Iterator for Combinations - where I: Iterator, - I::Item: Clone +where + I: Iterator, + I::Item: Clone, { type Item = Vec; fn next(&mut self) -> Option { @@ -112,7 +121,7 @@ impl Iterator for Combinations // Increment index, and reset the ones to its right self.indices[i] += 1; - for j in i+1..self.indices.len() { + for j in i + 1..self.indices.len() { self.indices[j] = self.indices[j - 1] + 1; } } @@ -123,6 +132,8 @@ impl Iterator for Combinations } impl FusedIterator for Combinations - where I: Iterator, - I::Item: Clone -{} +where + I: Iterator, + I::Item: Clone, +{ +} diff --git a/src/combinations_with_replacement.rs b/src/combinations_with_replacement.rs index 81b13f130..46f848971 100644 --- a/src/combinations_with_replacement.rs +++ b/src/combinations_with_replacement.rs @@ -80,7 +80,7 @@ where // Work out where we need to update our indices let mut increment: Option<(usize, usize)> = None; for (i, indices_int) in self.indices.iter().enumerate().rev() { - if *indices_int < self.pool.len()-1 { + if *indices_int < self.pool.len() - 1 { increment = Some((i, indices_int + 1)); break; } @@ -106,4 +106,5 @@ impl FusedIterator for CombinationsWithReplacement where I: Iterator, I::Item: Clone, -{} +{ +} diff --git a/src/concat_impl.rs b/src/concat_impl.rs index 450f7fce1..42b5288b8 100644 --- a/src/concat_impl.rs +++ b/src/concat_impl.rs @@ -10,13 +10,20 @@ use crate::Itertools; /// /// ```rust /// use itertools::concat; -/// +/// /// let input = vec![vec![1], vec![2, 3], vec![4, 5, 6]]; /// assert_eq!(concat(input), vec![1, 2, 3, 4, 5, 6]); /// ``` pub fn concat(iterable: I) -> I::Item - where I: IntoIterator, - I::Item: Extend<<::Item as IntoIterator>::Item> + IntoIterator + Default +where + I: IntoIterator, + I::Item: Extend<<::Item as IntoIterator>::Item> + IntoIterator + Default, { - iterable.into_iter().fold1(|mut a, b| { a.extend(b); a }).unwrap_or_else(<_>::default) + iterable + .into_iter() + .fold1(|mut a, b| { + a.extend(b); + a + }) + .unwrap_or_else(<_>::default) } diff --git a/src/cons_tuples_impl.rs b/src/cons_tuples_impl.rs index ae0f48f34..3cae0b06e 100644 --- a/src/cons_tuples_impl.rs +++ b/src/cons_tuples_impl.rs @@ -1,4 +1,3 @@ - macro_rules! impl_cons_iter( ($_A:ident, $_B:ident, ) => (); // stop @@ -44,13 +43,15 @@ impl_cons_iter!(A, B, C, D, E, F, G, H, I, J, K, L,); #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[derive(Debug)] pub struct ConsTuples - where I: Iterator, +where + I: Iterator, { iter: I, } impl Clone for ConsTuples - where I: Clone + Iterator, +where + I: Clone + Iterator, { clone_fields!(iter); } @@ -58,7 +59,10 @@ impl Clone for ConsTuples /// Create an iterator that maps for example iterators of /// `((A, B), C)` to `(A, B, C)`. pub fn cons_tuples(iterable: I) -> ConsTuples - where I: IntoIterator +where + I: IntoIterator, { - ConsTuples { iter: iterable.into_iter() } + ConsTuples { + iter: iterable.into_iter(), + } } diff --git a/src/diff.rs b/src/diff.rs index 1731f0639..0d3d358b5 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -13,8 +13,9 @@ use crate::structs::PutBack; /// `Diff` represents the way in which the elements yielded by the iterator `I` differ to some /// iterator `J`. pub enum Diff - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { /// The index of the first non-matching element along with both iterator's remaining elements /// starting with the first mis-match. @@ -37,11 +38,11 @@ pub enum Diff /// /// If `i` becomes exhausted before `j` becomes exhausted, the number of elements in `i` along with /// the remaining `j` elements will be returned as `Diff::Longer`. -pub fn diff_with(i: I, j: J, is_equal: F) - -> Option> - where I: IntoIterator, - J: IntoIterator, - F: Fn(&I::Item, &J::Item) -> bool +pub fn diff_with(i: I, j: J, is_equal: F) -> Option> +where + I: IntoIterator, + J: IntoIterator, + F: Fn(&I::Item, &J::Item) -> bool, { let mut i = i.into_iter(); let mut j = j.into_iter(); @@ -49,13 +50,16 @@ pub fn diff_with(i: I, j: J, is_equal: F) while let Some(i_elem) = i.next() { match j.next() { None => return Some(Diff::Shorter(idx, put_back(i).with_value(i_elem))), - Some(j_elem) => if !is_equal(&i_elem, &j_elem) { - let remaining_i = put_back(i).with_value(i_elem); - let remaining_j = put_back(j).with_value(j_elem); - return Some(Diff::FirstMismatch(idx, remaining_i, remaining_j)); - }, + Some(j_elem) => { + if !is_equal(&i_elem, &j_elem) { + let remaining_i = put_back(i).with_value(i_elem); + let remaining_j = put_back(j).with_value(j_elem); + return Some(Diff::FirstMismatch(idx, remaining_i, remaining_j)); + } + } } idx += 1; } - j.next().map(|j_elem| Diff::Longer(idx, put_back(j).with_value(j_elem))) + j.next() + .map(|j_elem| Diff::Longer(idx, put_back(j).with_value(j_elem))) } diff --git a/src/duplicates_impl.rs b/src/duplicates_impl.rs index 28eda44a9..a80316a7c 100644 --- a/src/duplicates_impl.rs +++ b/src/duplicates_impl.rs @@ -2,8 +2,8 @@ use std::hash::Hash; mod private { use std::collections::HashMap; - use std::hash::Hash; use std::fmt; + use std::hash::Hash; #[derive(Clone)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] @@ -213,4 +213,3 @@ where { Duplicates::new(iter, private::ById) } - diff --git a/src/exactly_one_err.rs b/src/exactly_one_err.rs index 63485c993..727bef54e 100644 --- a/src/exactly_one_err.rs +++ b/src/exactly_one_err.rs @@ -54,13 +54,9 @@ where Some(Either::Left([first, second])) => { self.first_two = Some(Either::Right(second)); Some(first) - }, - Some(Either::Right(second)) => { - Some(second) - } - None => { - self.inner.next() } + Some(Either::Right(second)) => Some(second), + None => self.inner.next(), } } @@ -69,11 +65,11 @@ where } } - impl ExactSizeIterator for ExactlyOneError where I: ExactSizeIterator {} -impl Display for ExactlyOneError - where I: Iterator, +impl Display for ExactlyOneError +where + I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); @@ -85,17 +81,26 @@ impl Display for ExactlyOneError } } -impl Debug for ExactlyOneError - where I: Iterator + Debug, - I::Item: Debug, +impl Debug for ExactlyOneError +where + I: Iterator + Debug, + I::Item: Debug, { fn fmt(&self, f: &mut Formatter) -> FmtResult { match &self.first_two { Some(Either::Left([first, second])) => { - write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) - }, + write!( + f, + "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", + first, second, self.inner + ) + } Some(Either::Right(second)) => { - write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) + write!( + f, + "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", + second, self.inner + ) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) @@ -105,6 +110,9 @@ impl Debug for ExactlyOneError } #[cfg(feature = "use_std")] -impl Error for ExactlyOneError where I: Iterator + Debug, I::Item: Debug, {} - - +impl Error for ExactlyOneError +where + I: Iterator + Debug, + I::Item: Debug, +{ +} diff --git a/src/format.rs b/src/format.rs index d87cee950..fe82ad526 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,5 +1,5 @@ -use std::fmt; use std::cell::RefCell; +use std::fmt; /// Format all iterator elements lazily, separated by `sep`. /// @@ -29,8 +29,9 @@ pub struct Format<'a, I> { } pub fn new_format(iter: I, separator: &str, f: F) -> FormatWith<'_, I, F> - where I: Iterator, - F: FnMut(I::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result +where + I: Iterator, + F: FnMut(I::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result, { FormatWith { sep: separator, @@ -39,7 +40,8 @@ pub fn new_format(iter: I, separator: &str, f: F) -> FormatWith<'_, I, F> } pub fn new_format_default(iter: I, separator: &str) -> Format<'_, I> - where I: Iterator, +where + I: Iterator, { Format { sep: separator, @@ -48,8 +50,9 @@ pub fn new_format_default(iter: I, separator: &str) -> Format<'_, I> } impl<'a, I, F> fmt::Display for FormatWith<'a, I, F> - where I: Iterator, - F: FnMut(I::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result +where + I: Iterator, + F: FnMut(I::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (mut iter, mut format) = match self.inner.borrow_mut().take() { @@ -71,10 +74,12 @@ impl<'a, I, F> fmt::Display for FormatWith<'a, I, F> } impl<'a, I> Format<'a, I> - where I: Iterator, +where + I: Iterator, { fn format(&self, f: &mut fmt::Formatter, mut cb: F) -> fmt::Result - where F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result, + where + F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result, { let mut iter = match self.inner.borrow_mut().take() { Some(t) => t, @@ -109,5 +114,5 @@ macro_rules! impl_format { } } -impl_format!{Display Debug - UpperExp LowerExp UpperHex LowerHex Octal Binary Pointer} +impl_format! {Display Debug +UpperExp LowerExp UpperHex LowerHex Octal Binary Pointer} diff --git a/src/free.rs b/src/free.rs index 3886f5f1f..ff7ea3426 100644 --- a/src/free.rs +++ b/src/free.rs @@ -10,30 +10,24 @@ use std::iter::{self, Zip}; type VecIntoIter = alloc::vec::IntoIter; #[cfg(feature = "use_alloc")] -use alloc::{ - string::String, -}; +use alloc::string::String; -use crate::Itertools; use crate::intersperse::{Intersperse, IntersperseWith}; +use crate::Itertools; -pub use crate::adaptors::{ - interleave, - merge, - put_back, -}; +pub use crate::adaptors::{interleave, merge, put_back}; #[cfg(feature = "use_alloc")] -pub use crate::put_back_n_impl::put_back_n; +pub use crate::kmerge_impl::kmerge; +pub use crate::merge_join::merge_join_by; #[cfg(feature = "use_alloc")] pub use crate::multipeek_impl::multipeek; #[cfg(feature = "use_alloc")] pub use crate::peek_nth::peek_nth; #[cfg(feature = "use_alloc")] -pub use crate::kmerge_impl::kmerge; -pub use crate::zip_eq_impl::zip_eq; -pub use crate::merge_join::merge_join_by; +pub use crate::put_back_n_impl::put_back_n; #[cfg(feature = "use_alloc")] pub use crate::rciter_impl::rciter; +pub use crate::zip_eq_impl::zip_eq; /// Iterate `iterable` with a particular value inserted between each element. /// @@ -45,8 +39,9 @@ pub use crate::rciter_impl::rciter; /// itertools::assert_equal(intersperse((0..3), 8), vec![0, 8, 1, 8, 2]); /// ``` pub fn intersperse(iterable: I, element: I::Item) -> Intersperse - where I: IntoIterator, - ::Item: Clone +where + I: IntoIterator, + ::Item: Clone, { Itertools::intersperse(iterable.into_iter(), element) } @@ -64,8 +59,9 @@ pub fn intersperse(iterable: I, element: I::Item) -> Intersperse /// assert_eq!(i, 8); /// ``` pub fn intersperse_with(iterable: I, element: F) -> IntersperseWith - where I: IntoIterator, - F: FnMut() -> I::Item +where + I: IntoIterator, + F: FnMut() -> I::Item, { Itertools::intersperse_with(iterable.into_iter(), element) } @@ -82,7 +78,8 @@ pub fn intersperse_with(iterable: I, element: F) -> IntersperseWith(iterable: I) -> iter::Enumerate - where I: IntoIterator +where + I: IntoIterator, { iterable.into_iter().enumerate() } @@ -99,8 +96,9 @@ pub fn enumerate(iterable: I) -> iter::Enumerate /// } /// ``` pub fn rev(iterable: I) -> iter::Rev - where I: IntoIterator, - I::IntoIter: DoubleEndedIterator +where + I: IntoIterator, + I::IntoIter: DoubleEndedIterator, { iterable.into_iter().rev() } @@ -118,8 +116,9 @@ pub fn rev(iterable: I) -> iter::Rev /// } /// ``` pub fn zip(i: I, j: J) -> Zip - where I: IntoIterator, - J: IntoIterator +where + I: IntoIterator, + J: IntoIterator, { i.into_iter().zip(j) } @@ -135,9 +134,13 @@ pub fn zip(i: I, j: J) -> Zip /// /* loop body */ /// } /// ``` -pub fn chain(i: I, j: J) -> iter::Chain<::IntoIter, ::IntoIter> - where I: IntoIterator, - J: IntoIterator +pub fn chain( + i: I, + j: J, +) -> iter::Chain<::IntoIter, ::IntoIter> +where + I: IntoIterator, + J: IntoIterator, { i.into_iter().chain(j) } @@ -152,8 +155,9 @@ pub fn chain(i: I, j: J) -> iter::Chain<::IntoIter, (iterable: I) -> iter::Cloned - where I: IntoIterator, - T: Clone, +where + I: IntoIterator, + T: Clone, { iterable.into_iter().cloned() } @@ -168,8 +172,9 @@ pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned /// assert_eq!(fold(&[1., 2., 3.], 0., |a, &b| f32::max(a, b)), 3.); /// ``` pub fn fold(iterable: I, init: B, f: F) -> B - where I: IntoIterator, - F: FnMut(B, I::Item) -> B +where + I: IntoIterator, + F: FnMut(B, I::Item) -> B, { iterable.into_iter().fold(init, f) } @@ -184,8 +189,9 @@ pub fn fold(iterable: I, init: B, f: F) -> B /// assert!(all(&[1, 2, 3], |elt| *elt > 0)); /// ``` pub fn all(iterable: I, f: F) -> bool - where I: IntoIterator, - F: FnMut(I::Item) -> bool +where + I: IntoIterator, + F: FnMut(I::Item) -> bool, { iterable.into_iter().all(f) } @@ -200,8 +206,9 @@ pub fn all(iterable: I, f: F) -> bool /// assert!(any(&[0, -1, 2], |elt| *elt > 0)); /// ``` pub fn any(iterable: I, f: F) -> bool - where I: IntoIterator, - F: FnMut(I::Item) -> bool +where + I: IntoIterator, + F: FnMut(I::Item) -> bool, { iterable.into_iter().any(f) } @@ -216,8 +223,9 @@ pub fn any(iterable: I, f: F) -> bool /// assert_eq!(max(0..10), Some(9)); /// ``` pub fn max(iterable: I) -> Option - where I: IntoIterator, - I::Item: Ord +where + I: IntoIterator, + I::Item: Ord, { iterable.into_iter().max() } @@ -232,13 +240,13 @@ pub fn max(iterable: I) -> Option /// assert_eq!(min(0..10), Some(0)); /// ``` pub fn min(iterable: I) -> Option - where I: IntoIterator, - I::Item: Ord +where + I: IntoIterator, + I::Item: Ord, { iterable.into_iter().min() } - /// Combine all iterator elements into one String, separated by `sep`. /// /// [`IntoIterator`] enabled version of [`Itertools::join`]. @@ -250,8 +258,9 @@ pub fn min(iterable: I) -> Option /// ``` #[cfg(feature = "use_alloc")] pub fn join(iterable: I, sep: &str) -> String - where I: IntoIterator, - I::Item: Display +where + I: IntoIterator, + I::Item: Display, { iterable.into_iter().join(sep) } @@ -268,9 +277,9 @@ pub fn join(iterable: I, sep: &str) -> String /// ``` #[cfg(feature = "use_alloc")] pub fn sorted(iterable: I) -> VecIntoIter - where I: IntoIterator, - I::Item: Ord +where + I: IntoIterator, + I::Item: Ord, { iterable.into_iter().sorted() } - diff --git a/src/group_map.rs b/src/group_map.rs index a2d0ebb2a..8891f95ac 100644 --- a/src/group_map.rs +++ b/src/group_map.rs @@ -9,8 +9,9 @@ use std::iter::Iterator; /// See [`.into_group_map()`](crate::Itertools::into_group_map) /// for more information. pub fn into_group_map(iter: I) -> HashMap> - where I: Iterator, - K: Hash + Eq, +where + I: Iterator, + K: Hash + Eq, { let mut lookup = HashMap::new(); @@ -22,11 +23,9 @@ pub fn into_group_map(iter: I) -> HashMap> } pub fn into_group_map_by(iter: I, f: impl Fn(&V) -> K) -> HashMap> - where - I: Iterator, - K: Hash + Eq, +where + I: Iterator, + K: Hash + Eq, { - into_group_map( - iter.map(|v| (f(&v), v)) - ) + into_group_map(iter.map(|v| (f(&v), v))) } diff --git a/src/groupbylazy.rs b/src/groupbylazy.rs index 91c52ea59..f9aff6fdf 100644 --- a/src/groupbylazy.rs +++ b/src/groupbylazy.rs @@ -1,5 +1,5 @@ -use std::cell::{Cell, RefCell}; use alloc::vec::{self, Vec}; +use std::cell::{Cell, RefCell}; /// A trait to unify FnMut for GroupBy with the chunk key in IntoChunks trait KeyFunction { @@ -8,7 +8,8 @@ trait KeyFunction { } impl<'a, A, K, F: ?Sized> KeyFunction for F - where F: FnMut(A) -> K +where + F: FnMut(A) -> K, { type Key = K; #[inline] @@ -17,7 +18,6 @@ impl<'a, A, K, F: ?Sized> KeyFunction for F } } - /// ChunkIndex acts like the grouping key function for IntoChunks #[derive(Debug)] struct ChunkIndex { @@ -50,9 +50,9 @@ impl<'a, A> KeyFunction for ChunkIndex { } } - struct GroupInner - where I: Iterator +where + I: Iterator, { key: F, iter: I, @@ -75,9 +75,10 @@ struct GroupInner } impl GroupInner - where I: Iterator, - F: for<'a> KeyFunction<&'a I::Item, Key=K>, - K: PartialEq, +where + I: Iterator, + F: for<'a> KeyFunction<&'a I::Item, Key = K>, + K: PartialEq, { /// `client`: Index of group that requests next element #[inline(always)] @@ -90,9 +91,8 @@ impl GroupInner */ if client < self.oldest_buffered_group { None - } else if client < self.top_group || - (client == self.top_group && - self.buffer.len() > self.top_group - self.bottom_group) + } else if client < self.top_group + || (client == self.top_group && self.buffer.len() > self.top_group - self.bottom_group) { self.lookup_buffer(client) } else if self.done { @@ -118,8 +118,10 @@ impl GroupInner // `bottom_group..oldest_buffered_group` is unused, and if it's large enough, erase it. self.oldest_buffered_group += 1; // skip forward further empty queues too - while self.buffer.get(self.oldest_buffered_group - self.bottom_group) - .map_or(false, |buf| buf.len() == 0) + while self + .buffer + .get(self.oldest_buffered_group - self.bottom_group) + .map_or(false, |buf| buf.len() == 0) { self.oldest_buffered_group += 1; } @@ -144,12 +146,14 @@ impl GroupInner fn next_element(&mut self) -> Option { debug_assert!(!self.done); match self.iter.next() { - None => { self.done = true; None } + None => { + self.done = true; + None + } otherwise => otherwise, } } - #[inline(never)] fn step_buffering(&mut self, client: usize) -> Option { // requested a later group -- walk through the current group up to @@ -171,11 +175,13 @@ impl GroupInner let key = self.key.call_mut(&elt); match self.current_key.take() { None => {} - Some(old_key) => if old_key != key { - self.current_key = Some(key); - first_elt = Some(elt); - break; - }, + Some(old_key) => { + if old_key != key { + self.current_key = Some(key); + first_elt = Some(elt); + break; + } + } } self.current_key = Some(key); if self.top_group != self.dropped_group { @@ -220,12 +226,14 @@ impl GroupInner let key = self.key.call_mut(&elt); match self.current_key.take() { None => {} - Some(old_key) => if old_key != key { - self.current_key = Some(key); - self.current_elt = Some(elt); - self.top_group += 1; - return None; - }, + Some(old_key) => { + if old_key != key { + self.current_key = Some(key); + self.current_elt = Some(elt); + self.top_group += 1; + return None; + } + } } self.current_key = Some(key); Some(elt) @@ -261,7 +269,8 @@ impl GroupInner } impl GroupInner - where I: Iterator, +where + I: Iterator, { /// Called when a group is dropped fn drop_group(&mut self, client: usize) { @@ -287,7 +296,8 @@ impl GroupInner /// See [`.group_by()`](crate::Itertools::group_by) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct GroupBy - where I: Iterator, +where + I: Iterator, { inner: RefCell>, // the group iterator's current index. Keep this in the main value @@ -297,8 +307,9 @@ pub struct GroupBy /// Create a new pub fn new(iter: J, f: F) -> GroupBy - where J: IntoIterator, - F: FnMut(&J::Item) -> K, +where + J: IntoIterator, + F: FnMut(&J::Item) -> K, { GroupBy { inner: RefCell::new(GroupInner { @@ -318,12 +329,14 @@ pub fn new(iter: J, f: F) -> GroupBy } impl GroupBy - where I: Iterator, +where + I: Iterator, { /// `client`: Index of group that requests next element fn step(&self, client: usize) -> Option - where F: FnMut(&I::Item) -> K, - K: PartialEq, + where + F: FnMut(&I::Item) -> K, + K: PartialEq, { self.inner.borrow_mut().step(client) } @@ -335,10 +348,11 @@ impl GroupBy } impl<'a, K, I, F> IntoIterator for &'a GroupBy - where I: Iterator, - I::Item: 'a, - F: FnMut(&I::Item) -> K, - K: PartialEq +where + I: Iterator, + I::Item: 'a, + F: FnMut(&I::Item) -> K, + K: PartialEq, { type Item = (K, Group<'a, K, I, F>); type IntoIter = Groups<'a, K, I, F>; @@ -348,7 +362,6 @@ impl<'a, K, I, F> IntoIterator for &'a GroupBy } } - /// An iterator that yields the Group iterators. /// /// Iterator element type is `(K, Group)`: @@ -357,17 +370,19 @@ impl<'a, K, I, F> IntoIterator for &'a GroupBy /// See [`.group_by()`](crate::Itertools::group_by) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Groups<'a, K: 'a, I: 'a, F: 'a> - where I: Iterator, - I::Item: 'a +where + I: Iterator, + I::Item: 'a, { parent: &'a GroupBy, } impl<'a, K, I, F> Iterator for Groups<'a, K, I, F> - where I: Iterator, - I::Item: 'a, - F: FnMut(&I::Item) -> K, - K: PartialEq +where + I: Iterator, + I::Item: 'a, + F: FnMut(&I::Item) -> K, + K: PartialEq, { type Item = (K, Group<'a, K, I, F>); @@ -378,11 +393,14 @@ impl<'a, K, I, F> Iterator for Groups<'a, K, I, F> let inner = &mut *self.parent.inner.borrow_mut(); inner.step(index).map(|elt| { let key = inner.group_key(index); - (key, Group { - parent: self.parent, - index, - first: Some(elt), - }) + ( + key, + Group { + parent: self.parent, + index, + first: Some(elt), + }, + ) }) } } @@ -391,8 +409,9 @@ impl<'a, K, I, F> Iterator for Groups<'a, K, I, F> /// /// Iterator element type is `I::Item`. pub struct Group<'a, K: 'a, I: 'a, F: 'a> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { parent: &'a GroupBy, index: usize, @@ -400,8 +419,9 @@ pub struct Group<'a, K: 'a, I: 'a, F: 'a> } impl<'a, K, I, F> Drop for Group<'a, K, I, F> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { fn drop(&mut self) { self.parent.drop_group(self.index); @@ -409,10 +429,11 @@ impl<'a, K, I, F> Drop for Group<'a, K, I, F> } impl<'a, K, I, F> Iterator for Group<'a, K, I, F> - where I: Iterator, - I::Item: 'a, - F: FnMut(&I::Item) -> K, - K: PartialEq, +where + I: Iterator, + I::Item: 'a, + F: FnMut(&I::Item) -> K, + K: PartialEq, { type Item = I::Item; #[inline] @@ -428,7 +449,8 @@ impl<'a, K, I, F> Iterator for Group<'a, K, I, F> /// Create a new pub fn new_chunks(iter: J, size: usize) -> IntoChunks - where J: IntoIterator, +where + J: IntoIterator, { IntoChunks { inner: RefCell::new(GroupInner { @@ -447,7 +469,6 @@ pub fn new_chunks(iter: J, size: usize) -> IntoChunks } } - /// `ChunkLazy` is the storage for a lazy chunking operation. /// /// `IntoChunks` behaves just like `GroupBy`: it is iterable, and @@ -463,7 +484,8 @@ pub fn new_chunks(iter: J, size: usize) -> IntoChunks /// See [`.chunks()`](crate::Itertools::chunks) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct IntoChunks - where I: Iterator, +where + I: Iterator, { inner: RefCell>, // the chunk iterator's current index. Keep this in the main value @@ -471,9 +493,9 @@ pub struct IntoChunks index: Cell, } - impl IntoChunks - where I: Iterator, +where + I: Iterator, { /// `client`: Index of chunk that requests next element fn step(&self, client: usize) -> Option { @@ -487,20 +509,18 @@ impl IntoChunks } impl<'a, I> IntoIterator for &'a IntoChunks - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { type Item = Chunk<'a, I>; type IntoIter = Chunks<'a, I>; fn into_iter(self) -> Self::IntoIter { - Chunks { - parent: self, - } + Chunks { parent: self } } } - /// An iterator that yields the Chunk iterators. /// /// Iterator element type is `Chunk`. @@ -508,15 +528,17 @@ impl<'a, I> IntoIterator for &'a IntoChunks /// See [`.chunks()`](crate::Itertools::chunks) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Chunks<'a, I: 'a> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { parent: &'a IntoChunks, } impl<'a, I> Iterator for Chunks<'a, I> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { type Item = Chunk<'a, I>; @@ -525,12 +547,10 @@ impl<'a, I> Iterator for Chunks<'a, I> let index = self.parent.index.get(); self.parent.index.set(index + 1); let inner = &mut *self.parent.inner.borrow_mut(); - inner.step(index).map(|elt| { - Chunk { - parent: self.parent, - index, - first: Some(elt), - } + inner.step(index).map(|elt| Chunk { + parent: self.parent, + index, + first: Some(elt), }) } } @@ -539,8 +559,9 @@ impl<'a, I> Iterator for Chunks<'a, I> /// /// Iterator element type is `I::Item`. pub struct Chunk<'a, I: 'a> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { parent: &'a IntoChunks, index: usize, @@ -548,8 +569,9 @@ pub struct Chunk<'a, I: 'a> } impl<'a, I> Drop for Chunk<'a, I> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { fn drop(&mut self) { self.parent.drop_group(self.index); @@ -557,8 +579,9 @@ impl<'a, I> Drop for Chunk<'a, I> } impl<'a, I> Iterator for Chunk<'a, I> - where I: Iterator, - I::Item: 'a, +where + I: Iterator, + I::Item: 'a, { type Item = I::Item; #[inline] diff --git a/src/grouping_map.rs b/src/grouping_map.rs index 82ba1192b..03d5f011d 100644 --- a/src/grouping_map.rs +++ b/src/grouping_map.rs @@ -1,8 +1,8 @@ #![cfg(feature = "use_std")] use crate::MinMaxResult; -use std::collections::HashMap; use std::cmp::Ordering; +use std::collections::HashMap; use std::hash::Hash; use std::iter::Iterator; use std::ops::{Add, Mul}; @@ -18,9 +18,10 @@ impl MapForGrouping { } impl Iterator for MapForGrouping - where I: Iterator, - K: Hash + Eq, - F: FnMut(&V) -> K, +where + I: Iterator, + K: Hash + Eq, + F: FnMut(&V) -> K, { type Item = (K, V); fn next(&mut self) -> Option { @@ -30,21 +31,22 @@ impl Iterator for MapForGrouping /// Creates a new `GroupingMap` from `iter` pub fn new(iter: I) -> GroupingMap - where I: Iterator, - K: Hash + Eq, +where + I: Iterator, + K: Hash + Eq, { GroupingMap { iter } } /// `GroupingMapBy` is an intermediate struct for efficient group-and-fold operations. -/// +/// /// See [`GroupingMap`] for more informations. pub type GroupingMapBy = GroupingMap>; /// `GroupingMap` is an intermediate struct for efficient group-and-fold operations. /// It groups elements by their key and at the same time fold each group /// using some aggregating operation. -/// +/// /// No method on this struct performs temporary allocations. #[derive(Clone, Debug)] #[must_use = "GroupingMap is lazy and do nothing unless consumed"] @@ -53,13 +55,14 @@ pub struct GroupingMap { } impl GroupingMap - where I: Iterator, - K: Hash + Eq, +where + I: Iterator, + K: Hash + Eq, { /// This is the generic way to perform any operation on a `GroupingMap`. /// It's suggested to use this method only to implement custom operations /// when the already provided ones are not enough. - /// + /// /// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements /// of each group sequentially, passing the previously accumulated value, a reference to the key /// and the current element as arguments, and stores the results in an `HashMap`. @@ -68,17 +71,17 @@ impl GroupingMap /// - the current value of the accumulator of the group if there is currently one; /// - a reference to the key of the group this element belongs to; /// - the element from the source being aggregated; - /// + /// /// If `operation` returns `Some(element)` then the accumulator is updated with `element`, /// otherwise the previous accumulation is discarded. /// /// Return a `HashMap` associating the key of each group with the result of aggregation of /// that group's elements. If the aggregation of the last element of a group discards the /// accumulator then there won't be an entry associated to that group's key. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let data = vec![2, 8, 5, 7, 9, 0, 4, 10]; /// let lookup = data.into_iter() /// .into_grouping_map_by(|&n| n % 4) @@ -89,7 +92,7 @@ impl GroupingMap /// Some(acc.unwrap_or(0) + val) /// } /// }); - /// + /// /// assert_eq!(lookup[&0], 4); // 0 resets the accumulator so only 4 is summed /// assert_eq!(lookup[&1], 5 + 9); /// assert_eq!(lookup.get(&2), None); // 10 resets the accumulator and nothing is summed afterward @@ -97,7 +100,8 @@ impl GroupingMap /// assert_eq!(lookup.len(), 3); // The final keys are only 0, 1 and 2 /// ``` pub fn aggregate(self, mut operation: FO) -> HashMap - where FO: FnMut(Option, &K, V) -> Option, + where + FO: FnMut(Option, &K, V) -> Option, { let mut destination_map = HashMap::new(); @@ -123,22 +127,23 @@ impl GroupingMap /// - the element from the source being accumulated. /// /// Return a `HashMap` associating the key of each group with the result of folding that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = (1..=7) /// .into_grouping_map_by(|&n| n % 3) /// .fold(0, |acc, _key, val| acc + val); - /// + /// /// assert_eq!(lookup[&0], 3 + 6); /// assert_eq!(lookup[&1], 1 + 4 + 7); /// assert_eq!(lookup[&2], 2 + 5); /// assert_eq!(lookup.len(), 3); /// ``` pub fn fold(self, init: R, mut operation: FO) -> HashMap - where R: Clone, - FO: FnMut(R, &K, V) -> R, + where + R: Clone, + FO: FnMut(R, &K, V) -> R, { self.aggregate(|acc, key, val| { let acc = acc.unwrap_or_else(|| init.clone()); @@ -158,23 +163,24 @@ impl GroupingMap /// - the element from the source being accumulated. /// /// Return a `HashMap` associating the key of each group with the result of folding that group's elements. - /// + /// /// [`fold`]: GroupingMap::fold - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = (1..=7) /// .into_grouping_map_by(|&n| n % 3) /// .fold_first(|acc, _key, val| acc + val); - /// + /// /// assert_eq!(lookup[&0], 3 + 6); /// assert_eq!(lookup[&1], 1 + 4 + 7); /// assert_eq!(lookup[&2], 2 + 5); /// assert_eq!(lookup.len(), 3); /// ``` pub fn fold_first(self, mut operation: FO) -> HashMap - where FO: FnMut(V, &K, V) -> V, + where + FO: FnMut(V, &K, V) -> V, { self.aggregate(|acc, key, val| { Some(match acc { @@ -185,249 +191,261 @@ impl GroupingMap } /// Groups elements from the `GroupingMap` source by key and collects the elements of each group in - /// an instance of `C`. The iteration order is preserved when inserting elements. - /// + /// an instance of `C`. The iteration order is preserved when inserting elements. + /// /// Return a `HashMap` associating the key of each group with the collection containing that group's elements. - /// + /// /// ``` /// use itertools::Itertools; /// use std::collections::HashSet; - /// + /// /// let lookup = vec![0, 1, 2, 3, 4, 5, 6, 2, 3, 6].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .collect::>(); - /// + /// /// assert_eq!(lookup[&0], vec![0, 3, 6].into_iter().collect::>()); /// assert_eq!(lookup[&1], vec![1, 4].into_iter().collect::>()); /// assert_eq!(lookup[&2], vec![2, 5].into_iter().collect::>()); /// assert_eq!(lookup.len(), 3); /// ``` pub fn collect(self) -> HashMap - where C: Default + Extend, + where + C: Default + Extend, { let mut destination_map = HashMap::new(); self.iter.for_each(|(key, val)| { - destination_map.entry(key).or_insert_with(C::default).extend(Some(val)); + destination_map + .entry(key) + .or_insert_with(C::default) + .extend(Some(val)); }); destination_map } /// Groups elements from the `GroupingMap` source by key and finds the maximum of each group. - /// + /// /// If several elements are equally maximum, the last element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .max(); - /// + /// /// assert_eq!(lookup[&0], 12); /// assert_eq!(lookup[&1], 7); /// assert_eq!(lookup[&2], 8); /// assert_eq!(lookup.len(), 3); /// ``` pub fn max(self) -> HashMap - where V: Ord, + where + V: Ord, { self.max_by(|_, v1, v2| V::cmp(v1, v2)) } /// Groups elements from the `GroupingMap` source by key and finds the maximum of each group /// with respect to the specified comparison function. - /// + /// /// If several elements are equally maximum, the last element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .max_by(|_key, x, y| y.cmp(x)); - /// + /// /// assert_eq!(lookup[&0], 3); /// assert_eq!(lookup[&1], 1); /// assert_eq!(lookup[&2], 5); /// assert_eq!(lookup.len(), 3); /// ``` pub fn max_by(self, mut compare: F) -> HashMap - where F: FnMut(&K, &V, &V) -> Ordering, + where + F: FnMut(&K, &V, &V) -> Ordering, { self.fold_first(|acc, key, val| match compare(key, &acc, &val) { Ordering::Less | Ordering::Equal => val, - Ordering::Greater => acc + Ordering::Greater => acc, }) } /// Groups elements from the `GroupingMap` source by key and finds the element of each group /// that gives the maximum from the specified function. - /// + /// /// If several elements are equally maximum, the last element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .max_by_key(|_key, &val| val % 4); - /// + /// /// assert_eq!(lookup[&0], 3); /// assert_eq!(lookup[&1], 7); /// assert_eq!(lookup[&2], 5); /// assert_eq!(lookup.len(), 3); /// ``` pub fn max_by_key(self, mut f: F) -> HashMap - where F: FnMut(&K, &V) -> CK, - CK: Ord, + where + F: FnMut(&K, &V) -> CK, + CK: Ord, { self.max_by(|key, v1, v2| f(key, &v1).cmp(&f(key, &v2))) } /// Groups elements from the `GroupingMap` source by key and finds the minimum of each group. - /// + /// /// If several elements are equally minimum, the first element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .min(); - /// + /// /// assert_eq!(lookup[&0], 3); /// assert_eq!(lookup[&1], 1); /// assert_eq!(lookup[&2], 5); /// assert_eq!(lookup.len(), 3); /// ``` pub fn min(self) -> HashMap - where V: Ord, + where + V: Ord, { self.min_by(|_, v1, v2| V::cmp(v1, v2)) } /// Groups elements from the `GroupingMap` source by key and finds the minimum of each group /// with respect to the specified comparison function. - /// + /// /// If several elements are equally minimum, the first element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .min_by(|_key, x, y| y.cmp(x)); - /// + /// /// assert_eq!(lookup[&0], 12); /// assert_eq!(lookup[&1], 7); /// assert_eq!(lookup[&2], 8); /// assert_eq!(lookup.len(), 3); /// ``` pub fn min_by(self, mut compare: F) -> HashMap - where F: FnMut(&K, &V, &V) -> Ordering, + where + F: FnMut(&K, &V, &V) -> Ordering, { self.fold_first(|acc, key, val| match compare(key, &acc, &val) { Ordering::Less | Ordering::Equal => acc, - Ordering::Greater => val + Ordering::Greater => val, }) } /// Groups elements from the `GroupingMap` source by key and finds the element of each group /// that gives the minimum from the specified function. - /// + /// /// If several elements are equally minimum, the first element is picked. - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .min_by_key(|_key, &val| val % 4); - /// + /// /// assert_eq!(lookup[&0], 12); /// assert_eq!(lookup[&1], 4); /// assert_eq!(lookup[&2], 8); /// assert_eq!(lookup.len(), 3); /// ``` pub fn min_by_key(self, mut f: F) -> HashMap - where F: FnMut(&K, &V) -> CK, - CK: Ord, + where + F: FnMut(&K, &V) -> CK, + CK: Ord, { self.min_by(|key, v1, v2| f(key, &v1).cmp(&f(key, &v2))) } /// Groups elements from the `GroupingMap` source by key and find the maximum and minimum of /// each group. - /// + /// /// If several elements are equally maximum, the last element is picked. /// If several elements are equally minimum, the first element is picked. - /// + /// /// See [.minmax()](crate::Itertools::minmax) for the non-grouping version. - /// + /// /// Differences from the non grouping version: /// - It never produces a `MinMaxResult::NoElements` /// - It doesn't have any speedup - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum and maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; /// use itertools::MinMaxResult::{OneElement, MinMax}; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .minmax(); - /// + /// /// assert_eq!(lookup[&0], MinMax(3, 12)); /// assert_eq!(lookup[&1], MinMax(1, 7)); /// assert_eq!(lookup[&2], OneElement(5)); /// assert_eq!(lookup.len(), 3); /// ``` pub fn minmax(self) -> HashMap> - where V: Ord, + where + V: Ord, { self.minmax_by(|_, v1, v2| V::cmp(v1, v2)) } /// Groups elements from the `GroupingMap` source by key and find the maximum and minimum of /// each group with respect to the specified comparison function. - /// + /// /// If several elements are equally maximum, the last element is picked. /// If several elements are equally minimum, the first element is picked. - /// + /// /// It has the same differences from the non-grouping version as `minmax`. - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum and maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; /// use itertools::MinMaxResult::{OneElement, MinMax}; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .minmax_by(|_key, x, y| y.cmp(x)); - /// + /// /// assert_eq!(lookup[&0], MinMax(12, 3)); /// assert_eq!(lookup[&1], MinMax(7, 1)); /// assert_eq!(lookup[&2], OneElement(5)); /// assert_eq!(lookup.len(), 3); /// ``` pub fn minmax_by(self, mut compare: F) -> HashMap> - where F: FnMut(&K, &V, &V) -> Ordering, + where + F: FnMut(&K, &V, &V) -> Ordering, { self.aggregate(|acc, key, val| { Some(match acc { @@ -455,80 +473,83 @@ impl GroupingMap /// Groups elements from the `GroupingMap` source by key and find the elements of each group /// that gives the minimum and maximum from the specified function. - /// + /// /// If several elements are equally maximum, the last element is picked. /// If several elements are equally minimum, the first element is picked. - /// + /// /// It has the same differences from the non-grouping version as `minmax`. - /// + /// /// Returns a `HashMap` associating the key of each group with the minimum and maximum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; /// use itertools::MinMaxResult::{OneElement, MinMax}; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .minmax_by_key(|_key, &val| val % 4); - /// + /// /// assert_eq!(lookup[&0], MinMax(12, 3)); /// assert_eq!(lookup[&1], MinMax(4, 7)); /// assert_eq!(lookup[&2], OneElement(5)); /// assert_eq!(lookup.len(), 3); /// ``` pub fn minmax_by_key(self, mut f: F) -> HashMap> - where F: FnMut(&K, &V) -> CK, - CK: Ord, + where + F: FnMut(&K, &V) -> CK, + CK: Ord, { self.minmax_by(|key, v1, v2| f(key, &v1).cmp(&f(key, &v2))) } - + /// Groups elements from the `GroupingMap` source by key and sums them. - /// + /// /// This is just a shorthand for `self.fold_first(|acc, _, val| acc + val)`. /// It is more limited than `Iterator::sum` since it doesn't use the `Sum` trait. - /// + /// /// Returns a `HashMap` associating the key of each group with the sum of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .sum(); - /// + /// /// assert_eq!(lookup[&0], 3 + 9 + 12); /// assert_eq!(lookup[&1], 1 + 4 + 7); /// assert_eq!(lookup[&2], 5 + 8); /// assert_eq!(lookup.len(), 3); /// ``` pub fn sum(self) -> HashMap - where V: Add + where + V: Add, { self.fold_first(|acc, _, val| acc + val) } /// Groups elements from the `GroupingMap` source by key and multiply them. - /// + /// /// This is just a shorthand for `self.fold_first(|acc, _, val| acc * val)`. /// It is more limited than `Iterator::product` since it doesn't use the `Product` trait. - /// + /// /// Returns a `HashMap` associating the key of each group with the product of that group's elements. - /// + /// /// ``` /// use itertools::Itertools; - /// + /// /// let lookup = vec![1, 3, 4, 5, 7, 8, 9, 12].into_iter() /// .into_grouping_map_by(|&n| n % 3) /// .product(); - /// + /// /// assert_eq!(lookup[&0], 3 * 9 * 12); /// assert_eq!(lookup[&1], 1 * 4 * 7); /// assert_eq!(lookup[&2], 5 * 8); /// assert_eq!(lookup.len(), 3); /// ``` pub fn product(self) -> HashMap - where V: Mul, + where + V: Mul, { self.fold_first(|acc, _, val| acc * val) } diff --git a/src/impl_macros.rs b/src/impl_macros.rs index a029843b0..5fd78cb4d 100644 --- a/src/impl_macros.rs +++ b/src/impl_macros.rs @@ -1,4 +1,4 @@ -//! +//! //! Implementation's internal macros macro_rules! debug_fmt_fields { diff --git a/src/intersperse.rs b/src/intersperse.rs index 2c660d492..d68857812 100644 --- a/src/intersperse.rs +++ b/src/intersperse.rs @@ -1,5 +1,5 @@ -use std::iter::{Fuse, FusedIterator}; use super::size_hint; +use std::iter::{Fuse, FusedIterator}; pub trait IntersperseElement { fn generate(&mut self) -> Item; @@ -26,12 +26,13 @@ pub type Intersperse = IntersperseWith(iter: I, elt: I::Item) -> Intersperse - where I: Iterator, +where + I: Iterator, { intersperse_with(iter, IntersperseElementSimple(elt)) } -implItem> IntersperseElement for F { +impl Item> IntersperseElement for F { fn generate(&mut self) -> Item { self() } @@ -48,7 +49,8 @@ implItem> IntersperseElement for F { #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[derive(Clone, Debug)] pub struct IntersperseWith - where I: Iterator, +where + I: Iterator, { element: ElemF, iter: Fuse, @@ -57,7 +59,8 @@ pub struct IntersperseWith /// Create a new IntersperseWith iterator pub fn intersperse_with(iter: I, elt: ElemF) -> IntersperseWith - where I: Iterator, +where + I: Iterator, { let mut iter = iter.fuse(); IntersperseWith { @@ -68,8 +71,9 @@ pub fn intersperse_with(iter: I, elt: ElemF) -> IntersperseWith Iterator for IntersperseWith - where I: Iterator, - ElemF: IntersperseElement +where + I: Iterator, + ElemF: IntersperseElement, { type Item = I::Item; #[inline] @@ -93,8 +97,10 @@ impl Iterator for IntersperseWith size_hint::add_scalar(size_hint::add(sh, sh), has_peek) } - fn fold(mut self, init: B, mut f: F) -> B where - Self: Sized, F: FnMut(B, Self::Item) -> B, + fn fold(mut self, init: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, { let mut accum = init; @@ -104,16 +110,17 @@ impl Iterator for IntersperseWith let element = &mut self.element; - self.iter.fold(accum, - |accum, x| { - let accum = f(accum, element.generate()); - let accum = f(accum, x); - accum + self.iter.fold(accum, |accum, x| { + let accum = f(accum, element.generate()); + let accum = f(accum, x); + accum }) } } impl FusedIterator for IntersperseWith - where I: Iterator, - ElemF: IntersperseElement -{} +where + I: Iterator, + ElemF: IntersperseElement, +{ +} diff --git a/src/k_smallest.rs b/src/k_smallest.rs index acaea5941..6af66cfaf 100644 --- a/src/k_smallest.rs +++ b/src/k_smallest.rs @@ -2,7 +2,9 @@ use alloc::collections::BinaryHeap; use core::cmp::Ord; pub(crate) fn k_smallest>(mut iter: I, k: usize) -> BinaryHeap { - if k == 0 { return BinaryHeap::new(); } + if k == 0 { + return BinaryHeap::new(); + } let mut heap = iter.by_ref().take(k).collect::>(); diff --git a/src/kmerge_impl.rs b/src/kmerge_impl.rs index 5642b36c9..b1dbefe8c 100644 --- a/src/kmerge_impl.rs +++ b/src/kmerge_impl.rs @@ -2,9 +2,9 @@ use crate::size_hint; use crate::Itertools; use alloc::vec::Vec; +use std::fmt; use std::iter::FusedIterator; use std::mem::replace; -use std::fmt; /// Head element and Tail iterator pair /// @@ -15,24 +15,21 @@ use std::fmt; /// `KMerge` into a min-heap. #[derive(Debug)] struct HeadTail - where I: Iterator +where + I: Iterator, { head: I::Item, tail: I, } impl HeadTail - where I: Iterator +where + I: Iterator, { /// Constructs a `HeadTail` from an `Iterator`. Returns `None` if the `Iterator` is empty. fn new(mut it: I) -> Option> { let head = it.next(); - head.map(|h| { - HeadTail { - head: h, - tail: it, - } - }) + head.map(|h| HeadTail { head: h, tail: it }) } /// Get the next element and update `head`, returning the old head in `Some`. @@ -53,15 +50,17 @@ impl HeadTail } impl Clone for HeadTail - where I: Iterator + Clone, - I::Item: Clone +where + I: Iterator + Clone, + I::Item: Clone, { clone_fields!(head, tail); } /// Make `data` a heap (min-heap w.r.t the sorting). fn heapify(data: &mut [T], mut less_than: S) - where S: FnMut(&T, &T) -> bool +where + S: FnMut(&T, &T) -> bool, { for i in (0..data.len() / 2).rev() { sift_down(data, i, &mut less_than); @@ -70,7 +69,8 @@ fn heapify(data: &mut [T], mut less_than: S) /// Sift down element at `index` (`heap` is a min-heap wrt the ordering) fn sift_down(heap: &mut [T], index: usize, mut less_than: S) - where S: FnMut(&T, &T) -> bool +where + S: FnMut(&T, &T) -> bool, { debug_assert!(index <= heap.len()); let mut pos = index; @@ -81,7 +81,7 @@ fn sift_down(heap: &mut [T], index: usize, mut less_than: S) while child + 1 < heap.len() { // pick the smaller of the two children // use arithmetic to avoid an unpredictable branch - child += less_than(&heap[child+1], &heap[child]) as usize; + child += less_than(&heap[child + 1], &heap[child]) as usize; // sift down is done if we are already in order if !less_than(&heap[child], &heap[pos]) { @@ -119,7 +119,7 @@ impl KMergePredicate for KMergeByLt { } } -implbool> KMergePredicate for F { +impl bool> KMergePredicate for F { fn kmerge_pred(&mut self, a: &T, b: &T) -> bool { self(a, b) } @@ -138,9 +138,10 @@ implbool> KMergePredicate for F { /// } /// ``` pub fn kmerge(iterable: I) -> KMerge<::IntoIter> - where I: IntoIterator, - I::Item: IntoIterator, - <::Item as IntoIterator>::Item: PartialOrd +where + I: IntoIterator, + I::Item: IntoIterator, + <::Item as IntoIterator>::Item: PartialOrd, { kmerge_by(iterable, KMergeByLt) } @@ -154,15 +155,17 @@ pub fn kmerge(iterable: I) -> KMerge<::IntoIter> /// information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct KMergeBy - where I: Iterator, +where + I: Iterator, { heap: Vec>, less_than: F, } impl fmt::Debug for KMergeBy - where I: Iterator + fmt::Debug, - I::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: fmt::Debug, { debug_fmt_fields!(KMergeBy, heap); } @@ -170,11 +173,14 @@ impl fmt::Debug for KMergeBy /// Create an iterator that merges elements of the contained iterators. /// /// [`IntoIterator`] enabled version of [`Itertools::kmerge_by`]. -pub fn kmerge_by(iterable: I, mut less_than: F) - -> KMergeBy<::IntoIter, F> - where I: IntoIterator, - I::Item: IntoIterator, - F: KMergePredicate<<::Item as IntoIterator>::Item>, +pub fn kmerge_by( + iterable: I, + mut less_than: F, +) -> KMergeBy<::IntoIter, F> +where + I: IntoIterator, + I::Item: IntoIterator, + F: KMergePredicate<<::Item as IntoIterator>::Item>, { let iter = iterable.into_iter(); let (lower, _) = iter.size_hint(); @@ -185,16 +191,18 @@ pub fn kmerge_by(iterable: I, mut less_than: F) } impl Clone for KMergeBy - where I: Iterator + Clone, - I::Item: Clone, - F: Clone, +where + I: Iterator + Clone, + I::Item: Clone, + F: Clone, { clone_fields!(heap, less_than); } impl Iterator for KMergeBy - where I: Iterator, - F: KMergePredicate +where + I: Iterator, + F: KMergePredicate, { type Item = I::Item; @@ -208,19 +216,24 @@ impl Iterator for KMergeBy self.heap.swap_remove(0).head }; let less_than = &mut self.less_than; - sift_down(&mut self.heap, 0, |a, b| less_than.kmerge_pred(&a.head, &b.head)); + sift_down(&mut self.heap, 0, |a, b| { + less_than.kmerge_pred(&a.head, &b.head) + }); Some(result) } fn size_hint(&self) -> (usize, Option) { - self.heap.iter() - .map(|i| i.size_hint()) - .fold1(size_hint::add) - .unwrap_or((0, Some(0))) + self.heap + .iter() + .map(|i| i.size_hint()) + .fold1(size_hint::add) + .unwrap_or((0, Some(0))) } } impl FusedIterator for KMergeBy - where I: Iterator, - F: KMergePredicate -{} +where + I: Iterator, + F: KMergePredicate, +{ +} diff --git a/src/lazy_buffer.rs b/src/lazy_buffer.rs index fa514ec2d..27e4326c7 100644 --- a/src/lazy_buffer.rs +++ b/src/lazy_buffer.rs @@ -1,5 +1,5 @@ -use std::ops::Index; use alloc::vec::Vec; +use std::ops::Index; #[derive(Debug, Clone)] pub struct LazyBuffer { @@ -57,7 +57,7 @@ impl Index for LazyBuffer where I: Iterator, I::Item: Sized, - Vec: Index + Vec: Index, { type Output = as Index>::Output; diff --git a/src/lib.rs b/src/lib.rs index 6e86ab789..ec3f1f70b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ #![warn(missing_docs)] -#![crate_name="itertools"] +#![crate_name = "itertools"] #![cfg_attr(not(feature = "use_std"), no_std)] //! Extra iterator adaptors, functions and macros. @@ -43,7 +43,7 @@ //! ## Rust Version //! //! This version of itertools requires Rust 1.32 or later. -#![doc(html_root_url="https://docs.rs/itertools/0.8/")] +#![doc(html_root_url = "https://docs.rs/itertools/0.8/")] #[cfg(not(feature = "use_std"))] extern crate core as std; @@ -52,25 +52,22 @@ extern crate core as std; extern crate alloc; #[cfg(feature = "use_alloc")] -use alloc::{ - string::String, - vec::Vec, -}; +use alloc::{string::String, vec::Vec}; pub use either::Either; use core::borrow::Borrow; +use std::cmp::Ordering; #[cfg(feature = "use_std")] use std::collections::HashMap; -use std::iter::{IntoIterator, once}; -use std::cmp::Ordering; -use std::fmt; #[cfg(feature = "use_std")] use std::collections::HashSet; -#[cfg(feature = "use_std")] -use std::hash::Hash; +use std::fmt; #[cfg(feature = "use_alloc")] use std::fmt::Write; +#[cfg(feature = "use_std")] +use std::hash::Hash; +use std::iter::{once, IntoIterator}; #[cfg(feature = "use_alloc")] type VecIntoIter = alloc::vec::IntoIter; #[cfg(feature = "use_alloc")] @@ -85,72 +82,54 @@ pub use std::iter as __std_iter; /// The concrete iterator types. pub mod structs { + #[cfg(feature = "use_alloc")] + pub use crate::adaptors::MultiProduct; pub use crate::adaptors::{ - Dedup, - DedupBy, - DedupWithCount, - DedupByWithCount, - Interleave, - InterleaveShortest, - FilterMapOk, - FilterOk, - Product, - PutBack, - Batching, - MapInto, - MapOk, - Merge, - MergeBy, - TakeWhileRef, - WhileSome, - Coalesce, - TupleCombinations, - Positions, - Update, + Batching, Coalesce, Dedup, DedupBy, DedupByWithCount, DedupWithCount, FilterMapOk, + FilterOk, Interleave, InterleaveShortest, MapInto, MapOk, Merge, MergeBy, Positions, + Product, PutBack, TakeWhileRef, TupleCombinations, Update, WhileSome, }; #[allow(deprecated)] pub use crate::adaptors::{MapResults, Step}; #[cfg(feature = "use_alloc")] - pub use crate::adaptors::MultiProduct; - #[cfg(feature = "use_alloc")] pub use crate::combinations::Combinations; #[cfg(feature = "use_alloc")] pub use crate::combinations_with_replacement::CombinationsWithReplacement; pub use crate::cons_tuples_impl::ConsTuples; + #[cfg(feature = "use_std")] + pub use crate::duplicates_impl::{Duplicates, DuplicatesBy}; pub use crate::exactly_one_err::ExactlyOneError; - pub use crate::format::{Format, FormatWith}; pub use crate::flatten_ok::FlattenOk; + pub use crate::format::{Format, FormatWith}; + #[cfg(feature = "use_alloc")] + pub use crate::groupbylazy::{Chunk, Chunks, Group, GroupBy, Groups, IntoChunks}; #[cfg(feature = "use_std")] pub use crate::grouping_map::{GroupingMap, GroupingMapBy}; - #[cfg(feature = "use_alloc")] - pub use crate::groupbylazy::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups}; pub use crate::intersperse::{Intersperse, IntersperseWith}; #[cfg(feature = "use_alloc")] pub use crate::kmerge_impl::{KMerge, KMergeBy}; pub use crate::merge_join::MergeJoinBy; #[cfg(feature = "use_alloc")] pub use crate::multipeek_impl::MultiPeek; + pub use crate::pad_tail::PadUsing; #[cfg(feature = "use_alloc")] pub use crate::peek_nth::PeekNth; - pub use crate::pad_tail::PadUsing; pub use crate::peeking_take_while::PeekingTakeWhile; #[cfg(feature = "use_alloc")] pub use crate::permutations::Permutations; - pub use crate::process_results_impl::ProcessResults; #[cfg(feature = "use_alloc")] pub use crate::powerset::Powerset; + pub use crate::process_results_impl::ProcessResults; #[cfg(feature = "use_alloc")] pub use crate::put_back_n_impl::PutBackN; #[cfg(feature = "use_alloc")] pub use crate::rciter_impl::RcIter; pub use crate::repeatn::RepeatN; #[allow(deprecated)] - pub use crate::sources::{RepeatCall, Unfold, Iterate}; + pub use crate::sources::{Iterate, RepeatCall, Unfold}; #[cfg(feature = "use_alloc")] pub use crate::tee::Tee; - pub use crate::tuple_impl::{TupleBuffer, TupleWindows, CircularTupleWindows, Tuples}; - #[cfg(feature = "use_std")] - pub use crate::duplicates_impl::{Duplicates, DuplicatesBy}; + pub use crate::tuple_impl::{CircularTupleWindows, TupleBuffer, TupleWindows, Tuples}; #[cfg(feature = "use_std")] pub use crate::unique_impl::{Unique, UniqueBy}; pub use crate::with_position::WithPosition; @@ -164,22 +143,22 @@ pub mod traits { pub use crate::tuple_impl::HomogeneousTuple; } -#[allow(deprecated)] -pub use crate::structs::*; pub use crate::concat_impl::concat; pub use crate::cons_tuples_impl::cons_tuples; pub use crate::diff::diff_with; pub use crate::diff::Diff; #[cfg(feature = "use_alloc")] -pub use crate::kmerge_impl::{kmerge_by}; +pub use crate::kmerge_impl::kmerge_by; pub use crate::minmax::MinMaxResult; pub use crate::peeking_take_while::PeekingNext; pub use crate::process_results_impl::process_results; pub use crate::repeatn::repeat_n; #[allow(deprecated)] -pub use crate::sources::{repeat_call, unfold, iterate}; -pub use crate::with_position::Position; +pub use crate::sources::{iterate, repeat_call, unfold}; +#[allow(deprecated)] +pub use crate::structs::*; pub use crate::unziptuple::{multiunzip, MultiUnzip}; +pub use crate::with_position::Position; pub use crate::ziptuple::multizip; mod adaptors; mod either_or_both; @@ -188,24 +167,26 @@ pub use crate::either_or_both::EitherOrBoth; pub mod free; #[doc(inline)] pub use crate::free::*; -mod concat_impl; -mod cons_tuples_impl; #[cfg(feature = "use_alloc")] mod combinations; #[cfg(feature = "use_alloc")] mod combinations_with_replacement; -mod exactly_one_err; +mod concat_impl; +mod cons_tuples_impl; mod diff; -mod flatten_ok; +#[cfg(feature = "use_std")] +mod duplicates_impl; +mod exactly_one_err; #[cfg(feature = "use_std")] mod extrema_set; +mod flatten_ok; mod format; -#[cfg(feature = "use_std")] -mod grouping_map; #[cfg(feature = "use_alloc")] mod group_map; #[cfg(feature = "use_alloc")] mod groupbylazy; +#[cfg(feature = "use_std")] +mod grouping_map; mod intersperse; #[cfg(feature = "use_alloc")] mod k_smallest; @@ -237,8 +218,6 @@ mod sources; mod tee; mod tuple_impl; #[cfg(feature = "use_std")] -mod duplicates_impl; -#[cfg(feature = "use_std")] mod unique_impl; mod unziptuple; mod with_position; @@ -428,7 +407,7 @@ macro_rules! chain { /// return a regular value of some other kind. /// [`.next_tuple()`](Itertools::next_tuple) is an example and the first regular /// method in the list. -pub trait Itertools : Iterator { +pub trait Itertools: Iterator { // adaptors /// Alternate elements from two iterators until both have run out. @@ -444,8 +423,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]); /// ``` fn interleave(self, other: J) -> Interleave - where J: IntoIterator, - Self: Sized + where + J: IntoIterator, + Self: Sized, { interleave(self, other) } @@ -462,8 +442,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]); /// ``` fn interleave_shortest(self, other: J) -> InterleaveShortest - where J: IntoIterator, - Self: Sized + where + J: IntoIterator, + Self: Sized, { adaptors::interleave_shortest(self, other.into_iter()) } @@ -481,8 +462,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]); /// ``` fn intersperse(self, element: Self::Item) -> Intersperse - where Self: Sized, - Self::Item: Clone + where + Self: Sized, + Self::Item: Clone, { intersperse::intersperse(self, element) } @@ -502,8 +484,9 @@ pub trait Itertools : Iterator { /// assert_eq!(i, 8); /// ``` fn intersperse_with(self, element: F) -> IntersperseWith - where Self: Sized, - F: FnMut() -> Self::Item + where + Self: Sized, + F: FnMut() -> Self::Item, { intersperse::intersperse_with(self, element) } @@ -536,8 +519,9 @@ pub trait Itertools : Iterator { /// ``` #[inline] fn zip_longest(self, other: J) -> ZipLongest - where J: IntoIterator, - Self: Sized + where + J: IntoIterator, + Self: Sized, { zip_longest::zip_longest(self, other.into_iter()) } @@ -549,8 +533,9 @@ pub trait Itertools : Iterator { /// lengths. #[inline] fn zip_eq(self, other: J) -> ZipEq - where J: IntoIterator, - Self: Sized + where + J: IntoIterator, + Self: Sized, { zip_eq(self, other) } @@ -579,8 +564,9 @@ pub trait Itertools : Iterator { /// ``` /// fn batching(self, f: F) -> Batching - where F: FnMut(&mut Self) -> Option, - Self: Sized + where + F: FnMut(&mut Self) -> Option, + Self: Sized, { adaptors::batching(self, f) } @@ -621,9 +607,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn group_by(self, key: F) -> GroupBy - where Self: Sized, - F: FnMut(&Self::Item) -> K, - K: PartialEq, + where + Self: Sized, + F: FnMut(&Self::Item) -> K, + K: PartialEq, { groupbylazy::new(self, key) } @@ -657,7 +644,8 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn chunks(self, size: usize) -> IntoChunks - where Self: Sized, + where + Self: Sized, { assert!(size != 0); groupbylazy::new_chunks(self, size) @@ -697,9 +685,10 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]); /// ``` fn tuple_windows(self) -> TupleWindows - where Self: Sized + Iterator, - T: traits::HomogeneousTuple, - T::Item: Clone + where + Self: Sized + Iterator, + T: traits::HomogeneousTuple, + T::Item: Clone, { tuple_impl::tuple_windows(self) } @@ -732,9 +721,10 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)]); /// ``` fn circular_tuple_windows(self) -> CircularTupleWindows - where Self: Sized + Clone + Iterator + ExactSizeIterator, - T: tuple_impl::TupleCollect + Clone, - T::Item: Clone + where + Self: Sized + Clone + Iterator + ExactSizeIterator, + T: tuple_impl::TupleCollect + Clone, + T::Item: Clone, { tuple_impl::circular_tuple_windows(self) } @@ -770,8 +760,9 @@ pub trait Itertools : Iterator { /// /// See also [`Tuples::into_buffer`]. fn tuples(self) -> Tuples - where Self: Sized + Iterator, - T: traits::HomogeneousTuple + where + Self: Sized + Iterator, + T: traits::HomogeneousTuple, { tuple_impl::tuples(self) } @@ -795,8 +786,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn tee(self) -> (Tee, Tee) - where Self: Sized, - Self::Item: Clone + where + Self: Sized, + Self::Item: Clone, { tee::new(self) } @@ -817,10 +809,11 @@ pub trait Itertools : Iterator { /// let it = (0..8).step(3); /// itertools::assert_equal(it, vec![0, 3, 6]); /// ``` - #[deprecated(note="Use std .step_by() instead", since="0.8.0")] + #[deprecated(note = "Use std .step_by() instead", since = "0.8.0")] #[allow(deprecated)] fn step(self, n: usize) -> Step - where Self: Sized + where + Self: Sized, { adaptors::step(self, n) } @@ -833,17 +826,19 @@ pub trait Itertools : Iterator { /// (1i32..42i32).map_into::().collect_vec(); /// ``` fn map_into(self) -> MapInto - where Self: Sized, - Self::Item: Into, + where + Self: Sized, + Self::Item: Into, { adaptors::map_into(self) } /// See [`.map_ok()`](Itertools::map_ok). - #[deprecated(note="Use .map_ok() instead", since="0.10.0")] + #[deprecated(note = "Use .map_ok() instead", since = "0.10.0")] fn map_results(self, f: F) -> MapOk - where Self: Iterator> + Sized, - F: FnMut(T) -> U, + where + Self: Iterator> + Sized, + F: FnMut(T) -> U, { self.map_ok(f) } @@ -860,8 +855,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]); /// ``` fn map_ok(self, f: F) -> MapOk - where Self: Iterator> + Sized, - F: FnMut(T) -> U, + where + Self: Iterator> + Sized, + F: FnMut(T) -> U, { adaptors::map_ok(self, f) } @@ -878,8 +874,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![Ok(22), Err(false)]); /// ``` fn filter_ok(self, f: F) -> FilterOk - where Self: Iterator> + Sized, - F: FnMut(&T) -> bool, + where + Self: Iterator> + Sized, + F: FnMut(&T) -> bool, { adaptors::filter_ok(self, f) } @@ -896,15 +893,16 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![Ok(44), Err(false)]); /// ``` fn filter_map_ok(self, f: F) -> FilterMapOk - where Self: Iterator> + Sized, - F: FnMut(T) -> Option, + where + Self: Iterator> + Sized, + F: FnMut(T) -> Option, { adaptors::filter_map_ok(self, f) } /// Return an iterator adaptor that flattens every `Result::Ok` value into /// a series of `Result::Ok` values. `Result::Err` values are unchanged. - /// + /// /// This is useful when you have some common error type for your crate and /// need to propagate it upwards, but the `Result::Ok` case needs to be flattened. /// @@ -914,14 +912,15 @@ pub trait Itertools : Iterator { /// let input = vec![Ok(0..2), Err(false), Ok(2..4)]; /// let it = input.iter().cloned().flatten_ok(); /// itertools::assert_equal(it.clone(), vec![Ok(0), Ok(1), Err(false), Ok(2), Ok(3)]); - /// + /// /// // This can also be used to propagate errors when collecting. /// let output_result: Result, bool> = it.collect(); /// assert_eq!(output_result, Err(false)); /// ``` fn flatten_ok(self) -> FlattenOk - where Self: Iterator> + Sized, - T: IntoIterator + where + Self: Iterator> + Sized, + T: IntoIterator, { flatten_ok::flatten_ok(self) } @@ -941,9 +940,10 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]); /// ``` fn merge(self, other: J) -> Merge - where Self: Sized, - Self::Item: PartialOrd, - J: IntoIterator + where + Self: Sized, + Self::Item: PartialOrd, + J: IntoIterator, { merge(self, other) } @@ -965,9 +965,10 @@ pub trait Itertools : Iterator { /// ``` fn merge_by(self, other: J, is_first: F) -> MergeBy - where Self: Sized, - J: IntoIterator, - F: FnMut(&Self::Item, &Self::Item) -> bool + where + Self: Sized, + J: IntoIterator, + F: FnMut(&Self::Item, &Self::Item) -> bool, { adaptors::merge_by_new(self, other.into_iter(), is_first) } @@ -1001,9 +1002,10 @@ pub trait Itertools : Iterator { /// ``` #[inline] fn merge_join_by(self, other: J, cmp_fn: F) -> MergeJoinBy - where J: IntoIterator, - F: FnMut(&Self::Item, &J::Item) -> std::cmp::Ordering, - Self: Sized + where + J: IntoIterator, + F: FnMut(&Self::Item, &J::Item) -> std::cmp::Ordering, + Self: Sized, { merge_join_by(self, other, cmp_fn) } @@ -1026,9 +1028,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn kmerge(self) -> KMerge<::IntoIter> - where Self: Sized, - Self::Item: IntoIterator, - ::Item: PartialOrd, + where + Self: Sized, + Self::Item: IntoIterator, + ::Item: PartialOrd, { kmerge(self) } @@ -1054,12 +1057,11 @@ pub trait Itertools : Iterator { /// assert_eq!(it.last(), Some(-7.)); /// ``` #[cfg(feature = "use_alloc")] - fn kmerge_by(self, first: F) - -> KMergeBy<::IntoIter, F> - where Self: Sized, - Self::Item: IntoIterator, - F: FnMut(&::Item, - &::Item) -> bool + fn kmerge_by(self, first: F) -> KMergeBy<::IntoIter, F> + where + Self: Sized, + Self::Item: IntoIterator, + F: FnMut(&::Item, &::Item) -> bool, { kmerge_by(self, first) } @@ -1076,10 +1078,11 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]); /// ``` fn cartesian_product(self, other: J) -> Product - where Self: Sized, - Self::Item: Clone, - J: IntoIterator, - J::IntoIter: Clone + where + Self: Sized, + Self::Item: Clone, + J: IntoIterator, + J::IntoIter: Clone, { adaptors::cartesian_product(self, other.into_iter()) } @@ -1111,10 +1114,11 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn multi_cartesian_product(self) -> MultiProduct<::IntoIter> - where Self: Iterator + Sized, - Self::Item: IntoIterator, - ::IntoIter: Clone, - ::Item: Clone + where + Self: Iterator + Sized, + Self::Item: IntoIterator, + ::IntoIter: Clone, + ::Item: Clone, { adaptors::multi_cartesian_product(self) } @@ -1148,9 +1152,9 @@ pub trait Itertools : Iterator { /// vec![-6., 4., -1.]); /// ``` fn coalesce(self, f: F) -> Coalesce - where Self: Sized, - F: FnMut(Self::Item, Self::Item) - -> Result + where + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> Result, { adaptors::coalesce(self, f) } @@ -1170,8 +1174,9 @@ pub trait Itertools : Iterator { /// vec![1., 2., 3., 2.]); /// ``` fn dedup(self) -> Dedup - where Self: Sized, - Self::Item: PartialEq, + where + Self: Sized, + Self::Item: PartialEq, { adaptors::dedup(self) } @@ -1192,8 +1197,9 @@ pub trait Itertools : Iterator { /// vec![(0, 1.), (0, 2.), (0, 3.), (1, 2.)]); /// ``` fn dedup_by(self, cmp: Cmp) -> DedupBy - where Self: Sized, - Cmp: FnMut(&Self::Item, &Self::Item)->bool, + where + Self: Sized, + Cmp: FnMut(&Self::Item, &Self::Item) -> bool, { adaptors::dedup_by(self, cmp) } @@ -1260,8 +1266,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn duplicates(self) -> Duplicates - where Self: Sized, - Self::Item: Eq + Hash + where + Self: Sized, + Self::Item: Eq + Hash, { duplicates_impl::duplicates(self) } @@ -1285,9 +1292,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn duplicates_by(self, f: F) -> DuplicatesBy - where Self: Sized, - V: Eq + Hash, - F: FnMut(&Self::Item) -> V + where + Self: Sized, + V: Eq + Hash, + F: FnMut(&Self::Item) -> V, { duplicates_impl::duplicates_by(self, f) } @@ -1312,8 +1320,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn unique(self) -> Unique - where Self: Sized, - Self::Item: Clone + Eq + Hash + where + Self: Sized, + Self::Item: Clone + Eq + Hash, { unique_impl::unique(self) } @@ -1338,9 +1347,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn unique_by(self, f: F) -> UniqueBy - where Self: Sized, - V: Eq + Hash, - F: FnMut(&Self::Item) -> V + where + Self: Sized, + V: Eq + Hash, + F: FnMut(&Self::Item) -> V, { unique_impl::unique_by(self, f) } @@ -1358,8 +1368,9 @@ pub trait Itertools : Iterator { /// See also [`.take_while_ref()`](Itertools::take_while_ref) /// which is a similar adaptor. fn peeking_take_while(&mut self, accept: F) -> PeekingTakeWhile - where Self: Sized + PeekingNext, - F: FnMut(&Self::Item) -> bool, + where + Self: Sized + PeekingNext, + F: FnMut(&Self::Item) -> bool, { peeking_take_while::peeking_take_while(self, accept) } @@ -1383,8 +1394,9 @@ pub trait Itertools : Iterator { /// /// ``` fn take_while_ref(&mut self, accept: F) -> TakeWhileRef - where Self: Clone, - F: FnMut(&Self::Item) -> bool + where + Self: Clone, + F: FnMut(&Self::Item) -> bool, { adaptors::take_while_ref(self, accept) } @@ -1404,7 +1416,8 @@ pub trait Itertools : Iterator { /// /// ``` fn while_some(self) -> WhileSome - where Self: Sized + Iterator> + where + Self: Sized + Iterator>, { adaptors::while_some(self) } @@ -1443,9 +1456,10 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]); /// ``` fn tuple_combinations(self) -> TupleCombinations - where Self: Sized + Clone, - Self::Item: Clone, - T: adaptors::HasCombination, + where + Self: Sized + Clone, + Self::Item: Clone, + T: adaptors::HasCombination, { adaptors::tuple_combinations(self) } @@ -1481,8 +1495,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn combinations(self, k: usize) -> Combinations - where Self: Sized, - Self::Item: Clone + where + Self: Sized, + Self::Item: Clone, { combinations::combinations(self, k) } @@ -1554,8 +1569,9 @@ pub trait Itertools : Iterator { /// re-iterated if the permutations adaptor is completed and re-iterated. #[cfg(feature = "use_alloc")] fn permutations(self, k: usize) -> Permutations - where Self: Sized, - Self::Item: Clone + where + Self: Sized, + Self::Item: Clone, { permutations::permutations(self, k) } @@ -1590,8 +1606,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn powerset(self) -> Powerset - where Self: Sized, - Self::Item: Clone, + where + Self: Sized, + Self::Item: Clone, { powerset::powerset(self) } @@ -1614,8 +1631,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]); /// ``` fn pad_using(self, min: usize, f: F) -> PadUsing - where Self: Sized, - F: FnMut(usize) -> Self::Item + where + Self: Sized, + F: FnMut(usize) -> Self::Item, { pad_tail::pad_using(self, min, f) } @@ -1640,7 +1658,8 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![Position::Only(0)]); /// ``` fn with_position(self) -> WithPosition - where Self: Sized, + where + Self: Sized, { with_position::with_position(self) } @@ -1659,8 +1678,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]); /// ``` fn positions

(self, predicate: P) -> Positions - where Self: Sized, - P: FnMut(Self::Item) -> bool, + where + Self: Sized, + P: FnMut(Self::Item) -> bool, { adaptors::positions(self, predicate) } @@ -1676,8 +1696,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]); /// ``` fn update(self, updater: F) -> Update - where Self: Sized, - F: FnMut(&mut Self::Item), + where + Self: Sized, + F: FnMut(&mut Self::Item), { adaptors::update(self, updater) } @@ -1697,8 +1718,9 @@ pub trait Itertools : Iterator { /// assert_eq!(Some((1, 2)), iter.next_tuple()); /// ``` fn next_tuple(&mut self) -> Option - where Self: Sized + Iterator, - T: traits::HomogeneousTuple + where + Self: Sized + Iterator, + T: traits::HomogeneousTuple, { T::collect_from_iter_no_buf(self) } @@ -1722,19 +1744,19 @@ pub trait Itertools : Iterator { /// } /// ``` fn collect_tuple(mut self) -> Option - where Self: Sized + Iterator, - T: traits::HomogeneousTuple + where + Self: Sized + Iterator, + T: traits::HomogeneousTuple, { match self.next_tuple() { elt @ Some(_) => match self.next() { Some(_) => None, None => elt, }, - _ => None + _ => None, } } - /// Find the position and value of the first element satisfying a predicate. /// /// The iterator is not advanced past the first element found. @@ -1746,7 +1768,8 @@ pub trait Itertools : Iterator { /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α'))); /// ``` fn find_position

(&mut self, mut pred: P) -> Option<(usize, Self::Item)> - where P: FnMut(&Self::Item) -> bool + where + P: FnMut(&Self::Item) -> bool, { let mut index = 0usize; for elt in self { @@ -1770,12 +1793,20 @@ pub trait Itertools : Iterator { /// assert_eq!(std::iter::empty::().find_or_last(|&x| x > 5), None); /// ``` fn find_or_last

(mut self, mut predicate: P) -> Option - where Self: Sized, - P: FnMut(&Self::Item) -> bool, + where + Self: Sized, + P: FnMut(&Self::Item) -> bool, { let mut prev = None; - self.find_map(|x| if predicate(&x) { Some(x) } else { prev = Some(x); None }) - .or(prev) + self.find_map(|x| { + if predicate(&x) { + Some(x) + } else { + prev = Some(x); + None + } + }) + .or(prev) } /// Find the value of the first element satisfying a predicate or return the first element, if any. /// @@ -1790,8 +1821,9 @@ pub trait Itertools : Iterator { /// assert_eq!(std::iter::empty::().find_or_first(|&x| x > 5), None); /// ``` fn find_or_first

(mut self, mut predicate: P) -> Option - where Self: Sized, - P: FnMut(&Self::Item) -> bool, + where + Self: Sized, + P: FnMut(&Self::Item) -> bool, { let first = self.next()?; Some(if predicate(&first) { @@ -1812,14 +1844,14 @@ pub trait Itertools : Iterator { /// /// #[derive(PartialEq, Debug)] /// enum Enum { A, B, C, D, E, } - /// + /// /// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter(); - /// + /// /// // search `iter` for `B` /// assert_eq!(iter.contains(&Enum::B), true); /// // `B` was found, so the iterator now rests at the item after `B` (i.e, `C`). /// assert_eq!(iter.next(), Some(Enum::C)); - /// + /// /// // search `iter` for `E` /// assert_eq!(iter.contains(&Enum::E), false); /// // `E` wasn't found, so `iter` is now exhausted @@ -1851,8 +1883,9 @@ pub trait Itertools : Iterator { /// assert!(data.into_iter().all_equal()); /// ``` fn all_equal(&mut self) -> bool - where Self: Sized, - Self::Item: PartialEq, + where + Self: Sized, + Self::Item: PartialEq, { match self.next() { None => true, @@ -1877,8 +1910,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn all_unique(&mut self) -> bool - where Self: Sized, - Self::Item: Eq + Hash + where + Self: Sized, + Self::Item: Eq + Hash, { let mut used = HashSet::new(); self.all(move |elt| used.insert(elt)) @@ -1900,7 +1934,8 @@ pub trait Itertools : Iterator { /// *Fusing notes: if the iterator is exhausted by dropping, /// the result of calling `.next()` again depends on the iterator implementation.* fn dropping(mut self, n: usize) -> Self - where Self: Sized + where + Self: Sized, { if n > 0 { self.nth(n - 1); @@ -1924,8 +1959,9 @@ pub trait Itertools : Iterator { /// itertools::assert_equal(init, vec![0, 3, 6]); /// ``` fn dropping_back(mut self, n: usize) -> Self - where Self: Sized, - Self: DoubleEndedIterator + where + Self: Sized, + Self: DoubleEndedIterator, { if n > 0 { (&mut self).rev().nth(n - 1); @@ -1950,10 +1986,11 @@ pub trait Itertools : Iterator { /// /// itertools::assert_equal(rx.iter(), vec![1, 3, 5, 7, 9]); /// ``` - #[deprecated(note="Use .for_each() instead", since="0.8.0")] + #[deprecated(note = "Use .for_each() instead", since = "0.8.0")] fn foreach(self, f: F) - where F: FnMut(Self::Item), - Self: Sized, + where + F: FnMut(Self::Item), + Self: Sized, { self.for_each(f) } @@ -1972,8 +2009,10 @@ pub trait Itertools : Iterator { /// vec![1, 2, 3, 4, 5, 6]); /// ``` fn concat(self) -> Self::Item - where Self: Sized, - Self::Item: Extend<<::Item as IntoIterator>::Item> + IntoIterator + Default + where + Self: Sized, + Self::Item: + Extend<<::Item as IntoIterator>::Item> + IntoIterator + Default, { concat(self) } @@ -1982,7 +2021,8 @@ pub trait Itertools : Iterator { /// for convenience. #[cfg(feature = "use_alloc")] fn collect_vec(self) -> Vec - where Self: Sized + where + Self: Sized, { self.collect() } @@ -2033,8 +2073,9 @@ pub trait Itertools : Iterator { /// ``` #[inline] fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize - where Self: Iterator, - J: IntoIterator + where + Self: Iterator, + J: IntoIterator, { let mut count = 0; for elt in from { @@ -2059,7 +2100,8 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn join(&mut self, sep: &str) -> String - where Self::Item: std::fmt::Display + where + Self::Item: std::fmt::Display, { match self.next() { None => String::new(), @@ -2093,7 +2135,8 @@ pub trait Itertools : Iterator { /// "1.10, 2.72, -3.00"); /// ``` fn format(self, sep: &str) -> Format - where Self: Sized, + where + Self: Sized, { format::new_format_default(self, sep) } @@ -2131,17 +2174,19 @@ pub trait Itertools : Iterator { /// /// ``` fn format_with(self, sep: &str, format: F) -> FormatWith - where Self: Sized, - F: FnMut(Self::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result, + where + Self: Sized, + F: FnMut(Self::Item, &mut dyn FnMut(&dyn fmt::Display) -> fmt::Result) -> fmt::Result, { format::new_format(self, sep, format) } /// See [`.fold_ok()`](Itertools::fold_ok). - #[deprecated(note="Use .fold_ok() instead", since="0.10.0")] + #[deprecated(note = "Use .fold_ok() instead", since = "0.10.0")] fn fold_results(&mut self, start: B, f: F) -> Result - where Self: Iterator>, - F: FnMut(B, A) -> B + where + Self: Iterator>, + F: FnMut(B, A) -> B, { self.fold_ok(start, f) } @@ -2189,8 +2234,9 @@ pub trait Itertools : Iterator { /// ); /// ``` fn fold_ok(&mut self, mut start: B, mut f: F) -> Result - where Self: Iterator>, - F: FnMut(B, A) -> B + where + Self: Iterator>, + F: FnMut(B, A) -> B, { for elt in self { match elt { @@ -2221,8 +2267,9 @@ pub trait Itertools : Iterator { /// assert_eq!(more_values.next().unwrap(), Some(0)); /// ``` fn fold_options(&mut self, mut start: B, mut f: F) -> Option - where Self: Iterator>, - F: FnMut(B, A) -> B + where + Self: Iterator>, + F: FnMut(B, A) -> B, { for elt in self { match elt { @@ -2247,8 +2294,9 @@ pub trait Itertools : Iterator { /// ``` #[deprecated(since = "0.10.2", note = "Use `Iterator::reduce` instead")] fn fold1(mut self, f: F) -> Option - where F: FnMut(Self::Item, Self::Item) -> Self::Item, - Self: Sized, + where + F: FnMut(Self::Item, Self::Item) -> Self::Item, + Self: Sized, { self.next().map(move |x| self.fold(x, f)) } @@ -2302,44 +2350,48 @@ pub trait Itertools : Iterator { /// (0..10).fold1(|x, y| x - y)); /// ``` fn tree_fold1(mut self, mut f: F) -> Option - where F: FnMut(Self::Item, Self::Item) -> Self::Item, - Self: Sized, + where + F: FnMut(Self::Item, Self::Item) -> Self::Item, + Self: Sized, { type State = Result>; fn inner0(it: &mut II, f: &mut FF) -> State - where - II: Iterator, - FF: FnMut(T, T) -> T + where + II: Iterator, + FF: FnMut(T, T) -> T, { // This function could be replaced with `it.next().ok_or(None)`, // but half the useful tree_fold1 work is combining adjacent items, // so put that in a form that LLVM is more likely to optimize well. - let a = - if let Some(v) = it.next() { v } - else { return Err(None) }; - let b = - if let Some(v) = it.next() { v } - else { return Err(Some(a)) }; + let a = if let Some(v) = it.next() { + v + } else { + return Err(None); + }; + let b = if let Some(v) = it.next() { + v + } else { + return Err(Some(a)); + }; Ok(f(a, b)) } fn inner(stop: usize, it: &mut II, f: &mut FF) -> State - where - II: Iterator, - FF: FnMut(T, T) -> T + where + II: Iterator, + FF: FnMut(T, T) -> T, { let mut x = inner0(it, f)?; for height in 0..stop { // Try to get another tree the same size with which to combine it, // creating a new tree that's twice as big for next time around. - let next = - if height == 0 { - inner0(it, f) - } else { - inner(height, it, f) - }; + let next = if height == 0 { + inner0(it, f) + } else { + inner(height, it, f) + }; match next { Ok(y) => x = f(x, y), @@ -2400,19 +2452,19 @@ pub trait Itertools : Iterator { /// `fold()` called the provided closure for every item of the callee iterator, /// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`. fn fold_while(&mut self, init: B, mut f: F) -> FoldWhile - where Self: Sized, - F: FnMut(B, Self::Item) -> FoldWhile - { - use Result::{ - Ok as Continue, - Err as Break, - }; - - let result = self.try_fold(init, #[inline(always)] |acc, v| - match f(acc, v) { - FoldWhile::Continue(acc) => Continue(acc), - FoldWhile::Done(acc) => Break(acc), - } + where + Self: Sized, + F: FnMut(B, Self::Item) -> FoldWhile, + { + use Result::{Err as Break, Ok as Continue}; + + let result = self.try_fold( + init, + #[inline(always)] + |acc, v| match f(acc, v) { + FoldWhile::Continue(acc) => Continue(acc), + FoldWhile::Done(acc) => Break(acc), + }, ); match result { @@ -2443,11 +2495,11 @@ pub trait Itertools : Iterator { /// assert_eq!(nonempty_sum, Some(55)); /// ``` fn sum1(mut self) -> Option - where Self: Sized, - S: std::iter::Sum, + where + Self: Sized, + S: std::iter::Sum, { - self.next() - .map(|first| once(first).chain(self).sum()) + self.next().map(|first| once(first).chain(self).sum()) } /// Iterate over the entire iterator and multiply all the elements. @@ -2471,11 +2523,11 @@ pub trait Itertools : Iterator { /// assert_eq!(nonempty_product, Some(3628800)); /// ``` fn product1

(mut self) -> Option

- where Self: Sized, - P: std::iter::Product, + where + Self: Sized, + P: std::iter::Product, { - self.next() - .map(|first| once(first).chain(self).product()) + self.next().map(|first| once(first).chain(self).product()) } /// Sort all iterator elements into a new iterator in ascending order. @@ -2497,8 +2549,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted_unstable(self) -> VecIntoIter - where Self: Sized, - Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { // Use .sort_unstable() directly since it is not quite identical with // .sort_by(Ord::cmp) @@ -2532,8 +2585,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted_unstable_by(self, cmp: F) -> VecIntoIter - where Self: Sized, - F: FnMut(&Self::Item, &Self::Item) -> Ordering, + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { let mut v = Vec::from_iter(self); v.sort_unstable_by(cmp); @@ -2565,9 +2619,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted_unstable_by_key(self, f: F) -> VecIntoIter - where Self: Sized, - K: Ord, - F: FnMut(&Self::Item) -> K, + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { let mut v = Vec::from_iter(self); v.sort_unstable_by_key(f); @@ -2593,8 +2648,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted(self) -> VecIntoIter - where Self: Sized, - Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { // Use .sort() directly since it is not quite identical with // .sort_by(Ord::cmp) @@ -2628,8 +2684,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted_by(self, cmp: F) -> VecIntoIter - where Self: Sized, - F: FnMut(&Self::Item, &Self::Item) -> Ordering, + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { let mut v = Vec::from_iter(self); v.sort_by(cmp); @@ -2661,9 +2718,10 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn sorted_by_key(self, f: F) -> VecIntoIter - where Self: Sized, - K: Ord, - F: FnMut(&Self::Item) -> K, + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { let mut v = Vec::from_iter(self); v.sort_by_key(f); @@ -2736,8 +2794,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_alloc")] fn k_smallest(self, k: usize) -> VecIntoIter - where Self: Sized, - Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { crate::k_smallest::k_smallest(self, k) .into_sorted_vec() @@ -2766,10 +2825,11 @@ pub trait Itertools : Iterator { /// assert_eq!(failures, [false, true]); /// ``` fn partition_map(self, mut predicate: F) -> (A, B) - where Self: Sized, - F: FnMut(Self::Item) -> Either, - A: Default + Extend, - B: Default + Extend, + where + Self: Sized, + F: FnMut(Self::Item) -> Either, + A: Default + Extend, + B: Default + Extend, { let mut left = A::default(); let mut right = B::default(); @@ -2798,10 +2858,10 @@ pub trait Itertools : Iterator { /// assert_eq!(failures, [false, true]); /// ``` fn partition_result(self) -> (A, B) - where - Self: Iterator> + Sized, - A: Default + Extend, - B: Default + Extend, + where + Self: Iterator> + Sized, + A: Default + Extend, + B: Default + Extend, { self.partition_map(|r| match r { Ok(v) => Either::Left(v), @@ -2827,8 +2887,9 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn into_group_map(self) -> HashMap> - where Self: Iterator + Sized, - K: Hash + Eq, + where + Self: Iterator + Sized, + K: Hash + Eq, { group_map::into_group_map(self) } @@ -2862,44 +2923,46 @@ pub trait Itertools : Iterator { /// ``` #[cfg(feature = "use_std")] fn into_group_map_by(self, f: F) -> HashMap> - where - Self: Iterator + Sized, - K: Hash + Eq, - F: Fn(&V) -> K, + where + Self: Iterator + Sized, + K: Hash + Eq, + F: Fn(&V) -> K, { group_map::into_group_map_by(self, f) } - /// Constructs a `GroupingMap` to be used later with one of the efficient + /// Constructs a `GroupingMap` to be used later with one of the efficient /// group-and-fold operations it allows to perform. - /// + /// /// The input iterator must yield item in the form of `(K, V)` where the /// value of type `K` will be used as key to identify the groups and the /// value of type `V` as value for the folding operation. - /// + /// /// See [`GroupingMap`] for more informations /// on what operations are available. #[cfg(feature = "use_std")] fn into_grouping_map(self) -> GroupingMap - where Self: Iterator + Sized, - K: Hash + Eq, + where + Self: Iterator + Sized, + K: Hash + Eq, { grouping_map::new(self) } - /// Constructs a `GroupingMap` to be used later with one of the efficient + /// Constructs a `GroupingMap` to be used later with one of the efficient /// group-and-fold operations it allows to perform. - /// + /// /// The values from this iterator will be used as values for the folding operation /// while the keys will be obtained from the values by calling `key_mapper`. - /// + /// /// See [`GroupingMap`] for more informations /// on what operations are available. #[cfg(feature = "use_std")] fn into_grouping_map_by(self, key_mapper: F) -> GroupingMapBy - where Self: Iterator + Sized, - K: Hash + Eq, - F: FnMut(&V) -> K + where + Self: Iterator + Sized, + K: Hash + Eq, + F: FnMut(&V) -> K, { grouping_map::new(grouping_map::MapForGrouping::new(self, key_mapper)) } @@ -2928,7 +2991,9 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn min_set(self) -> Vec - where Self: Sized, Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { extrema_set::min_set_impl(self, |_| (), |x, y, _, _| x.cmp(y)) } @@ -2959,13 +3024,11 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn min_set_by(self, mut compare: F) -> Vec - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { - extrema_set::min_set_impl( - self, - |_| (), - |x, y, _, _| compare(x, y) - ) + extrema_set::min_set_impl(self, |_| (), |x, y, _, _| compare(x, y)) } /// Return all minimum elements of an iterator, as determined by @@ -2993,7 +3056,10 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn min_set_by_key(self, key: F) -> Vec - where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { extrema_set::min_set_impl(self, key, |_, _, kx, ky| kx.cmp(ky)) } @@ -3022,7 +3088,9 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn max_set(self) -> Vec - where Self: Sized, Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { extrema_set::max_set_impl(self, |_| (), |x, y, _, _| x.cmp(y)) } @@ -3053,13 +3121,11 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn max_set_by(self, mut compare: F) -> Vec - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { - extrema_set::max_set_impl( - self, - |_| (), - |x, y, _, _| compare(x, y) - ) + extrema_set::max_set_impl(self, |_| (), |x, y, _, _| compare(x, y)) } /// Return all minimum elements of an iterator, as determined by @@ -3087,7 +3153,10 @@ pub trait Itertools : Iterator { /// if an element is NaN. #[cfg(feature = "use_std")] fn max_set_by_key(self, key: F) -> Vec - where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { extrema_set::max_set_impl(self, key, |_, _, kx, ky| kx.cmp(ky)) } @@ -3128,7 +3197,9 @@ pub trait Itertools : Iterator { /// The elements can be floats but no particular result is guaranteed /// if an element is NaN. fn minmax(self) -> MinMaxResult - where Self: Sized, Self::Item: PartialOrd + where + Self: Sized, + Self::Item: PartialOrd, { minmax::minmax_impl(self, |_| (), |x, y, _, _| x < y) } @@ -3145,7 +3216,10 @@ pub trait Itertools : Iterator { /// The keys can be floats but no particular result is guaranteed /// if a key is NaN. fn minmax_by_key(self, key: F) -> MinMaxResult - where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: PartialOrd, + F: FnMut(&Self::Item) -> K, { minmax::minmax_impl(self, key, |_, _, xk, yk| xk < yk) } @@ -3159,13 +3233,11 @@ pub trait Itertools : Iterator { /// the last maximal element wins. This matches the behavior of the standard /// [`Iterator::min`] and [`Iterator::max`] methods. fn minmax_by(self, mut compare: F) -> MinMaxResult - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { - minmax::minmax_impl( - self, - |_| (), - |x, y, _, _| Ordering::Less == compare(x, y) - ) + minmax::minmax_impl(self, |_| (), |x, y, _, _| Ordering::Less == compare(x, y)) } /// Return the position of the maximum element in the iterator. @@ -3188,7 +3260,9 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_max(), Some(1)); /// ``` fn position_max(self) -> Option - where Self: Sized, Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { self.enumerate() .max_by(|x, y| Ord::cmp(&x.1, &y.1)) @@ -3216,7 +3290,10 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_max_by_key(|x| x.abs()), Some(3)); /// ``` fn position_max_by_key(self, mut key: F) -> Option - where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { self.enumerate() .max_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1))) @@ -3244,7 +3321,9 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(1)); /// ``` fn position_max_by(self, mut compare: F) -> Option - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { self.enumerate() .max_by(|x, y| compare(&x.1, &y.1)) @@ -3271,7 +3350,9 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_min(), Some(2)); /// ``` fn position_min(self) -> Option - where Self: Sized, Self::Item: Ord + where + Self: Sized, + Self::Item: Ord, { self.enumerate() .min_by(|x, y| Ord::cmp(&x.1, &y.1)) @@ -3299,7 +3380,10 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_min_by_key(|x| x.abs()), Some(0)); /// ``` fn position_min_by_key(self, mut key: F) -> Option - where Self: Sized, K: Ord, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: Ord, + F: FnMut(&Self::Item) -> K, { self.enumerate() .min_by(|x, y| Ord::cmp(&key(&x.1), &key(&y.1))) @@ -3327,7 +3411,9 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_min_by(|x, y| x.cmp(y)), Some(2)); /// ``` fn position_min_by(self, mut compare: F) -> Option - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { self.enumerate() .min_by(|x, y| compare(&x.1, &y.1)) @@ -3377,9 +3463,11 @@ pub trait Itertools : Iterator { /// assert_eq!(a.iter().position_minmax(), MinMax(2, 1)); /// ``` fn position_minmax(self) -> MinMaxResult - where Self: Sized, Self::Item: PartialOrd + where + Self: Sized, + Self::Item: PartialOrd, { - use crate::MinMaxResult::{NoElements, OneElement, MinMax}; + use crate::MinMaxResult::{MinMax, NoElements, OneElement}; match minmax::minmax_impl(self.enumerate(), |_| (), |x, y, _, _| x.1 < y.1) { NoElements => NoElements, OneElement(x) => OneElement(x.0), @@ -3422,9 +3510,12 @@ pub trait Itertools : Iterator { /// /// [`position_minmax`]: Self::position_minmax fn position_minmax_by_key(self, mut key: F) -> MinMaxResult - where Self: Sized, K: PartialOrd, F: FnMut(&Self::Item) -> K + where + Self: Sized, + K: PartialOrd, + F: FnMut(&Self::Item) -> K, { - use crate::MinMaxResult::{NoElements, OneElement, MinMax}; + use crate::MinMaxResult::{MinMax, NoElements, OneElement}; match self.enumerate().minmax_by_key(|e| key(&e.1)) { NoElements => NoElements, OneElement(x) => OneElement(x.0), @@ -3464,9 +3555,11 @@ pub trait Itertools : Iterator { /// /// [`position_minmax`]: Self::position_minmax fn position_minmax_by(self, mut compare: F) -> MinMaxResult - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { - use crate::MinMaxResult::{NoElements, OneElement, MinMax}; + use crate::MinMaxResult::{MinMax, NoElements, OneElement}; match self.enumerate().minmax_by(|x, y| compare(&x.1, &y.1)) { NoElements => NoElements, OneElement(x) => OneElement(x.0), @@ -3496,16 +3589,13 @@ pub trait Itertools : Iterator { Self: Sized, { match self.next() { - Some(first) => { - match self.next() { - Some(second) => { - Err(ExactlyOneError::new(Some(Either::Left([first, second])), self)) - } - None => { - Ok(first) - } - } - } + Some(first) => match self.next() { + Some(second) => Err(ExactlyOneError::new( + Some(Either::Left([first, second])), + self, + )), + None => Ok(first), + }, None => Err(ExactlyOneError::new(None, self)), } } @@ -3532,16 +3622,13 @@ pub trait Itertools : Iterator { Self: Sized, { match self.next() { - Some(first) => { - match self.next() { - Some(second) => { - Err(ExactlyOneError::new(Some(Either::Left([first, second])), self)) - } - None => { - Ok(Some(first)) - } - } - } + Some(first) => match self.next() { + Some(second) => Err(ExactlyOneError::new( + Some(Either::Left([first, second])), + self, + )), + None => Ok(Some(first)), + }, None => Ok(None), } } @@ -3603,7 +3690,7 @@ pub trait Itertools : Iterator { /// first_name: &'static str, /// last_name: &'static str, /// } - /// + /// /// let characters = /// vec![ /// Character { first_name: "Amy", last_name: "Pond" }, @@ -3614,8 +3701,8 @@ pub trait Itertools : Iterator { /// Character { first_name: "James", last_name: "Norington" }, /// Character { first_name: "James", last_name: "Kirk" }, /// ]; - /// - /// let first_name_frequency = + /// + /// let first_name_frequency = /// characters /// .into_iter() /// .counts_by(|c| c.first_name); @@ -3640,7 +3727,7 @@ pub trait Itertools : Iterator { /// column. /// /// This function is, in some sense, the opposite of [`multizip`]. - /// + /// /// ``` /// use itertools::Itertools; /// @@ -3662,7 +3749,7 @@ pub trait Itertools : Iterator { } } -impl Itertools for T where T: Iterator { } +impl Itertools for T where T: Iterator {} /// Return `true` if both iterables produce equal sequences /// (elements pairwise equal and sequences of the same length), @@ -3675,9 +3762,10 @@ impl Itertools for T where T: Iterator { } /// assert!(!itertools::equal(&[0, 0], &[0, 0, 0])); /// ``` pub fn equal(a: I, b: J) -> bool - where I: IntoIterator, - J: IntoIterator, - I::Item: PartialEq +where + I: IntoIterator, + J: IntoIterator, + I::Item: PartialEq, { a.into_iter().eq(b) } @@ -3693,10 +3781,11 @@ pub fn equal(a: I, b: J) -> bool /// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1', /// ``` pub fn assert_equal(a: I, b: J) - where I: IntoIterator, - J: IntoIterator, - I::Item: fmt::Debug + PartialEq, - J::Item: fmt::Debug, +where + I: IntoIterator, + J: IntoIterator, + I::Item: fmt::Debug + PartialEq, + J::Item: fmt::Debug, { let mut ia = a.into_iter(); let mut ib = b.into_iter(); @@ -3709,8 +3798,13 @@ pub fn assert_equal(a: I, b: J) (&Some(ref a), &Some(ref b)) => a == b, _ => false, }; - assert!(equal, "Failed assertion {a:?} == {b:?} for iteration {i}", - i=i, a=a, b=b); + assert!( + equal, + "Failed assertion {a:?} == {b:?} for iteration {i}", + i = i, + a = a, + b = b + ); i += 1; } } @@ -3735,9 +3829,10 @@ pub fn assert_equal(a: I, b: J) /// assert_eq!(split_index, 3); /// ``` pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize - where I: IntoIterator, - I::IntoIter: DoubleEndedIterator, - F: FnMut(&A) -> bool +where + I: IntoIterator, + I::IntoIter: DoubleEndedIterator, + F: FnMut(&A) -> bool, { let mut split_index = 0; let mut iter = iter.into_iter(); @@ -3745,10 +3840,12 @@ pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize if !pred(front) { loop { match iter.next_back() { - Some(back) => if pred(back) { - std::mem::swap(front, back); - break; - }, + Some(back) => { + if pred(back) { + std::mem::swap(front, back); + break; + } + } None => break 'main, } } diff --git a/src/merge_join.rs b/src/merge_join.rs index f2fbdea2c..53de78656 100644 --- a/src/merge_join.rs +++ b/src/merge_join.rs @@ -1,8 +1,8 @@ use std::cmp::Ordering; -use std::iter::Fuse; use std::fmt; +use std::iter::Fuse; -use super::adaptors::{PutBack, put_back}; +use super::adaptors::{put_back, PutBack}; use crate::either_or_both::EitherOrBoth; #[cfg(doc)] use crate::Itertools; @@ -10,11 +10,15 @@ use crate::Itertools; /// Return an iterator adaptor that merge-joins items from the two base iterators in ascending order. /// /// [`IntoIterator`] enabled version of [`Itertools::merge_join_by`]. -pub fn merge_join_by(left: I, right: J, cmp_fn: F) - -> MergeJoinBy - where I: IntoIterator, - J: IntoIterator, - F: FnMut(&I::Item, &J::Item) -> Ordering +pub fn merge_join_by( + left: I, + right: J, + cmp_fn: F, +) -> MergeJoinBy +where + I: IntoIterator, + J: IntoIterator, + F: FnMut(&I::Item, &J::Item) -> Ordering, { MergeJoinBy { left: put_back(left.into_iter().fuse()), @@ -30,56 +34,54 @@ pub fn merge_join_by(left: I, right: J, cmp_fn: F) pub struct MergeJoinBy { left: PutBack>, right: PutBack>, - cmp_fn: F + cmp_fn: F, } impl Clone for MergeJoinBy - where I: Iterator, - J: Iterator, - PutBack>: Clone, - PutBack>: Clone, - F: Clone, +where + I: Iterator, + J: Iterator, + PutBack>: Clone, + PutBack>: Clone, + F: Clone, { clone_fields!(left, right, cmp_fn); } impl fmt::Debug for MergeJoinBy - where I: Iterator + fmt::Debug, - I::Item: fmt::Debug, - J: Iterator + fmt::Debug, - J::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: fmt::Debug, + J: Iterator + fmt::Debug, + J::Item: fmt::Debug, { debug_fmt_fields!(MergeJoinBy, left, right); } impl Iterator for MergeJoinBy - where I: Iterator, - J: Iterator, - F: FnMut(&I::Item, &J::Item) -> Ordering +where + I: Iterator, + J: Iterator, + F: FnMut(&I::Item, &J::Item) -> Ordering, { type Item = EitherOrBoth; fn next(&mut self) -> Option { match (self.left.next(), self.right.next()) { (None, None) => None, - (Some(left), None) => - Some(EitherOrBoth::Left(left)), - (None, Some(right)) => - Some(EitherOrBoth::Right(right)), - (Some(left), Some(right)) => { - match (self.cmp_fn)(&left, &right) { - Ordering::Equal => - Some(EitherOrBoth::Both(left, right)), - Ordering::Less => { - self.right.put_back(right); - Some(EitherOrBoth::Left(left)) - }, - Ordering::Greater => { - self.left.put_back(left); - Some(EitherOrBoth::Right(right)) - } + (Some(left), None) => Some(EitherOrBoth::Left(left)), + (None, Some(right)) => Some(EitherOrBoth::Right(right)), + (Some(left), Some(right)) => match (self.cmp_fn)(&left, &right) { + Ordering::Equal => Some(EitherOrBoth::Both(left, right)), + Ordering::Less => { + self.right.put_back(right); + Some(EitherOrBoth::Left(left)) } - } + Ordering::Greater => { + self.left.put_back(left); + Some(EitherOrBoth::Right(right)) + } + }, } } diff --git a/src/minmax.rs b/src/minmax.rs index 52b2f115d..f04e5adba 100644 --- a/src/minmax.rs +++ b/src/minmax.rs @@ -1,4 +1,3 @@ - /// `MinMaxResult` is an enum returned by `minmax`. /// /// See [`.minmax()`](crate::Itertools::minmax) for more detail. @@ -12,7 +11,7 @@ pub enum MinMaxResult { /// More than one element in the iterator, the first element is not larger /// than the second - MinMax(T, T) + MinMax(T, T), } impl MinMaxResult { @@ -36,34 +35,36 @@ impl MinMaxResult { /// let r = MinMax(1, 2); /// assert_eq!(r.into_option(), Some((1, 2))); /// ``` - pub fn into_option(self) -> Option<(T,T)> { + pub fn into_option(self) -> Option<(T, T)> { match self { MinMaxResult::NoElements => None, MinMaxResult::OneElement(x) => Some((x.clone(), x)), - MinMaxResult::MinMax(x, y) => Some((x, y)) + MinMaxResult::MinMax(x, y) => Some((x, y)), } } } /// Implementation guts for `minmax` and `minmax_by_key`. -pub fn minmax_impl(mut it: I, mut key_for: F, - mut lt: L) -> MinMaxResult - where I: Iterator, - F: FnMut(&I::Item) -> K, - L: FnMut(&I::Item, &I::Item, &K, &K) -> bool, +pub fn minmax_impl(mut it: I, mut key_for: F, mut lt: L) -> MinMaxResult +where + I: Iterator, + F: FnMut(&I::Item) -> K, + L: FnMut(&I::Item, &I::Item, &K, &K) -> bool, { let (mut min, mut max, mut min_key, mut max_key) = match it.next() { None => return MinMaxResult::NoElements, - Some(x) => { - match it.next() { - None => return MinMaxResult::OneElement(x), - Some(y) => { - let xk = key_for(&x); - let yk = key_for(&y); - if !lt(&y, &x, &yk, &xk) {(x, y, xk, yk)} else {(y, x, yk, xk)} + Some(x) => match it.next() { + None => return MinMaxResult::OneElement(x), + Some(y) => { + let xk = key_for(&x); + let yk = key_for(&y); + if !lt(&y, &x, &yk, &xk) { + (x, y, xk, yk) + } else { + (y, x, yk, xk) } } - } + }, }; loop { @@ -74,7 +75,7 @@ pub fn minmax_impl(mut it: I, mut key_for: F, // for 2 elements. let first = match it.next() { None => break, - Some(x) => x + Some(x) => x, }; let second = match it.next() { None => { @@ -86,7 +87,7 @@ pub fn minmax_impl(mut it: I, mut key_for: F, } break; } - Some(x) => x + Some(x) => x, }; let first_key = key_for(&first); let second_key = key_for(&second); diff --git a/src/multipeek_impl.rs b/src/multipeek_impl.rs index 0ac9380b6..2bc1d4821 100644 --- a/src/multipeek_impl.rs +++ b/src/multipeek_impl.rs @@ -1,14 +1,15 @@ -use std::iter::Fuse; -use alloc::collections::VecDeque; use crate::size_hint; -use crate::PeekingNext; #[cfg(doc)] use crate::Itertools; +use crate::PeekingNext; +use alloc::collections::VecDeque; +use std::iter::Fuse; /// See [`multipeek()`] for more information. #[derive(Clone, Debug)] pub struct MultiPeek - where I: Iterator +where + I: Iterator, { iter: Fuse, buf: VecDeque, @@ -20,7 +21,8 @@ pub struct MultiPeek /// /// [`IntoIterator`] enabled version of [`Itertools::multipeek`]. pub fn multipeek(iterable: I) -> MultiPeek - where I: IntoIterator +where + I: IntoIterator, { MultiPeek { iter: iterable.into_iter().fuse(), @@ -30,7 +32,8 @@ pub fn multipeek(iterable: I) -> MultiPeek } impl MultiPeek - where I: Iterator +where + I: Iterator, { /// Reset the peeking “cursor” pub fn reset_peek(&mut self) { @@ -62,18 +65,24 @@ impl MultiPeek { } impl PeekingNext for MultiPeek - where I: Iterator, +where + I: Iterator, { fn peeking_next(&mut self, accept: F) -> Option - where F: FnOnce(&Self::Item) -> bool + where + F: FnOnce(&Self::Item) -> bool, { if self.buf.is_empty() { if let Some(r) = self.peek() { - if !accept(r) { return None } + if !accept(r) { + return None; + } } } else { if let Some(r) = self.buf.get(0) { - if !accept(r) { return None } + if !accept(r) { + return None; + } } } self.next() @@ -81,7 +90,8 @@ impl PeekingNext for MultiPeek } impl Iterator for MultiPeek - where I: Iterator +where + I: Iterator, { type Item = I::Item; @@ -96,8 +106,4 @@ impl Iterator for MultiPeek } // Same size -impl ExactSizeIterator for MultiPeek - where I: ExactSizeIterator -{} - - +impl ExactSizeIterator for MultiPeek where I: ExactSizeIterator {} diff --git a/src/pad_tail.rs b/src/pad_tail.rs index de57ee416..024c22659 100644 --- a/src/pad_tail.rs +++ b/src/pad_tail.rs @@ -1,5 +1,5 @@ -use std::iter::{Fuse, FusedIterator}; use crate::size_hint; +use std::iter::{Fuse, FusedIterator}; /// An iterator adaptor that pads a sequence to a minimum length by filling /// missing elements using a closure. @@ -25,8 +25,9 @@ where /// Create a new **PadUsing** iterator. pub fn pad_using(iter: I, min: usize, filler: F) -> PadUsing - where I: Iterator, - F: FnMut(usize) -> I::Item +where + I: Iterator, + F: FnMut(usize) -> I::Item, { PadUsing { iter: iter.fuse(), @@ -37,8 +38,9 @@ pub fn pad_using(iter: I, min: usize, filler: F) -> PadUsing } impl Iterator for PadUsing - where I: Iterator, - F: FnMut(usize) -> I::Item +where + I: Iterator, + F: FnMut(usize) -> I::Item, { type Item = I::Item; @@ -53,7 +55,7 @@ impl Iterator for PadUsing } else { None } - }, + } e => { self.pos += 1; e @@ -68,8 +70,9 @@ impl Iterator for PadUsing } impl DoubleEndedIterator for PadUsing - where I: DoubleEndedIterator + ExactSizeIterator, - F: FnMut(usize) -> I::Item +where + I: DoubleEndedIterator + ExactSizeIterator, + F: FnMut(usize) -> I::Item, { fn next_back(&mut self) -> Option { if self.min == 0 { @@ -85,12 +88,15 @@ impl DoubleEndedIterator for PadUsing } impl ExactSizeIterator for PadUsing - where I: ExactSizeIterator, - F: FnMut(usize) -> I::Item -{} - +where + I: ExactSizeIterator, + F: FnMut(usize) -> I::Item, +{ +} impl FusedIterator for PadUsing - where I: FusedIterator, - F: FnMut(usize) -> I::Item -{} +where + I: FusedIterator, + F: FnMut(usize) -> I::Item, +{ +} diff --git a/src/peeking_take_while.rs b/src/peeking_take_while.rs index cd0945a52..76062db83 100644 --- a/src/peeking_take_while.rs +++ b/src/peeking_take_while.rs @@ -1,7 +1,7 @@ -use std::iter::Peekable; use crate::PutBack; #[cfg(feature = "use_alloc")] use crate::PutBackN; +use std::iter::Peekable; /// An iterator that allows peeking at an element before deciding to accept it. /// @@ -11,19 +11,22 @@ use crate::PutBackN; /// This is implemented by peeking adaptors like peekable and put back, /// but also by a few iterators that can be peeked natively, like the slice’s /// by reference iterator (`std::slice::Iter`). -pub trait PeekingNext : Iterator { +pub trait PeekingNext: Iterator { /// Pass a reference to the next iterator element to the closure `accept`; /// if `accept` returns true, return it as the next element, /// else None. fn peeking_next(&mut self, accept: F) -> Option - where F: FnOnce(&Self::Item) -> bool; + where + F: FnOnce(&Self::Item) -> bool; } impl PeekingNext for Peekable - where I: Iterator, +where + I: Iterator, { fn peeking_next(&mut self, accept: F) -> Option - where F: FnOnce(&Self::Item) -> bool + where + F: FnOnce(&Self::Item) -> bool, { if let Some(r) = self.peek() { if !accept(r) { @@ -35,10 +38,12 @@ impl PeekingNext for Peekable } impl PeekingNext for PutBack - where I: Iterator, +where + I: Iterator, { fn peeking_next(&mut self, accept: F) -> Option - where F: FnOnce(&Self::Item) -> bool + where + F: FnOnce(&Self::Item) -> bool, { if let Some(r) = self.next() { if !accept(&r) { @@ -54,10 +59,12 @@ impl PeekingNext for PutBack #[cfg(feature = "use_alloc")] impl PeekingNext for PutBackN - where I: Iterator, +where + I: Iterator, { fn peeking_next(&mut self, accept: F) -> Option - where F: FnOnce(&Self::Item) -> bool + where + F: FnOnce(&Self::Item) -> bool, { if let Some(r) = self.next() { if !accept(&r) { @@ -77,7 +84,8 @@ impl PeekingNext for PutBackN /// for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct PeekingTakeWhile<'a, I: 'a, F> - where I: Iterator, +where + I: Iterator, { iter: &'a mut I, f: F, @@ -92,18 +100,16 @@ where /// Create a PeekingTakeWhile pub fn peeking_take_while(iter: &mut I, f: F) -> PeekingTakeWhile - where I: Iterator, +where + I: Iterator, { - PeekingTakeWhile { - iter, - f, - } + PeekingTakeWhile { iter, f } } impl<'a, I, F> Iterator for PeekingTakeWhile<'a, I, F> - where I: PeekingNext, - F: FnMut(&I::Item) -> bool, - +where + I: PeekingNext, + F: FnMut(&I::Item) -> bool, { type Item = I::Item; fn next(&mut self) -> Option { @@ -151,4 +157,4 @@ peeking_next_by_clone! { ['a, T] alloc::collections::vec_deque::Iter<'a, T> } // cloning a Rev has no extra overhead; peekable and put backs are never DEI. peeking_next_by_clone! { [I: Clone + PeekingNext + DoubleEndedIterator] - ::std::iter::Rev } +::std::iter::Rev } diff --git a/src/permutations.rs b/src/permutations.rs index 3080f9d5c..23ff0d211 100644 --- a/src/permutations.rs +++ b/src/permutations.rs @@ -16,21 +16,17 @@ pub struct Permutations { } impl Clone for Permutations - where I: Clone + Iterator, - I::Item: Clone, +where + I: Clone + Iterator, + I::Item: Clone, { clone_fields!(vals, state); } #[derive(Clone, Debug)] enum PermutationState { - StartUnknownLen { - k: usize, - }, - OngoingUnknownLen { - k: usize, - min_n: usize, - }, + StartUnknownLen { k: usize }, + OngoingUnknownLen { k: usize, min_n: usize }, Complete(CompleteState), Empty, } @@ -44,7 +40,7 @@ enum CompleteState { Ongoing { indices: Vec, cycles: Vec, - } + }, } enum CompleteStateRemaining { @@ -53,8 +49,9 @@ enum CompleteStateRemaining { } impl fmt::Debug for Permutations - where I: Iterator + fmt::Debug, - I::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: fmt::Debug, { debug_fmt_fields!(Permutations, vals, state); } @@ -66,10 +63,7 @@ pub fn permutations(iter: I, k: usize) -> Permutations { // Special case, yields single empty vec; `n` is irrelevant let state = PermutationState::Complete(CompleteState::Start { n: 0, k: 0 }); - return Permutations { - vals, - state - }; + return Permutations { vals, state }; } let mut enough_vals = true; @@ -87,23 +81,23 @@ pub fn permutations(iter: I, k: usize) -> Permutations { PermutationState::Empty }; - Permutations { - vals, - state - } + Permutations { vals, state } } impl Iterator for Permutations where I: Iterator, - I::Item: Clone + I::Item: Clone, { type Item = Vec; fn next(&mut self) -> Option { self.advance(); - let &mut Permutations { ref vals, ref state } = self; + let &mut Permutations { + ref vals, + ref state, + } = self; match *state { PermutationState::StartUnknownLen { .. } => panic!("unexpected iterator state"), @@ -114,12 +108,15 @@ where Some(indices.map(|i| vals[i].clone()).collect()) } PermutationState::Complete(CompleteState::Start { .. }) => None, - PermutationState::Complete(CompleteState::Ongoing { ref indices, ref cycles }) => { + PermutationState::Complete(CompleteState::Ongoing { + ref indices, + ref cycles, + }) => { let k = cycles.len(); Some(indices[0..k].iter().map(|&i| vals[i].clone()).collect()) - }, - PermutationState::Empty => None + } + PermutationState::Empty => None, } } @@ -148,21 +145,21 @@ where let complete_state = CompleteState::Start { n, k }; from_complete(complete_state) - prev_iteration_count - }, + } PermutationState::Complete(state) => from_complete(state), - PermutationState::Empty => 0 + PermutationState::Empty => 0, } } fn size_hint(&self) -> (usize, Option) { match self.state { - PermutationState::StartUnknownLen { .. } | - PermutationState::OngoingUnknownLen { .. } => (0, None), // TODO can we improve this lower bound? + PermutationState::StartUnknownLen { .. } + | PermutationState::OngoingUnknownLen { .. } => (0, None), // TODO can we improve this lower bound? PermutationState::Complete(ref state) => match state.remaining() { CompleteStateRemaining::Known(count) => (count, Some(count)), - CompleteStateRemaining::Overflow => (::std::usize::MAX, None) - } - PermutationState::Empty => (0, Some(0)) + CompleteStateRemaining::Overflow => (::std::usize::MAX, None), + }, + PermutationState::Empty => (0, Some(0)), } } } @@ -170,10 +167,13 @@ where impl Permutations where I: Iterator, - I::Item: Clone + I::Item: Clone, { fn advance(&mut self) { - let &mut Permutations { ref mut vals, ref mut state } = self; + let &mut Permutations { + ref mut vals, + ref mut state, + } = self; *state = match *state { PermutationState::StartUnknownLen { k } => { @@ -181,7 +181,10 @@ where } PermutationState::OngoingUnknownLen { k, min_n } => { if vals.get_next() { - PermutationState::OngoingUnknownLen { k, min_n: min_n + 1 } + PermutationState::OngoingUnknownLen { + k, + min_n: min_n + 1, + } } else { let n = min_n; let prev_iteration_count = n - k + 1; @@ -200,7 +203,9 @@ where return; } - PermutationState::Empty => { return; } + PermutationState::Empty => { + return; + } }; } } @@ -212,12 +217,12 @@ impl CompleteState { let indices = (0..n).collect(); let cycles = ((n - k)..n).rev().collect(); - CompleteState::Ongoing { - cycles, - indices - } - }, - CompleteState::Ongoing { ref mut indices, ref mut cycles } => { + CompleteState::Ongoing { cycles, indices } + } + CompleteState::Ongoing { + ref mut indices, + ref mut cycles, + } => { let n = indices.len(); let k = cycles.len(); @@ -250,26 +255,31 @@ impl CompleteState { return Known(0); } - let count: Option = (n - k + 1..n + 1).fold(Some(1), |acc, i| { - acc.and_then(|acc| acc.checked_mul(i)) - }); + let count: Option = (n - k + 1..n + 1) + .fold(Some(1), |acc, i| acc.and_then(|acc| acc.checked_mul(i))); match count { Some(count) => Known(count), - None => Overflow + None => Overflow, } } - CompleteState::Ongoing { ref indices, ref cycles } => { + CompleteState::Ongoing { + ref indices, + ref cycles, + } => { let mut count: usize = 0; for (i, &c) in cycles.iter().enumerate() { let radix = indices.len() - i; - let next_count = count.checked_mul(radix) + let next_count = count + .checked_mul(radix) .and_then(|count| count.checked_add(c)); count = match next_count { Some(count) => count, - None => { return Overflow; } + None => { + return Overflow; + } }; } diff --git a/src/powerset.rs b/src/powerset.rs index 4d7685b12..454535cbe 100644 --- a/src/powerset.rs +++ b/src/powerset.rs @@ -1,9 +1,9 @@ +use alloc::vec::Vec; use std::fmt; use std::iter::FusedIterator; use std::usize; -use alloc::vec::Vec; -use super::combinations::{Combinations, combinations}; +use super::combinations::{combinations, Combinations}; use super::size_hint; /// An iterator to iterate through the powerset of the elements from an iterator. @@ -18,23 +18,26 @@ pub struct Powerset { } impl Clone for Powerset - where I: Clone + Iterator, - I::Item: Clone, +where + I: Clone + Iterator, + I::Item: Clone, { clone_fields!(combs, pos); } impl fmt::Debug for Powerset - where I: Iterator + fmt::Debug, - I::Item: fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: fmt::Debug, { debug_fmt_fields!(Powerset, combs, pos); } /// Create a new `Powerset` from a clonable iterator. pub fn powerset(src: I) -> Powerset - where I: Iterator, - I::Item: Clone, +where + I: Iterator, + I::Item: Clone, { Powerset { combs: combinations(src, 0), @@ -43,9 +46,9 @@ pub fn powerset(src: I) -> Powerset } impl Iterator for Powerset - where - I: Iterator, - I::Item: Clone, +where + I: Iterator, + I::Item: Clone, { type Item = Vec; @@ -53,9 +56,7 @@ impl Iterator for Powerset if let Some(elt) = self.combs.next() { self.pos = self.pos.saturating_add(1); Some(elt) - } else if self.combs.k() < self.combs.n() - || self.combs.k() == 0 - { + } else if self.combs.k() < self.combs.n() || self.combs.k() == 0 { self.combs.reset(self.combs.k() + 1); self.combs.next().map(|elt| { self.pos = self.pos.saturating_add(1); @@ -84,7 +85,8 @@ impl Iterator for Powerset } impl FusedIterator for Powerset - where - I: Iterator, - I::Item: Clone, -{} +where + I: Iterator, + I::Item: Clone, +{ +} diff --git a/src/process_results_impl.rs b/src/process_results_impl.rs index 44308f378..2b6037f92 100644 --- a/src/process_results_impl.rs +++ b/src/process_results_impl.rs @@ -1,4 +1,3 @@ - /// An iterator that produces only the `T` values as long as the /// inner iterator produces `Ok(T)`. /// @@ -12,7 +11,8 @@ pub struct ProcessResults<'a, I, E: 'a> { } impl<'a, I, T, E> Iterator for ProcessResults<'a, I, E> - where I: Iterator> +where + I: Iterator>, { type Item = T; @@ -85,13 +85,17 @@ impl<'a, I, T, E> Iterator for ProcessResults<'a, I, E> /// assert!(second_max.is_err()); /// ``` pub fn process_results(iterable: I, processor: F) -> Result - where I: IntoIterator>, - F: FnOnce(ProcessResults) -> R +where + I: IntoIterator>, + F: FnOnce(ProcessResults) -> R, { let iter = iterable.into_iter(); let mut error = Ok(()); - let result = processor(ProcessResults { error: &mut error, iter }); + let result = processor(ProcessResults { + error: &mut error, + iter, + }); error.map(|_| result) } diff --git a/src/put_back_n_impl.rs b/src/put_back_n_impl.rs index 60ea8e649..5fdbd5a98 100644 --- a/src/put_back_n_impl.rs +++ b/src/put_back_n_impl.rs @@ -17,7 +17,8 @@ pub struct PutBackN { /// /// Iterator element type is `I::Item`. pub fn put_back_n(iterable: I) -> PutBackN - where I: IntoIterator +where + I: IntoIterator, { PutBackN { top: Vec::new(), @@ -58,4 +59,3 @@ impl Iterator for PutBackN { size_hint::add_scalar(self.iter.size_hint(), self.top.len()) } } - diff --git a/src/rciter_impl.rs b/src/rciter_impl.rs index 7298350a8..1282ae865 100644 --- a/src/rciter_impl.rs +++ b/src/rciter_impl.rs @@ -1,7 +1,6 @@ - -use std::iter::{FusedIterator, IntoIterator}; use alloc::rc::Rc; use std::cell::RefCell; +use std::iter::{FusedIterator, IntoIterator}; /// A wrapper for `Rc>`, that implements the `Iterator` trait. #[derive(Debug)] @@ -45,9 +44,12 @@ pub struct RcIter { /// `.next()`, i.e. if it somehow participates in an “iterator knot” /// where it is an adaptor of itself. pub fn rciter(iterable: I) -> RcIter - where I: IntoIterator +where + I: IntoIterator, { - RcIter { rciter: Rc::new(RefCell::new(iterable.into_iter())) } + RcIter { + rciter: Rc::new(RefCell::new(iterable.into_iter())), + } } impl Clone for RcIter { @@ -55,7 +57,8 @@ impl Clone for RcIter { } impl Iterator for RcIter - where I: Iterator +where + I: Iterator, { type Item = A; #[inline] @@ -73,7 +76,8 @@ impl Iterator for RcIter } impl DoubleEndedIterator for RcIter - where I: DoubleEndedIterator +where + I: DoubleEndedIterator, { #[inline] fn next_back(&mut self) -> Option { @@ -83,7 +87,8 @@ impl DoubleEndedIterator for RcIter /// Return an iterator from `&RcIter` (by simply cloning it). impl<'a, I> IntoIterator for &'a RcIter - where I: Iterator +where + I: Iterator, { type Item = I::Item; type IntoIter = RcIter; @@ -93,7 +98,4 @@ impl<'a, I> IntoIterator for &'a RcIter } } - -impl FusedIterator for RcIter - where I: FusedIterator -{} +impl FusedIterator for RcIter where I: FusedIterator {} diff --git a/src/repeatn.rs b/src/repeatn.rs index e025f6f6a..512d057f3 100644 --- a/src/repeatn.rs +++ b/src/repeatn.rs @@ -12,17 +12,22 @@ pub struct RepeatN { /// Create an iterator that produces `n` repetitions of `element`. pub fn repeat_n(element: A, n: usize) -> RepeatN - where A: Clone, +where + A: Clone, { if n == 0 { - RepeatN { elt: None, n, } + RepeatN { elt: None, n } } else { - RepeatN { elt: Some(element), n, } + RepeatN { + elt: Some(element), + n, + } } } impl Iterator for RepeatN - where A: Clone +where + A: Clone, { type Item = A; @@ -42,7 +47,8 @@ impl Iterator for RepeatN } impl DoubleEndedIterator for RepeatN - where A: Clone +where + A: Clone, { #[inline] fn next_back(&mut self) -> Option { @@ -50,10 +56,6 @@ impl DoubleEndedIterator for RepeatN } } -impl ExactSizeIterator for RepeatN - where A: Clone -{} +impl ExactSizeIterator for RepeatN where A: Clone {} -impl FusedIterator for RepeatN - where A: Clone -{} +impl FusedIterator for RepeatN where A: Clone {} diff --git a/src/size_hint.rs b/src/size_hint.rs index 1168ecaa3..8d0a06c73 100644 --- a/src/size_hint.rs +++ b/src/size_hint.rs @@ -1,9 +1,9 @@ //! Arithmetic on **Iterator** *.size_hint()* values. //! -use std::usize; use std::cmp; use std::u32; +use std::usize; /// **SizeHint** is the return type of **Iterator::size_hint()**. pub type SizeHint = (usize, Option); @@ -39,7 +39,6 @@ pub fn sub_scalar(sh: SizeHint, x: usize) -> SizeHint { (low, hi) } - /// Multiply **SizeHint** correctly /// /// ```ignore diff --git a/src/sources.rs b/src/sources.rs index 3877ce3c8..bd520c21d 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -7,14 +7,13 @@ use std::mem; /// See [`repeat_call`](crate::repeat_call) for more information. #[derive(Clone)] -#[deprecated(note="Use std repeat_with() instead", since="0.8.0")] +#[deprecated(note = "Use std repeat_with() instead", since = "0.8.0")] pub struct RepeatCall { f: F, } -impl fmt::Debug for RepeatCall -{ - debug_fmt_fields!(RepeatCall, ); +impl fmt::Debug for RepeatCall { + debug_fmt_fields!(RepeatCall,); } /// An iterator source that produces elements indefinitely by calling @@ -39,15 +38,17 @@ impl fmt::Debug for RepeatCall /// vec![1, 1, 1, 1, 1] /// ); /// ``` -#[deprecated(note="Use std repeat_with() instead", since="0.8.0")] +#[deprecated(note = "Use std repeat_with() instead", since = "0.8.0")] pub fn repeat_call(function: F) -> RepeatCall - where F: FnMut() -> A +where + F: FnMut() -> A, { RepeatCall { f: function } } impl Iterator for RepeatCall - where F: FnMut() -> A +where + F: FnMut() -> A, { type Item = A; @@ -98,7 +99,8 @@ impl Iterator for RepeatCall /// assert_eq!(fibonacci.last(), Some(2_971_215_073)) /// ``` pub fn unfold(initial_state: St, f: F) -> Unfold - where F: FnMut(&mut St) -> Option +where + F: FnMut(&mut St) -> Option, { Unfold { f, @@ -107,7 +109,8 @@ pub fn unfold(initial_state: St, f: F) -> Unfold } impl fmt::Debug for Unfold - where St: fmt::Debug, +where + St: fmt::Debug, { debug_fmt_fields!(Unfold, state); } @@ -122,7 +125,8 @@ pub struct Unfold { } impl Iterator for Unfold - where F: FnMut(&mut St) -> Option +where + F: FnMut(&mut St) -> Option, { type Item = A; @@ -144,13 +148,15 @@ pub struct Iterate { } impl fmt::Debug for Iterate - where St: fmt::Debug, +where + St: fmt::Debug, { debug_fmt_fields!(Iterate, state); } impl Iterator for Iterate - where F: FnMut(&St) -> St +where + F: FnMut(&St) -> St, { type Item = St; @@ -174,7 +180,8 @@ impl Iterator for Iterate /// itertools::assert_equal(iterate(1, |&i| i * 3).take(5), vec![1, 3, 9, 27, 81]); /// ``` pub fn iterate(initial_value: St, f: F) -> Iterate - where F: FnMut(&St) -> St +where + F: FnMut(&St) -> St, { Iterate { state: initial_value, diff --git a/src/tee.rs b/src/tee.rs index ea4752906..0984c5de9 100644 --- a/src/tee.rs +++ b/src/tee.rs @@ -1,8 +1,8 @@ use super::size_hint; -use std::cell::RefCell; use alloc::collections::VecDeque; use alloc::rc::Rc; +use std::cell::RefCell; /// Common buffer object for the two tee halves #[derive(Debug)] @@ -19,24 +19,37 @@ struct TeeBuffer { #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[derive(Debug)] pub struct Tee - where I: Iterator +where + I: Iterator, { rcbuffer: Rc>>, id: bool, } pub fn new(iter: I) -> (Tee, Tee) - where I: Iterator +where + I: Iterator, { - let buffer = TeeBuffer{backlog: VecDeque::new(), iter, owner: false}; - let t1 = Tee{rcbuffer: Rc::new(RefCell::new(buffer)), id: true}; - let t2 = Tee{rcbuffer: t1.rcbuffer.clone(), id: false}; + let buffer = TeeBuffer { + backlog: VecDeque::new(), + iter, + owner: false, + }; + let t1 = Tee { + rcbuffer: Rc::new(RefCell::new(buffer)), + id: true, + }; + let t2 = Tee { + rcbuffer: t1.rcbuffer.clone(), + id: false, + }; (t1, t2) } impl Iterator for Tee - where I: Iterator, - I::Item: Clone +where + I: Iterator, + I::Item: Clone, { type Item = I::Item; fn next(&mut self) -> Option { @@ -73,6 +86,8 @@ impl Iterator for Tee } impl ExactSizeIterator for Tee - where I: ExactSizeIterator, - I::Item: Clone -{} +where + I: ExactSizeIterator, + I::Item: Clone, +{ +} diff --git a/src/tuple_impl.rs b/src/tuple_impl.rs index d914e0323..cc7df45bb 100644 --- a/src/tuple_impl.rs +++ b/src/tuple_impl.rs @@ -1,9 +1,9 @@ //! Some iterator that produces tuples +use std::iter::Cycle; use std::iter::Fuse; use std::iter::FusedIterator; use std::iter::Take; -use std::iter::Cycle; use std::marker::PhantomData; // `HomogeneousTuple` is a public facade for `TupleCollect`, allowing @@ -12,9 +12,7 @@ use std::marker::PhantomData; // See https://github.com/rust-itertools/itertools/issues/387 /// Implemented for homogeneous tuples of size up to 12. -pub trait HomogeneousTuple - : TupleCollect -{} +pub trait HomogeneousTuple: TupleCollect {} impl HomogeneousTuple for T {} @@ -24,25 +22,25 @@ impl HomogeneousTuple for T {} /// [`Tuples::into_buffer()`]. #[derive(Clone, Debug)] pub struct TupleBuffer - where T: HomogeneousTuple +where + T: HomogeneousTuple, { cur: usize, buf: T::Buffer, } impl TupleBuffer - where T: HomogeneousTuple +where + T: HomogeneousTuple, { fn new(buf: T::Buffer) -> Self { - TupleBuffer { - cur: 0, - buf, - } + TupleBuffer { cur: 0, buf } } } impl Iterator for TupleBuffer - where T: HomogeneousTuple +where + T: HomogeneousTuple, { type Item = T::Item; @@ -61,18 +59,16 @@ impl Iterator for TupleBuffer let len = if buffer.is_empty() { 0 } else { - buffer.iter() - .position(|x| x.is_none()) - .unwrap_or_else(|| buffer.len()) + buffer + .iter() + .position(|x| x.is_none()) + .unwrap_or_else(|| buffer.len()) }; (len, Some(len)) } } -impl ExactSizeIterator for TupleBuffer - where T: HomogeneousTuple -{ -} +impl ExactSizeIterator for TupleBuffer where T: HomogeneousTuple {} /// An iterator that groups the items in tuples of a specific size. /// @@ -80,8 +76,9 @@ impl ExactSizeIterator for TupleBuffer #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Tuples - where I: Iterator, - T: HomogeneousTuple +where + I: Iterator, + T: HomogeneousTuple, { iter: Fuse, buf: T::Buffer, @@ -89,8 +86,9 @@ pub struct Tuples /// Create a new tuples iterator. pub fn tuples(iter: I) -> Tuples - where I: Iterator, - T: HomogeneousTuple +where + I: Iterator, + T: HomogeneousTuple, { Tuples { iter: iter.fuse(), @@ -99,8 +97,9 @@ pub fn tuples(iter: I) -> Tuples } impl Iterator for Tuples - where I: Iterator, - T: HomogeneousTuple +where + I: Iterator, + T: HomogeneousTuple, { type Item = T; @@ -110,8 +109,9 @@ impl Iterator for Tuples } impl Tuples - where I: Iterator, - T: HomogeneousTuple +where + I: Iterator, + T: HomogeneousTuple, { /// Return a buffer with the produced items that was not enough to be grouped in a tuple. /// @@ -128,7 +128,6 @@ impl Tuples } } - /// An iterator over all contiguous windows that produces tuples of a specific size. /// /// See [`.tuple_windows()`](crate::Itertools::tuple_windows) for more @@ -136,8 +135,9 @@ impl Tuples #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[derive(Clone, Debug)] pub struct TupleWindows - where I: Iterator, - T: HomogeneousTuple +where + I: Iterator, + T: HomogeneousTuple, { iter: I, last: Option, @@ -145,9 +145,10 @@ pub struct TupleWindows /// Create a new tuple windows iterator. pub fn tuple_windows(mut iter: I) -> TupleWindows - where I: Iterator, - T: HomogeneousTuple, - T::Item: Clone +where + I: Iterator, + T: HomogeneousTuple, + T::Item: Clone, { use std::iter::once; @@ -161,22 +162,20 @@ pub fn tuple_windows(mut iter: I) -> TupleWindows } } - TupleWindows { - last, - iter, - } + TupleWindows { last, iter } } impl Iterator for TupleWindows - where I: Iterator, - T: HomogeneousTuple + Clone, - T::Item: Clone +where + I: Iterator, + T: HomogeneousTuple + Clone, + T::Item: Clone, { type Item = T; fn next(&mut self) -> Option { if T::num_items() == 1 { - return T::collect_from_iter_no_buf(&mut self.iter) + return T::collect_from_iter_no_buf(&mut self.iter); } if let Some(ref mut last) = self.last { if let Some(new) = self.iter.next() { @@ -189,10 +188,12 @@ impl Iterator for TupleWindows } impl FusedIterator for TupleWindows - where I: FusedIterator, - T: HomogeneousTuple + Clone, - T::Item: Clone -{} +where + I: FusedIterator, + T: HomogeneousTuple + Clone, + T::Item: Clone, +{ +} /// An iterator over all windows,wrapping back to the first elements when the /// window would otherwise exceed the length of the iterator, producing tuples @@ -203,31 +204,34 @@ impl FusedIterator for TupleWindows #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] #[derive(Debug)] pub struct CircularTupleWindows - where I: Iterator + Clone, - T: TupleCollect + Clone +where + I: Iterator + Clone, + T: TupleCollect + Clone, { iter: Take, T>>, - phantom_data: PhantomData + phantom_data: PhantomData, } pub fn circular_tuple_windows(iter: I) -> CircularTupleWindows - where I: Iterator + Clone + ExactSizeIterator, - T: TupleCollect + Clone, - T::Item: Clone +where + I: Iterator + Clone + ExactSizeIterator, + T: TupleCollect + Clone, + T::Item: Clone, { let len = iter.len(); let iter = tuple_windows(iter.cycle()).take(len); CircularTupleWindows { iter, - phantom_data: PhantomData{} + phantom_data: PhantomData {}, } } impl Iterator for CircularTupleWindows - where I: Iterator + Clone, - T: TupleCollect + Clone, - T::Item: Clone +where + I: Iterator + Clone, + T: TupleCollect + Clone, + T::Item: Clone, { type Item = T; @@ -241,10 +245,12 @@ pub trait TupleCollect: Sized { type Buffer: Default + AsRef<[Option]> + AsMut<[Option]>; fn collect_from_iter(iter: I, buf: &mut Self::Buffer) -> Option - where I: IntoIterator; + where + I: IntoIterator; fn collect_from_iter_no_buf(iter: I) -> Option - where I: IntoIterator; + where + I: IntoIterator; fn num_items() -> usize; diff --git a/src/unique_impl.rs b/src/unique_impl.rs index 2240f36ed..32c510298 100644 --- a/src/unique_impl.rs +++ b/src/unique_impl.rs @@ -1,8 +1,7 @@ - +use std::collections::hash_map::Entry; use std::collections::HashMap; -use std::collections::hash_map::{Entry}; -use std::hash::Hash; use std::fmt; +use std::hash::Hash; use std::iter::FusedIterator; /// An iterator adapter to filter out duplicate elements. @@ -18,17 +17,19 @@ pub struct UniqueBy { } impl fmt::Debug for UniqueBy - where I: Iterator + fmt::Debug, - V: fmt::Debug + Hash + Eq, +where + I: Iterator + fmt::Debug, + V: fmt::Debug + Hash + Eq, { debug_fmt_fields!(UniqueBy, iter, used); } /// Create a new `UniqueBy` iterator. pub fn unique_by(iter: I, f: F) -> UniqueBy - where V: Eq + Hash, - F: FnMut(&I::Item) -> V, - I: Iterator, +where + V: Eq + Hash, + F: FnMut(&I::Item) -> V, + I: Iterator, { UniqueBy { iter, @@ -39,8 +40,9 @@ pub fn unique_by(iter: I, f: F) -> UniqueBy // count the number of new unique keys in iterable (`used` is the set already seen) fn count_new_keys(mut used: HashMap, iterable: I) -> usize - where I: IntoIterator, - K: Hash + Eq, +where + I: IntoIterator, + K: Hash + Eq, { let iter = iterable.into_iter(); let current_used = used.len(); @@ -49,9 +51,10 @@ fn count_new_keys(mut used: HashMap, iterable: I) -> usize } impl Iterator for UniqueBy - where I: Iterator, - V: Eq + Hash, - F: FnMut(&I::Item) -> V +where + I: Iterator, + V: Eq + Hash, + F: FnMut(&I::Item) -> V, { type Item = I::Item; @@ -78,9 +81,10 @@ impl Iterator for UniqueBy } impl DoubleEndedIterator for UniqueBy - where I: DoubleEndedIterator, - V: Eq + Hash, - F: FnMut(&I::Item) -> V +where + I: DoubleEndedIterator, + V: Eq + Hash, + F: FnMut(&I::Item) -> V, { fn next_back(&mut self) -> Option { while let Some(v) = self.iter.next_back() { @@ -94,14 +98,17 @@ impl DoubleEndedIterator for UniqueBy } impl FusedIterator for UniqueBy - where I: FusedIterator, - V: Eq + Hash, - F: FnMut(&I::Item) -> V -{} +where + I: FusedIterator, + V: Eq + Hash, + F: FnMut(&I::Item) -> V, +{ +} impl Iterator for Unique - where I: Iterator, - I::Item: Eq + Hash + Clone +where + I: Iterator, + I::Item: Eq + Hash + Clone, { type Item = I::Item; @@ -128,8 +135,9 @@ impl Iterator for Unique } impl DoubleEndedIterator for Unique - where I: DoubleEndedIterator, - I::Item: Eq + Hash + Clone +where + I: DoubleEndedIterator, + I::Item: Eq + Hash + Clone, { fn next_back(&mut self) -> Option { while let Some(v) = self.iter.iter.next_back() { @@ -144,9 +152,11 @@ impl DoubleEndedIterator for Unique } impl FusedIterator for Unique - where I: FusedIterator, - I::Item: Eq + Hash + Clone -{} +where + I: FusedIterator, + I::Item: Eq + Hash + Clone, +{ +} /// An iterator adapter to filter out duplicate elements. /// @@ -158,21 +168,23 @@ pub struct Unique { } impl fmt::Debug for Unique - where I: Iterator + fmt::Debug, - I::Item: Hash + Eq + fmt::Debug, +where + I: Iterator + fmt::Debug, + I::Item: Hash + Eq + fmt::Debug, { debug_fmt_fields!(Unique, iter); } pub fn unique(iter: I) -> Unique - where I: Iterator, - I::Item: Eq + Hash, +where + I: Iterator, + I::Item: Eq + Hash, { Unique { iter: UniqueBy { iter, used: HashMap::new(), f: (), - } + }, } } diff --git a/src/with_position.rs b/src/with_position.rs index 1388503d1..cfbca08c9 100644 --- a/src/with_position.rs +++ b/src/with_position.rs @@ -1,4 +1,4 @@ -use std::iter::{Fuse,Peekable, FusedIterator}; +use std::iter::{Fuse, FusedIterator, Peekable}; /// An iterator adaptor that wraps each element in an [`Position`]. /// @@ -7,22 +7,25 @@ use std::iter::{Fuse,Peekable, FusedIterator}; /// See [`.with_position()`](crate::Itertools::with_position) for more information. #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct WithPosition - where I: Iterator, +where + I: Iterator, { handled_first: bool, peekable: Peekable>, } impl Clone for WithPosition - where I: Clone + Iterator, - I::Item: Clone, +where + I: Clone + Iterator, + I::Item: Clone, { clone_fields!(handled_first, peekable); } /// Create a new `WithPosition` iterator. pub fn with_position(iter: I) -> WithPosition - where I: Iterator, +where + I: Iterator, { WithPosition { handled_first: false, @@ -50,10 +53,7 @@ impl Position { /// Return the inner value. pub fn into_inner(self) -> T { match self { - Position::First(x) | - Position::Middle(x) | - Position::Last(x) | - Position::Only(x) => x, + Position::First(x) | Position::Middle(x) | Position::Last(x) | Position::Only(x) => x, } } } @@ -92,9 +92,6 @@ impl Iterator for WithPosition { } } -impl ExactSizeIterator for WithPosition - where I: ExactSizeIterator, -{ } +impl ExactSizeIterator for WithPosition where I: ExactSizeIterator {} -impl FusedIterator for WithPosition -{} +impl FusedIterator for WithPosition {} diff --git a/src/zip_eq_impl.rs b/src/zip_eq_impl.rs index a079b326a..09bc6988c 100644 --- a/src/zip_eq_impl.rs +++ b/src/zip_eq_impl.rs @@ -25,8 +25,9 @@ pub struct ZipEq { /// } /// ``` pub fn zip_eq(i: I, j: J) -> ZipEq - where I: IntoIterator, - J: IntoIterator +where + I: IntoIterator, + J: IntoIterator, { ZipEq { a: i.into_iter(), @@ -35,8 +36,9 @@ pub fn zip_eq(i: I, j: J) -> ZipEq } impl Iterator for ZipEq - where I: Iterator, - J: Iterator +where + I: Iterator, + J: Iterator, { type Item = (I::Item, J::Item); @@ -44,8 +46,9 @@ impl Iterator for ZipEq match (self.a.next(), self.b.next()) { (None, None) => None, (Some(a), Some(b)) => Some((a, b)), - (None, Some(_)) | (Some(_), None) => - panic!("itertools: .zip_eq() reached end of one iterator before the other") + (None, Some(_)) | (Some(_), None) => { + panic!("itertools: .zip_eq() reached end of one iterator before the other") + } } } @@ -55,6 +58,8 @@ impl Iterator for ZipEq } impl ExactSizeIterator for ZipEq - where I: ExactSizeIterator, - J: ExactSizeIterator -{} +where + I: ExactSizeIterator, + J: ExactSizeIterator, +{ +} diff --git a/src/zip_longest.rs b/src/zip_longest.rs index cb9a7bacb..98ce4e63e 100644 --- a/src/zip_longest.rs +++ b/src/zip_longest.rs @@ -1,5 +1,5 @@ -use std::cmp::Ordering::{Equal, Greater, Less}; use super::size_hint; +use std::cmp::Ordering::{Equal, Greater, Less}; use std::iter::{Fuse, FusedIterator}; use crate::either_or_both::EitherOrBoth; @@ -21,8 +21,9 @@ pub struct ZipLongest { /// Create a new `ZipLongest` iterator. pub fn zip_longest(a: T, b: U) -> ZipLongest - where T: Iterator, - U: Iterator +where + T: Iterator, + U: Iterator, { ZipLongest { a: a.fuse(), @@ -31,8 +32,9 @@ pub fn zip_longest(a: T, b: U) -> ZipLongest } impl Iterator for ZipLongest - where T: Iterator, - U: Iterator +where + T: Iterator, + U: Iterator, { type Item = EitherOrBoth; @@ -53,8 +55,9 @@ impl Iterator for ZipLongest } impl DoubleEndedIterator for ZipLongest - where T: DoubleEndedIterator + ExactSizeIterator, - U: DoubleEndedIterator + ExactSizeIterator +where + T: DoubleEndedIterator + ExactSizeIterator, + U: DoubleEndedIterator + ExactSizeIterator, { #[inline] fn next_back(&mut self) -> Option { @@ -73,11 +76,15 @@ impl DoubleEndedIterator for ZipLongest } impl ExactSizeIterator for ZipLongest - where T: ExactSizeIterator, - U: ExactSizeIterator -{} +where + T: ExactSizeIterator, + U: ExactSizeIterator, +{ +} impl FusedIterator for ZipLongest - where T: Iterator, - U: Iterator -{} +where + T: Iterator, + U: Iterator, +{ +} diff --git a/src/ziptuple.rs b/src/ziptuple.rs index b7902ae53..bab72e865 100644 --- a/src/ziptuple.rs +++ b/src/ziptuple.rs @@ -37,8 +37,9 @@ pub struct Zip { /// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]); /// ``` pub fn multizip(t: U) -> Zip - where Zip: From, - Zip: Iterator, +where + Zip: From, + Zip: Iterator, { Zip::from(t) } diff --git a/tests/adaptors_no_collect.rs b/tests/adaptors_no_collect.rs index a47f906f9..4f227ddcc 100644 --- a/tests/adaptors_no_collect.rs +++ b/tests/adaptors_no_collect.rs @@ -23,9 +23,14 @@ impl Iterator for PanickingCounter { } fn no_collect_test(to_adaptor: T) - where A: Iterator, T: Fn(PanickingCounter) -> A +where + A: Iterator, + T: Fn(PanickingCounter) -> A, { - let counter = PanickingCounter { curr: 0, max: 10_000 }; + let counter = PanickingCounter { + curr: 0, + max: 10_000, + }; let adaptor = to_adaptor(counter); for _ in adaptor.take(5) {} @@ -44,4 +49,4 @@ fn combinations_no_collect() { #[test] fn combinations_with_replacement_no_collect() { no_collect_test(|iter| iter.combinations_with_replacement(5)) -} \ No newline at end of file +} diff --git a/tests/merge_join.rs b/tests/merge_join.rs index 3280b7d4e..870e1faff 100644 --- a/tests/merge_join.rs +++ b/tests/merge_join.rs @@ -1,108 +1,101 @@ -use itertools::EitherOrBoth; use itertools::free::merge_join_by; +use itertools::EitherOrBoth; #[test] fn empty() { let left: Vec = vec![]; let right: Vec = vec![]; let expected_result: Vec> = vec![]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn left_only() { - let left: Vec = vec![1,2,3]; + let left: Vec = vec![1, 2, 3]; let right: Vec = vec![]; let expected_result: Vec> = vec![ EitherOrBoth::Left(1), EitherOrBoth::Left(2), - EitherOrBoth::Left(3) + EitherOrBoth::Left(3), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn right_only() { let left: Vec = vec![]; - let right: Vec = vec![1,2,3]; + let right: Vec = vec![1, 2, 3]; let expected_result: Vec> = vec![ EitherOrBoth::Right(1), EitherOrBoth::Right(2), - EitherOrBoth::Right(3) + EitherOrBoth::Right(3), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn first_left_then_right() { - let left: Vec = vec![1,2,3]; - let right: Vec = vec![4,5,6]; + let left: Vec = vec![1, 2, 3]; + let right: Vec = vec![4, 5, 6]; let expected_result: Vec> = vec![ EitherOrBoth::Left(1), EitherOrBoth::Left(2), EitherOrBoth::Left(3), EitherOrBoth::Right(4), EitherOrBoth::Right(5), - EitherOrBoth::Right(6) + EitherOrBoth::Right(6), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn first_right_then_left() { - let left: Vec = vec![4,5,6]; - let right: Vec = vec![1,2,3]; + let left: Vec = vec![4, 5, 6]; + let right: Vec = vec![1, 2, 3]; let expected_result: Vec> = vec![ EitherOrBoth::Right(1), EitherOrBoth::Right(2), EitherOrBoth::Right(3), EitherOrBoth::Left(4), EitherOrBoth::Left(5), - EitherOrBoth::Left(6) + EitherOrBoth::Left(6), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn interspersed_left_and_right() { - let left: Vec = vec![1,3,5]; - let right: Vec = vec![2,4,6]; + let left: Vec = vec![1, 3, 5]; + let right: Vec = vec![2, 4, 6]; let expected_result: Vec> = vec![ EitherOrBoth::Left(1), EitherOrBoth::Right(2), EitherOrBoth::Left(3), EitherOrBoth::Right(4), EitherOrBoth::Left(5), - EitherOrBoth::Right(6) + EitherOrBoth::Right(6), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } #[test] fn overlapping_left_and_right() { - let left: Vec = vec![1,3,4,6]; - let right: Vec = vec![2,3,4,5]; + let left: Vec = vec![1, 3, 4, 6]; + let right: Vec = vec![2, 3, 4, 5]; let expected_result: Vec> = vec![ EitherOrBoth::Left(1), EitherOrBoth::Right(2), EitherOrBoth::Both(3, 3), EitherOrBoth::Both(4, 4), EitherOrBoth::Right(5), - EitherOrBoth::Left(6) + EitherOrBoth::Left(6), ]; - let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)) - .collect::>(); + let actual_result = merge_join_by(left, right, |l, r| l.cmp(r)).collect::>(); assert_eq!(expected_result, actual_result); } diff --git a/tests/quick.rs b/tests/quick.rs index 5829d1c1d..ef549654a 100644 --- a/tests/quick.rs +++ b/tests/quick.rs @@ -3,34 +3,21 @@ //! //! In particular we test the tedious size_hint and exact size correctness. +use itertools::free::{ + cloned, enumerate, multipeek, peek_nth, put_back, put_back_n, rciter, zip, zip_eq, +}; +use itertools::Itertools; +use itertools::{iproduct, izip, multizip, EitherOrBoth}; use quickcheck as qc; +use std::cmp::{max, min, Ordering}; +use std::collections::{HashMap, HashSet}; use std::default::Default; use std::num::Wrapping; use std::ops::Range; -use std::cmp::{max, min, Ordering}; -use std::collections::{HashMap, HashSet}; -use itertools::Itertools; -use itertools::{ - multizip, - EitherOrBoth, - iproduct, - izip, -}; -use itertools::free::{ - cloned, - enumerate, - multipeek, - peek_nth, - put_back, - put_back_n, - rciter, - zip, - zip_eq, -}; -use rand::Rng; -use rand::seq::SliceRandom; use quickcheck::TestResult; +use rand::seq::SliceRandom; +use rand::Rng; /// Trait for size hint modifier types trait HintKind: Copy + Send + qc::Arbitrary { @@ -66,8 +53,10 @@ struct Inexact { impl HintKind for Inexact { fn loosen_bounds(&self, org_hint: (usize, Option)) -> (usize, Option) { let (org_lower, org_upper) = org_hint; - (org_lower.saturating_sub(self.underestimate), - org_upper.and_then(move |x| x.checked_add(self.overestimate))) + ( + org_lower.saturating_sub(self.underestimate), + org_upper.and_then(move |x| x.checked_add(self.overestimate)), + ) } } @@ -84,19 +73,15 @@ impl qc::Arbitrary for Inexact { } } - fn shrink(&self) -> Box> { + fn shrink(&self) -> Box> { let underestimate_value = self.underestimate; let overestimate_value = self.overestimate; - Box::new( - underestimate_value.shrink().flat_map(move |ue_value| - overestimate_value.shrink().map(move |oe_value| - Inexact { - underestimate: ue_value, - overestimate: oe_value, - } - ) - ) - ) + Box::new(underestimate_value.shrink().flat_map(move |ue_value| { + overestimate_value.shrink().map(move |oe_value| Inexact { + underestimate: ue_value, + overestimate: oe_value, + }) + })) } } @@ -116,7 +101,9 @@ struct Iter { hint_kind: SK, } -impl Iter where HK: HintKind +impl Iter +where + HK: HintKind, { fn new(it: Range, hint_kind: HK) -> Self { Iter { @@ -128,64 +115,66 @@ impl Iter where HK: HintKind } impl Iterator for Iter - where Range: Iterator, - as Iterator>::Item: Default, - HK: HintKind, +where + Range: Iterator, + as Iterator>::Item: Default, + HK: HintKind, { type Item = as Iterator>::Item; - fn next(&mut self) -> Option - { + fn next(&mut self) -> Option { let elt = self.iterator.next(); if elt.is_none() { self.fuse_flag += 1; // check fuse flag if self.fuse_flag == 2 { - return Some(Default::default()) + return Some(Default::default()); } } elt } - fn size_hint(&self) -> (usize, Option) - { + fn size_hint(&self) -> (usize, Option) { let org_hint = self.iterator.size_hint(); self.hint_kind.loosen_bounds(org_hint) } } impl DoubleEndedIterator for Iter - where Range: DoubleEndedIterator, - as Iterator>::Item: Default, - HK: HintKind +where + Range: DoubleEndedIterator, + as Iterator>::Item: Default, + HK: HintKind, { - fn next_back(&mut self) -> Option { self.iterator.next_back() } + fn next_back(&mut self) -> Option { + self.iterator.next_back() + } } -impl ExactSizeIterator for Iter where Range: ExactSizeIterator, +impl ExactSizeIterator for Iter +where + Range: ExactSizeIterator, as Iterator>::Item: Default, -{ } +{ +} impl qc::Arbitrary for Iter - where T: qc::Arbitrary, - HK: HintKind, +where + T: qc::Arbitrary, + HK: HintKind, { - fn arbitrary(g: &mut G) -> Self - { + fn arbitrary(g: &mut G) -> Self { Iter::new(T::arbitrary(g)..T::arbitrary(g), HK::arbitrary(g)) } - fn shrink(&self) -> Box>> - { + fn shrink(&self) -> Box>> { let r = self.iterator.clone(); let hint_kind = self.hint_kind; - Box::new( - r.start.shrink().flat_map(move |a| - r.end.shrink().map(move |b| - Iter::new(a.clone()..b, hint_kind) - ) - ) - ) + Box::new(r.start.shrink().flat_map(move |a| { + r.end + .shrink() + .map(move |b| Iter::new(a.clone()..b, hint_kind)) + })) } } @@ -201,7 +190,10 @@ struct ShiftRange { hint_kind: HK, } -impl Iterator for ShiftRange where HK: HintKind { +impl Iterator for ShiftRange +where + HK: HintKind, +{ type Item = Iter; fn next(&mut self) -> Option { @@ -219,10 +211,11 @@ impl Iterator for ShiftRange where HK: HintKind { } } -impl ExactSizeIterator for ShiftRange { } +impl ExactSizeIterator for ShiftRange {} impl qc::Arbitrary for ShiftRange - where HK: HintKind +where + HK: HintKind, { fn arbitrary(g: &mut G) -> Self { const MAX_STARTING_RANGE_DIFF: i32 = 32; @@ -250,7 +243,7 @@ impl qc::Arbitrary for ShiftRange fn correct_count(get_it: F) -> bool where I: Iterator, - F: Fn() -> I + F: Fn() -> I, { let mut counts = vec![get_it().count()]; @@ -275,7 +268,10 @@ where for (i, returned_count) in counts.into_iter().enumerate() { let actual_count = total_actual_count - i; if actual_count != returned_count { - println!("Total iterations: {} True count: {} returned count: {}", i, actual_count, returned_count); + println!( + "Total iterations: {} True count: {} returned count: {}", + i, actual_count, returned_count + ); return false; } @@ -298,12 +294,10 @@ fn correct_size_hint(mut it: I) -> bool { // check all the size hints for &(low, hi) in &hints { true_count -= 1; - if low > true_count || - (hi.is_some() && hi.unwrap() < true_count) - { + if low > true_count || (hi.is_some() && hi.unwrap() < true_count) { println!("True size: {:?}, size hint: {:?}", true_count, (low, hi)); //println!("All hints: {:?}", hints); - return false + return false; } } true @@ -312,13 +306,19 @@ fn correct_size_hint(mut it: I) -> bool { fn exact_size(mut it: I) -> bool { // check every iteration let (mut low, mut hi) = it.size_hint(); - if Some(low) != hi { return false; } + if Some(low) != hi { + return false; + } while let Some(_) = it.next() { let (xlow, xhi) = it.size_hint(); - if low != xlow + 1 { return false; } + if low != xlow + 1 { + return false; + } low = xlow; hi = xhi; - if Some(low) != hi { return false; } + if Some(low) != hi { + return false; + } } let (low, hi) = it.size_hint(); low == 0 && hi == Some(0) @@ -328,13 +328,19 @@ fn exact_size(mut it: I) -> bool { fn exact_size_for_this(mut it: I) -> bool { // check every iteration let (mut low, mut hi) = it.size_hint(); - if Some(low) != hi { return false; } + if Some(low) != hi { + return false; + } while let Some(_) = it.next() { let (xlow, xhi) = it.size_hint(); - if low != xlow + 1 { return false; } + if low != xlow + 1 { + return false; + } low = xlow; hi = xhi; - if Some(low) != hi { return false; } + if Some(low) != hi { + return false; + } } let (low, hi) = it.size_hint(); low == 0 && hi == Some(0) @@ -1237,7 +1243,7 @@ quickcheck! { Some(acc.unwrap_or(0) + val) } }); - + let group_map_lookup = a.iter() .map(|&b| b as u64) .map(|i| (i % modulo, i)) @@ -1257,7 +1263,7 @@ quickcheck! { for m in 0..modulo { assert_eq!( - lookup.get(&m).copied(), + lookup.get(&m).copied(), a.iter() .map(|&b| b as u64) .filter(|&val| val % modulo == m) @@ -1377,7 +1383,7 @@ quickcheck! { assert_eq!(Some(max), a.iter().copied().filter(|&val| val % modulo == key).max_by_key(|&val| val)); } } - + fn correct_grouping_map_by_min_modulo_key(a: Vec, modulo: u8) -> () { let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0` let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).min(); @@ -1428,7 +1434,7 @@ quickcheck! { assert_eq!(Some(min), a.iter().copied().filter(|&val| val % modulo == key).min_by_key(|&val| val)); } } - + fn correct_grouping_map_by_minmax_modulo_key(a: Vec, modulo: u8) -> () { let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0` let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).minmax(); @@ -1541,7 +1547,7 @@ quickcheck! { .min_by(|_, _, _| Ordering::Equal); assert_eq!(lookup[&0], 0); - + let lookup = (0..=10) .into_grouping_map_by(|_| 0) .minmax_by(|_, _, _| Ordering::Equal); @@ -1599,12 +1605,10 @@ quickcheck! { } } - -fn is_fused(mut it: I) -> bool -{ +fn is_fused(mut it: I) -> bool { while let Some(_) = it.next() {} - for _ in 0..10{ - if it.next().is_some(){ + for _ in 0..10 { + if it.next().is_some() { return false; } } @@ -1645,7 +1649,7 @@ quickcheck! { !is_fused(a.clone().interleave_shortest(b.clone())) && is_fused(a.fuse().interleave_shortest(b.fuse())) } - + fn fused_product(a: Iter, b: Iter) -> bool { is_fused(a.fuse().cartesian_product(b.fuse())) diff --git a/tests/specializations.rs b/tests/specializations.rs index 199cf562a..8585fe0fd 100644 --- a/tests/specializations.rs +++ b/tests/specializations.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use std::fmt::Debug; use quickcheck::quickcheck; +use std::fmt::Debug; struct Unspecialized(I); impl Iterator for Unspecialized @@ -24,12 +24,11 @@ macro_rules! check_specialized { let v2 = $closure; assert_eq!(v1, v2); - } + }; } -fn test_specializations( - it: &Iter, -) where +fn test_specializations(it: &Iter) +where IterItem: Eq + Debug + Clone, Iter: Iterator + Clone, { @@ -50,7 +49,7 @@ fn test_specializations( let first = i.next(); let all_result = i.all(|x| { parameters_from_all.push(x.clone()); - Some(x)==first + Some(x) == first }); (parameters_from_all, all_result) }); diff --git a/tests/test_core.rs b/tests/test_core.rs index a7b7449d3..d859290a0 100644 --- a/tests/test_core.rs +++ b/tests/test_core.rs @@ -5,17 +5,17 @@ //! except according to those terms. #![no_std] -use core::iter; -use itertools as it; -use crate::it::Itertools; +use crate::it::chain; +use crate::it::free::put_back; use crate::it::interleave; use crate::it::intersperse; use crate::it::intersperse_with; -use crate::it::multizip; -use crate::it::free::put_back; use crate::it::iproduct; use crate::it::izip; -use crate::it::chain; +use crate::it::multizip; +use crate::it::Itertools; +use core::iter; +use itertools as it; #[test] fn product2() { @@ -34,13 +34,12 @@ fn product_temporary() { for (_x, _y, _z) in iproduct!( [0, 1, 2].iter().cloned(), [0, 1, 2].iter().cloned(), - [0, 1, 2].iter().cloned()) - { + [0, 1, 2].iter().cloned() + ) { // ok } } - #[test] fn izip_macro() { let mut zip = izip!(2..3); @@ -61,7 +60,7 @@ fn izip_macro() { #[test] fn izip2() { let _zip1: iter::Zip<_, _> = izip!(1.., 2..); - let _zip2: iter::Zip<_, _> = izip!(1.., 2.., ); + let _zip2: iter::Zip<_, _> = izip!(1.., 2..,); } #[test] @@ -109,7 +108,7 @@ fn chain_macro() { #[test] fn chain2() { let _ = chain!(1.., 2..); - let _ = chain!(1.., 2.., ); + let _ = chain!(1.., 2..,); } #[test] @@ -127,7 +126,7 @@ fn write_to() { #[test] fn test_interleave() { - let xs: [u8; 0] = []; + let xs: [u8; 0] = []; let ys = [7u8, 9, 8, 10]; let zs = [2u8, 77]; let it = interleave(xs.iter(), ys.iter()); @@ -180,15 +179,13 @@ fn batching() { let ys = [(0, 1), (2, 1)]; // An iterator that gathers elements up in pairs - let pit = xs.iter().cloned().batching(|it| { - match it.next() { - None => None, - Some(x) => match it.next() { - None => None, - Some(y) => Some((x, y)), - } - } - }); + let pit = xs.iter().cloned().batching(|it| match it.next() { + None => None, + Some(x) => match it.next() { + None => None, + Some(y) => Some((x, y)), + }, + }); it::assert_equal(pit, ys.iter().cloned()); } @@ -216,7 +213,6 @@ fn merge() { it::assert_equal((0..10).step(2).merge((1..10).step(2)), 0..10); } - #[test] fn repeatn() { let s = "α"; @@ -236,29 +232,33 @@ fn count_clones() { use core::cell::Cell; #[derive(PartialEq, Debug)] struct Foo { - n: Cell + n: Cell, } - impl Clone for Foo - { - fn clone(&self) -> Self - { + impl Clone for Foo { + fn clone(&self) -> Self { let n = self.n.get(); self.n.set(n + 1); - Foo { n: Cell::new(n + 1) } + Foo { + n: Cell::new(n + 1), + } } } - for n in 0..10 { - let f = Foo{n: Cell::new(0)}; + let f = Foo { n: Cell::new(0) }; let it = it::repeat_n(f, n); // drain it let last = it.last(); if n == 0 { assert_eq!(last, None); } else { - assert_eq!(last, Some(Foo{n: Cell::new(n - 1)})); + assert_eq!( + last, + Some(Foo { + n: Cell::new(n - 1) + }) + ); } } } @@ -290,16 +290,36 @@ fn tree_fold1() { #[test] fn exactly_one() { assert_eq!((0..10).filter(|&x| x == 2).exactly_one().unwrap(), 2); - assert!((0..10).filter(|&x| x > 1 && x < 4).exactly_one().unwrap_err().eq(2..4)); - assert!((0..10).filter(|&x| x > 1 && x < 5).exactly_one().unwrap_err().eq(2..5)); - assert!((0..10).filter(|&_| false).exactly_one().unwrap_err().eq(0..0)); + assert!((0..10) + .filter(|&x| x > 1 && x < 4) + .exactly_one() + .unwrap_err() + .eq(2..4)); + assert!((0..10) + .filter(|&x| x > 1 && x < 5) + .exactly_one() + .unwrap_err() + .eq(2..5)); + assert!((0..10) + .filter(|&_| false) + .exactly_one() + .unwrap_err() + .eq(0..0)); } #[test] fn at_most_one() { assert_eq!((0..10).filter(|&x| x == 2).at_most_one().unwrap(), Some(2)); - assert!((0..10).filter(|&x| x > 1 && x < 4).at_most_one().unwrap_err().eq(2..4)); - assert!((0..10).filter(|&x| x > 1 && x < 5).at_most_one().unwrap_err().eq(2..5)); + assert!((0..10) + .filter(|&x| x > 1 && x < 4) + .at_most_one() + .unwrap_err() + .eq(2..4)); + assert!((0..10) + .filter(|&x| x > 1 && x < 5) + .at_most_one() + .unwrap_err() + .eq(2..5)); assert_eq!((0..10).filter(|&_| false).at_most_one().unwrap(), None); } diff --git a/tests/test_std.rs b/tests/test_std.rs index 4463d912f..3b49cad56 100644 --- a/tests/test_std.rs +++ b/tests/test_std.rs @@ -1,21 +1,25 @@ +use crate::it::cloned; +use crate::it::free::put_back_n; +use crate::it::free::rciter; +use crate::it::iproduct; +use crate::it::izip; +use crate::it::multipeek; +use crate::it::multizip; +use crate::it::peek_nth; +use crate::it::ExactlyOneError; +use crate::it::FoldWhile; +use crate::it::Itertools; +use itertools as it; use paste; use permutohedron; use quickcheck as qc; -use rand::{distributions::{Distribution, Standard}, Rng, SeedableRng, rngs::StdRng}; +use rand::{ + distributions::{Distribution, Standard}, + rngs::StdRng, + Rng, SeedableRng, +}; use rand::{seq::SliceRandom, thread_rng}; use std::{cmp::min, fmt::Debug, marker::PhantomData}; -use itertools as it; -use crate::it::Itertools; -use crate::it::ExactlyOneError; -use crate::it::multizip; -use crate::it::multipeek; -use crate::it::peek_nth; -use crate::it::free::rciter; -use crate::it::free::put_back_n; -use crate::it::FoldWhile; -use crate::it::cloned; -use crate::it::iproduct; -use crate::it::izip; #[test] fn product3() { @@ -29,9 +33,7 @@ fn product3() { } } } - for (_, _, _, _) in iproduct!(0..3, 0..2, 0..2, 0..3) { - /* test compiles */ - } + for (_, _, _, _) in iproduct!(0..3, 0..2, 0..2, 0..3) { /* test compiles */ } } #[test] @@ -64,9 +66,15 @@ fn duplicates_by() { let xs = ["aaa", "bbbbb", "aa", "ccc", "bbbb", "aaaaa", "cccc"]; let ys = ["aa", "bbbb", "cccc"]; it::assert_equal(ys.iter(), xs.iter().duplicates_by(|x| x[..2].to_string())); - it::assert_equal(ys.iter(), xs.iter().rev().duplicates_by(|x| x[..2].to_string()).rev()); + it::assert_equal( + ys.iter(), + xs.iter().rev().duplicates_by(|x| x[..2].to_string()).rev(), + ); let ys_rev = ["ccc", "aa", "bbbbb"]; - it::assert_equal(ys_rev.iter(), xs.iter().duplicates_by(|x| x[..2].to_string()).rev()); + it::assert_equal( + ys_rev.iter(), + xs.iter().duplicates_by(|x| x[..2].to_string()).rev(), + ); } #[test] @@ -88,7 +96,10 @@ fn duplicates() { let xs = vec![0, 1, 2, 1, 2]; let ys = vec![1, 2]; assert_eq!(ys, xs.iter().duplicates().cloned().collect_vec()); - assert_eq!(ys, xs.iter().rev().duplicates().rev().cloned().collect_vec()); + assert_eq!( + ys, + xs.iter().rev().duplicates().rev().cloned().collect_vec() + ); let ys_rev = vec![2, 1]; assert_eq!(ys_rev, xs.iter().duplicates().rev().cloned().collect_vec()); } @@ -98,9 +109,15 @@ fn unique_by() { let xs = ["aaa", "bbbbb", "aa", "ccc", "bbbb", "aaaaa", "cccc"]; let ys = ["aaa", "bbbbb", "ccc"]; it::assert_equal(ys.iter(), xs.iter().unique_by(|x| x[..2].to_string())); - it::assert_equal(ys.iter(), xs.iter().rev().unique_by(|x| x[..2].to_string()).rev()); + it::assert_equal( + ys.iter(), + xs.iter().rev().unique_by(|x| x[..2].to_string()).rev(), + ); let ys_rev = ["cccc", "aaaaa", "bbbb"]; - it::assert_equal(ys_rev.iter(), xs.iter().unique_by(|x| x[..2].to_string()).rev()); + it::assert_equal( + ys_rev.iter(), + xs.iter().unique_by(|x| x[..2].to_string()).rev(), + ); } #[test] @@ -151,13 +168,13 @@ fn dedup() { #[test] fn coalesce() { let data = vec![-1., -2., -3., 3., 1., 0., -1.]; - let it = data.iter().cloned().coalesce(|x, y| + let it = data.iter().cloned().coalesce(|x, y| { if (x >= 0.) == (y >= 0.) { Ok(x + y) } else { Err((x, y)) } - ); + }); itertools::assert_equal(it.clone(), vec![-6., 4., -1.]); assert_eq!( it.fold(vec![], |mut v, n| { @@ -170,17 +187,37 @@ fn coalesce() { #[test] fn dedup_by() { - let xs = [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (3, 1), (0, 3), (1, 3)]; + let xs = [ + (0, 0), + (0, 1), + (1, 1), + (2, 1), + (0, 2), + (3, 1), + (0, 3), + (1, 3), + ]; let ys = [(0, 0), (0, 1), (0, 2), (3, 1), (0, 3)]; - it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.1==y.1)); + it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.1 == y.1)); let xs = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]; let ys = [(0, 1)]; - it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.0==y.0)); - - let xs = [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (3, 1), (0, 3), (1, 3)]; + it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.0 == y.0)); + + let xs = [ + (0, 0), + (0, 1), + (1, 1), + (2, 1), + (0, 2), + (3, 1), + (0, 3), + (1, 3), + ]; let ys = [(0, 0), (0, 1), (0, 2), (3, 1), (0, 3)]; let mut xs_d = Vec::new(); - xs.iter().dedup_by(|x, y| x.1==y.1).fold((), |(), &elt| xs_d.push(elt)); + xs.iter() + .dedup_by(|x, y| x.1 == y.1) + .fold((), |(), &elt| xs_d.push(elt)); assert_eq!(&xs_d, &ys); } @@ -197,18 +234,38 @@ fn dedup_with_count() { it::assert_equal(ys.iter().cloned(), xs.iter().dedup_with_count()); } - #[test] fn dedup_by_with_count() { - let xs = [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (3, 1), (0, 3), (1, 3)]; - let ys = [(1, &(0, 0)), (3, &(0, 1)), (1, &(0, 2)), (1, &(3, 1)), (2, &(0, 3))]; + let xs = [ + (0, 0), + (0, 1), + (1, 1), + (2, 1), + (0, 2), + (3, 1), + (0, 3), + (1, 3), + ]; + let ys = [ + (1, &(0, 0)), + (3, &(0, 1)), + (1, &(0, 2)), + (1, &(3, 1)), + (2, &(0, 3)), + ]; - it::assert_equal(ys.iter().cloned(), xs.iter().dedup_by_with_count(|x, y| x.1==y.1)); + it::assert_equal( + ys.iter().cloned(), + xs.iter().dedup_by_with_count(|x, y| x.1 == y.1), + ); let xs = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]; - let ys = [( 5, &(0, 1))]; + let ys = [(5, &(0, 1))]; - it::assert_equal(ys.iter().cloned(), xs.iter().dedup_by_with_count(|x, y| x.0==y.0)); + it::assert_equal( + ys.iter().cloned(), + xs.iter().dedup_by_with_count(|x, y| x.0 == y.0), + ); } #[test] @@ -242,7 +299,7 @@ fn test_put_back_n() { #[test] fn tee() { - let xs = [0, 1, 2, 3]; + let xs = [0, 1, 2, 3]; let (mut t1, mut t2) = xs.iter().cloned().tee(); assert_eq!(t1.next(), Some(0)); assert_eq!(t2.next(), Some(0)); @@ -266,7 +323,6 @@ fn tee() { it::assert_equal(t1.zip(t2), xs.iter().cloned().zip(xs.iter().cloned())); } - #[test] fn test_rciter() { let xs = [0, 1, 1, 1, 2, 1, 3, 5, 6]; @@ -290,19 +346,19 @@ fn test_rciter() { #[allow(deprecated)] #[test] fn trait_pointers() { - struct ByRef<'r, I: ?Sized>(&'r mut I) ; + struct ByRef<'r, I: ?Sized>(&'r mut I); - impl<'r, X, I: ?Sized> Iterator for ByRef<'r, I> where - I: 'r + Iterator + impl<'r, X, I: ?Sized> Iterator for ByRef<'r, I> + where + I: 'r + Iterator, { type Item = X; - fn next(&mut self) -> Option - { + fn next(&mut self) -> Option { self.0.next() } } - let mut it = Box::new(0..10) as Box>; + let mut it = Box::new(0..10) as Box>; assert_eq!(it.next(), Some(0)); { @@ -322,9 +378,16 @@ fn trait_pointers() { #[test] fn merge_by() { - let odd : Vec<(u32, &str)> = vec![(1, "hello"), (3, "world"), (5, "!")]; + let odd: Vec<(u32, &str)> = vec![(1, "hello"), (3, "world"), (5, "!")]; let even = vec![(2, "foo"), (4, "bar"), (6, "baz")]; - let expected = vec![(1, "hello"), (2, "foo"), (3, "world"), (4, "bar"), (5, "!"), (6, "baz")]; + let expected = vec![ + (1, "hello"), + (2, "foo"), + (3, "world"), + (4, "bar"), + (5, "!"), + (6, "baz"), + ]; let results = odd.iter().merge_by(even.iter(), |a, b| a.0 <= b.0); it::assert_equal(results, expected.iter()); } @@ -338,7 +401,7 @@ fn merge_by_btree() { let mut bt2 = BTreeMap::new(); bt2.insert("foo", 2); bt2.insert("bar", 4); - let results = bt1.into_iter().merge_by(bt2.into_iter(), |a, b| a.0 <= b.0 ); + let results = bt1.into_iter().merge_by(bt2.into_iter(), |a, b| a.0 <= b.0); let expected = vec![("bar", 4), ("foo", 2), ("hello", 1), ("world", 3)]; it::assert_equal(results, expected.into_iter()); } @@ -380,19 +443,17 @@ fn kmerge_empty_size_hint() { #[test] fn join() { let many = [1, 2, 3]; - let one = [1]; + let one = [1]; let none: Vec = vec![]; assert_eq!(many.iter().join(", "), "1, 2, 3"); - assert_eq!( one.iter().join(", "), "1"); + assert_eq!(one.iter().join(", "), "1"); assert_eq!(none.iter().join(", "), ""); } #[test] fn sorted_unstable_by() { - let sc = [3, 4, 1, 2].iter().cloned().sorted_by(|&a, &b| { - a.cmp(&b) - }); + let sc = [3, 4, 1, 2].iter().cloned().sorted_by(|&a, &b| a.cmp(&b)); it::assert_equal(sc, vec![1, 2, 3, 4]); let v = (0..5).sorted_unstable_by(|&a, &b| a.cmp(&b).reverse()); @@ -410,9 +471,7 @@ fn sorted_unstable_by_key() { #[test] fn sorted_by() { - let sc = [3, 4, 1, 2].iter().cloned().sorted_by(|&a, &b| { - a.cmp(&b) - }); + let sc = [3, 4, 1, 2].iter().cloned().sorted_by(|&a, &b| a.cmp(&b)); it::assert_equal(sc, vec![1, 2, 3, 4]); let v = (0..5).sorted_by(|&a, &b| a.cmp(&b).reverse()); @@ -445,11 +504,13 @@ struct RandIter + _t: PhantomData, } impl Iterator for RandIter -where Standard: Distribution { +where + Standard: Distribution, +{ type Item = T; fn next(&mut self) -> Option { if self.idx == self.len { @@ -467,7 +528,7 @@ impl qc::Arbitrary for Ran idx: 0, len: g.size(), rng: R::seed_from_u64(g.next_u64()), - _t : PhantomData{}, + _t: PhantomData {}, } } } @@ -481,10 +542,7 @@ where { let j = i.clone(); let k = k as usize; - it::assert_equal( - i.k_smallest(k), - j.sorted().take(k) - ) + it::assert_equal(i.k_smallest(k), j.sorted().take(k)) } macro_rules! generic_test { @@ -536,7 +594,7 @@ fn sorted_by_cached_key() { #[test] fn test_multipeek() { - let nums = vec![1u8,2,3,4,5]; + let nums = vec![1u8, 2, 3, 4, 5]; let mp = multipeek(nums.iter().map(|&x| x)); assert_eq!(nums, mp.collect::>()); @@ -577,7 +635,7 @@ fn test_multipeek_reset() { #[test] fn test_multipeek_peeking_next() { use crate::it::PeekingNext; - let nums = vec![1u8,2,3,4,5,6,7]; + let nums = vec![1u8, 2, 3, 4, 5, 6, 7]; let mut mp = multipeek(nums.iter().map(|&x| x)); assert_eq!(mp.peeking_next(|&x| x != 0), Some(1)); @@ -602,7 +660,7 @@ fn test_multipeek_peeking_next() { #[test] fn test_peek_nth() { - let nums = vec![1u8,2,3,4,5]; + let nums = vec![1u8, 2, 3, 4, 5]; let iter = peek_nth(nums.iter().map(|&x| x)); assert_eq!(nums, iter.collect::>()); @@ -637,7 +695,7 @@ fn test_peek_nth() { #[test] fn test_peek_nth_peeking_next() { use it::PeekingNext; - let nums = vec![1u8,2,3,4,5,6,7]; + let nums = vec![1u8, 2, 3, 4, 5, 6, 7]; let mut iter = peek_nth(nums.iter().map(|&x| x)); assert_eq!(iter.peeking_next(|&x| x != 0), Some(1)); @@ -703,11 +761,11 @@ fn group_by() { for &idx in &indices[..] { let (key, text) = match idx { - 0 => ('A', "Aaa".chars()), - 1 => ('B', "Bbb".chars()), - 2 => ('C', "ccCc".chars()), - 3 => ('D', "DDDD".chars()), - _ => unreachable!(), + 0 => ('A', "Aaa".chars()), + 1 => ('B', "Bbb".chars()), + 2 => ('C', "ccCc".chars()), + 3 => ('D', "DDDD".chars()), + _ => unreachable!(), }; assert_eq!(key, subs[idx].0); it::assert_equal(&mut subs[idx].1, text); @@ -732,9 +790,11 @@ fn group_by() { { let mut ntimes = 0; let text = "AABCCC"; - for (_, sub) in &text.chars().group_by(|&x| { ntimes += 1; x}) { - for _ in sub { - } + for (_, sub) in &text.chars().group_by(|&x| { + ntimes += 1; + x + }) { + for _ in sub {} } assert_eq!(ntimes, text.len()); } @@ -742,8 +802,10 @@ fn group_by() { { let mut ntimes = 0; let text = "AABCCC"; - for _ in &text.chars().group_by(|&x| { ntimes += 1; x}) { - } + for _ in &text.chars().group_by(|&x| { + ntimes += 1; + x + }) {} assert_eq!(ntimes, text.len()); } @@ -783,8 +845,7 @@ fn group_by_lazy_2() { if i < 2 { groups.push(group); } else if i < 4 { - for _ in group { - } + for _ in group {} } else { groups.push(group); } @@ -796,7 +857,11 @@ fn group_by_lazy_2() { // use groups as chunks let data = vec![0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3]; let mut i = 0; - let grouper = data.iter().group_by(move |_| { let k = i / 3; i += 1; k }); + let grouper = data.iter().group_by(move |_| { + let k = i / 3; + i += 1; + k + }); for (i, group) in &grouper { match i { 0 => it::assert_equal(group, &[0, 0, 0]), @@ -847,8 +912,8 @@ fn concat_empty() { #[test] fn concat_non_empty() { - let data = vec![vec![1,2,3], vec![4,5,6], vec![7,8,9]]; - assert_eq!(data.into_iter().concat(), vec![1,2,3,4,5,6,7,8,9]) + let data = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]; + assert_eq!(data.into_iter().concat(), vec![1, 2, 3, 4, 5, 6, 7, 8, 9]) } #[test] @@ -856,19 +921,20 @@ fn combinations() { assert!((1..3).combinations(5).next().is_none()); let it = (1..3).combinations(2); - it::assert_equal(it, vec![ - vec![1, 2], - ]); + it::assert_equal(it, vec![vec![1, 2]]); let it = (1..5).combinations(2); - it::assert_equal(it, vec![ - vec![1, 2], - vec![1, 3], - vec![1, 4], - vec![2, 3], - vec![2, 4], - vec![3, 4], - ]); + it::assert_equal( + it, + vec![ + vec![1, 2], + vec![1, 3], + vec![1, 4], + vec![2, 3], + vec![2, 4], + vec![3, 4], + ], + ); it::assert_equal((0..0).tuple_combinations::<(_, _)>(), >::new()); it::assert_equal((0..1).tuple_combinations::<(_, _)>(), >::new()); @@ -888,7 +954,6 @@ fn combinations_of_too_short() { } } - #[test] fn combinations_zero() { it::assert_equal((1..3).combinations(0), vec![vec![]]); @@ -918,15 +983,9 @@ fn combinations_with_replacement() { ], ); // Zero size - it::assert_equal( - (0..3).combinations_with_replacement(0), - vec![vec![]], - ); + it::assert_equal((0..3).combinations_with_replacement(0), vec![vec![]]); // Zero size on empty pool - it::assert_equal( - (0..0).combinations_with_replacement(0), - vec![vec![]], - ); + it::assert_equal((0..0).combinations_with_replacement(0), vec![vec![]]); // Empty pool it::assert_equal( (0..0).combinations_with_replacement(2), @@ -938,13 +997,23 @@ fn combinations_with_replacement() { fn powerset() { it::assert_equal((0..0).powerset(), vec![vec![]]); it::assert_equal((0..1).powerset(), vec![vec![], vec![0]]); - it::assert_equal((0..2).powerset(), vec![vec![], vec![0], vec![1], vec![0, 1]]); - it::assert_equal((0..3).powerset(), vec![ - vec![], - vec![0], vec![1], vec![2], - vec![0, 1], vec![0, 2], vec![1, 2], - vec![0, 1, 2] - ]); + it::assert_equal( + (0..2).powerset(), + vec![vec![], vec![0], vec![1], vec![0, 1]], + ); + it::assert_equal( + (0..3).powerset(), + vec![ + vec![], + vec![0], + vec![1], + vec![2], + vec![0, 1], + vec![0, 2], + vec![1, 2], + vec![0, 1, 2], + ], + ); assert_eq!((0..4).powerset().count(), 1 << 4); assert_eq!((0..8).powerset().count(), 1 << 8); @@ -973,8 +1042,7 @@ fn diff_longer() { let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b); assert!(match diff { - Some(it::Diff::Longer(_, remaining)) => - remaining.collect::>() == vec![5, 6], + Some(it::Diff::Longer(_, remaining)) => remaining.collect::>() == vec![5, 6], _ => false, }); } @@ -1042,8 +1110,8 @@ fn extrema_set() { #[test] fn minmax() { - use std::cmp::Ordering; use crate::it::MinMaxResult; + use std::cmp::Ordering; // A peculiar type: Equality compares both tuple items, but ordering only the // first item. This is so we can check the stability property easily. @@ -1062,7 +1130,10 @@ fn minmax() { } } - assert_eq!(None::>.iter().minmax(), MinMaxResult::NoElements); + assert_eq!( + None::>.iter().minmax(), + MinMaxResult::NoElements + ); assert_eq!(Some(1u32).iter().minmax(), MinMaxResult::OneElement(&1)); @@ -1075,7 +1146,11 @@ fn minmax() { assert_eq!(min, &Val(2, 0)); assert_eq!(max, &Val(0, 2)); - let (min, max) = data.iter().minmax_by(|x, y| x.1.cmp(&y.1)).into_option().unwrap(); + let (min, max) = data + .iter() + .minmax_by(|x, y| x.1.cmp(&y.1)) + .into_option() + .unwrap(); assert_eq!(min, &Val(2, 0)); assert_eq!(max, &Val(0, 2)); } @@ -1098,8 +1173,9 @@ fn format() { #[test] fn while_some() { - let ns = (1..10).map(|x| if x % 5 != 0 { Some(x) } else { None }) - .while_some(); + let ns = (1..10) + .map(|x| if x % 5 != 0 { Some(x) } else { None }) + .while_some(); it::assert_equal(ns, vec![1, 2, 3, 4]); } @@ -1108,15 +1184,18 @@ fn while_some() { fn fold_while() { let mut iterations = 0; let vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - let sum = vec.into_iter().fold_while(0, |acc, item| { - iterations += 1; - let new_sum = acc.clone() + item; - if new_sum <= 20 { - FoldWhile::Continue(new_sum) - } else { - FoldWhile::Done(acc) - } - }).into_inner(); + let sum = vec + .into_iter() + .fold_while(0, |acc, item| { + iterations += 1; + let new_sum = acc.clone() + item; + if new_sum <= 20 { + FoldWhile::Continue(new_sum) + } else { + FoldWhile::Done(acc) + } + }) + .into_inner(); assert_eq!(iterations, 6); assert_eq!(sum, 15); } @@ -1155,16 +1234,52 @@ fn exactly_one_question_mark_syntax_works() { exactly_one_question_mark_return().unwrap_err(); } -fn exactly_one_question_mark_return() -> Result<(), ExactlyOneError>> { +fn exactly_one_question_mark_return() -> Result<(), ExactlyOneError>> +{ [].iter().exactly_one()?; Ok(()) } #[test] fn multiunzip() { - let (a, b, c): (Vec<_>, Vec<_>, Vec<_>) = [(0, 1, 2), (3, 4, 5), (6, 7, 8)].iter().cloned().multiunzip(); + let (a, b, c): (Vec<_>, Vec<_>, Vec<_>) = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] + .iter() + .cloned() + .multiunzip(); assert_eq!((a, b, c), (vec![0, 3, 6], vec![1, 4, 7], vec![2, 5, 8])); let (): () = [(), (), ()].iter().cloned().multiunzip(); - let t: (Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>) = [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)].iter().cloned().multiunzip(); - assert_eq!(t, (vec![0], vec![1], vec![2], vec![3], vec![4], vec![5], vec![6], vec![7], vec![8], vec![9], vec![10], vec![11])); + let t: ( + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + Vec<_>, + ) = [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)] + .iter() + .cloned() + .multiunzip(); + assert_eq!( + t, + ( + vec![0], + vec![1], + vec![2], + vec![3], + vec![4], + vec![5], + vec![6], + vec![7], + vec![8], + vec![9], + vec![10], + vec![11] + ) + ); } diff --git a/tests/zip.rs b/tests/zip.rs index 5801b4232..ed7f3740c 100644 --- a/tests/zip.rs +++ b/tests/zip.rs @@ -1,17 +1,18 @@ -use itertools::Itertools; -use itertools::EitherOrBoth::{Both, Left, Right}; use itertools::free::zip_eq; use itertools::multizip; +use itertools::EitherOrBoth::{Both, Left, Right}; +use itertools::Itertools; #[test] fn zip_longest_fused() { let a = [Some(1), None, Some(3), Some(4)]; let b = [1, 2, 3]; - let unfused = a.iter().batching(|it| *it.next().unwrap()) + let unfused = a + .iter() + .batching(|it| *it.next().unwrap()) .zip_longest(b.iter().cloned()); - itertools::assert_equal(unfused, - vec![Both(1, 1), Right(2), Right(3)]); + itertools::assert_equal(unfused, vec![Both(1, 1), Right(2), Right(3)]); } #[test] @@ -55,11 +56,9 @@ fn test_double_ended_zip() { assert_eq!(it.next_back(), None); } - #[should_panic] #[test] -fn zip_eq_panic1() -{ +fn zip_eq_panic1() { let a = [1, 2]; let b = [1, 2, 3]; @@ -68,8 +67,7 @@ fn zip_eq_panic1() #[should_panic] #[test] -fn zip_eq_panic2() -{ +fn zip_eq_panic2() { let a: [i32; 0] = []; let b = [1, 2, 3];