Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to edition 2021 #967

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ description = "Extra iterator adaptors, iterator methods, free functions, and ma
keywords = ["iterator", "data-structure", "zip", "product"]
categories = ["algorithms", "rust-patterns", "no-std", "no-std::no-alloc"]

edition = "2018"
edition = "2021"

# When bumping, please resolve all `#[allow(clippy::*)]` that are newly resolvable.
rust-version = "1.63.0"
Expand All @@ -30,7 +30,7 @@ rand = "0.7"
criterion = { version = "0.4.0", features = ["html_reports"] }
paste = "1.0.0" # Used in test_std to instantiate generic tests
permutohedron = "0.2"
quickcheck = { version = "0.9", default_features = false }
quickcheck = { version = "0.9", default-features = false }

[features]
default = ["use_std"]
Expand Down
4 changes: 2 additions & 2 deletions benches/powerset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const fn calc_iters(n: usize) -> usize {
}

fn powerset_n(c: &mut Criterion, n: usize) {
let id = format!("powerset {}", n);
let id = format!("powerset {n}");
c.bench_function(id.as_str(), move |b| {
b.iter(|| {
for _ in 0..calc_iters(n) {
Expand All @@ -21,7 +21,7 @@ fn powerset_n(c: &mut Criterion, n: usize) {
}

fn powerset_n_fold(c: &mut Criterion, n: usize) {
let id = format!("powerset {} fold", n);
let id = format!("powerset {n} fold");
c.bench_function(id.as_str(), move |b| {
b.iter(|| {
for _ in 0..calc_iters(n) {
Expand Down
2 changes: 1 addition & 1 deletion benches/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@ bench_specializations! {
.map(|x| if x % 2 == 1 { Err(x) } else { Ok(x) })
.collect_vec());
}
v.iter().copied().filter_map_ok(|x| if x % 3 == 0 { Some(x + 1) } else { None })
v.iter().copied().filter_map_ok(|x| (x % 3 == 0).then_some(x + 1))
}
flatten_ok {
DoubleEndedIterator
Expand Down
4 changes: 2 additions & 2 deletions examples/iris.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fn main() {
});
let mut irises = match irises {
Err(e) => {
println!("Error parsing: {:?}", e);
println!("Error parsing: {e:?}");
std::process::exit(1);
}
Ok(data) => data,
Expand Down Expand Up @@ -101,7 +101,7 @@ fn main() {

// using Itertools::tuple_combinations
for (a, b) in (0..4).tuple_combinations() {
println!("Column {} vs {}:", a, b);
println!("Column {a} vs {b}:");

// Clear plot
//
Expand Down
30 changes: 13 additions & 17 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use std::fmt;
use std::iter::{Enumerate, FromIterator, Fuse, FusedIterator};
use std::marker::PhantomData;
use std::ops::ControlFlow;

/// An iterator adaptor that alternates elements from two iterators until both
/// run out.
Expand Down Expand Up @@ -93,13 +94,13 @@
let res = i.try_fold(init, |mut acc, x| {
acc = f(acc, x);
match j.next() {
Some(y) => Ok(f(acc, y)),
None => Err(acc),
Some(y) => ControlFlow::Continue(f(acc, y)),
None => ControlFlow::Break(acc),
}
});
match res {
Ok(acc) => j.fold(acc, f),
Err(acc) => i.fold(acc, f),
ControlFlow::Continue(acc) => j.fold(acc, f),
ControlFlow::Break(acc) => i.fold(acc, f),
}
}
}
Expand Down Expand Up @@ -216,14 +217,12 @@
let res = i.try_fold(init, |mut acc, x| {
acc = f(acc, x);
match j.next() {
Some(y) => Ok(f(acc, y)),
None => Err(acc),
Some(y) => ControlFlow::Continue(f(acc, y)),
None => ControlFlow::Break(acc),
}
});
match res {
Ok(val) => val,
Err(val) => val,
}
let (ControlFlow::Continue(val) | ControlFlow::Break(val)) = res;
val
}
}

Expand Down Expand Up @@ -595,14 +594,11 @@
F: FnMut(B, Self::Item) -> B,
{
let res = self.iter.try_fold(acc, |acc, item| match item {
Some(item) => Ok(f(acc, item)),
None => Err(acc),
Some(item) => ControlFlow::Continue(f(acc, item)),
None => ControlFlow::Break(acc),

Check warning on line 598 in src/adaptors/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/adaptors/mod.rs#L598

Added line #L598 was not covered by tests
});

match res {
Ok(val) => val,
Err(val) => val,
}
let (ControlFlow::Continue(val) | ControlFlow::Break(val)) = res;
val
}
}

Expand Down
18 changes: 7 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@
//!
//! ## Rust Version
//!
//! This version of itertools requires Rust 1.63.0 or later.
//! This version of itertools requires Rust
#![doc = env!("CARGO_PKG_RUST_VERSION")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huge fan of this!

//! or later.

#[cfg(not(feature = "use_std"))]
extern crate core as std;
Expand Down Expand Up @@ -2318,10 +2320,10 @@ pub trait Itertools: Iterator {
// estimate lower bound of capacity needed
let (lower, _) = self.size_hint();
let mut result = String::with_capacity(sep.len() * lower);
write!(&mut result, "{}", first_elt).unwrap();
write!(&mut result, "{first_elt}").unwrap();
self.for_each(|elt| {
result.push_str(sep);
write!(&mut result, "{}", elt).unwrap();
write!(&mut result, "{elt}").unwrap();
});
result
}
Expand Down Expand Up @@ -2712,7 +2714,7 @@ pub trait Itertools: Iterator {
Self: Sized,
F: FnMut(B, Self::Item) -> FoldWhile<B>,
{
use Result::{Err as Break, Ok as Continue};
use std::ops::ControlFlow::{Break, Continue};

let result = self.try_fold(
init,
Expand Down Expand Up @@ -4520,13 +4522,7 @@ where
(Some(a), Some(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 += 1;
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/process_results_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ where

impl<'a, I, T, E> DoubleEndedIterator for ProcessResults<'a, I, E>
where
I: Iterator<Item = Result<T, E>>,
I: DoubleEndedIterator,
I: DoubleEndedIterator<Item = Result<T, E>>,
{
fn next_back(&mut self) -> Option<Self::Item> {
let item = self.iter.next_back();
Expand Down
2 changes: 1 addition & 1 deletion src/repeatn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ where
fn next(&mut self) -> Option<Self::Item> {
if self.n > 1 {
self.n -= 1;
self.elt.as_ref().cloned()
self.elt.clone()
} else {
self.n = 0;
self.elt.take()
Expand Down
9 changes: 5 additions & 4 deletions src/zip_longest.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::size_hint;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::{Fuse, FusedIterator};
use std::ops::ControlFlow;

use crate::either_or_both::EitherOrBoth;

Expand Down Expand Up @@ -62,12 +63,12 @@ where
{
let Self { mut a, mut b } = self;
let res = a.try_fold(init, |init, a| match b.next() {
Some(b) => Ok(f(init, EitherOrBoth::Both(a, b))),
None => Err(f(init, EitherOrBoth::Left(a))),
Some(b) => ControlFlow::Continue(f(init, EitherOrBoth::Both(a, b))),
None => ControlFlow::Break(f(init, EitherOrBoth::Left(a))),
});
match res {
Ok(acc) => b.map(EitherOrBoth::Right).fold(acc, f),
Err(acc) => a.map(EitherOrBoth::Left).fold(acc, f),
ControlFlow::Continue(acc) => b.map(EitherOrBoth::Right).fold(acc, f),
ControlFlow::Break(acc) => a.map(EitherOrBoth::Left).fold(acc, f),
}
}
}
Expand Down
8 changes: 1 addition & 7 deletions tests/laziness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,7 @@ must_use_tests! {
let _ = Panicking.map(Ok::<u8, ()>).filter_ok(|x| x % 2 == 0);
}
filter_map_ok {
let _ = Panicking.map(Ok::<u8, ()>).filter_map_ok(|x| {
if x % 2 == 0 {
Some(x + 1)
} else {
None
}
});
let _ = Panicking.map(Ok::<u8, ()>).filter_map_ok(|x| (x % 2 == 0).then_some(x + 1));
}
flatten_ok {
let _ = Panicking.map(|x| Ok::<_, ()>([x])).flatten_ok();
Expand Down
12 changes: 5 additions & 7 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,7 @@ where
let actual_count = total_actual_count - i;
if actual_count != returned_count {
println!(
"Total iterations: {} True count: {} returned count: {}",
i, actual_count, returned_count
"Total iterations: {i} True count: {actual_count} returned count: {returned_count}"
);

return false;
Expand Down Expand Up @@ -676,7 +675,7 @@ quickcheck! {
assert_eq!(perm.len(), k);

let all_items_valid = perm.iter().all(|p| vals.contains(p));
assert!(all_items_valid, "perm contains value not from input: {:?}", perm);
assert!(all_items_valid, "perm contains value not from input: {perm:?}");

// Check that all perm items are distinct
let distinct_len = {
Expand All @@ -686,7 +685,7 @@ quickcheck! {
assert_eq!(perm.len(), distinct_len);

// Check that the perm is new
assert!(actual.insert(perm.clone()), "perm already encountered: {:?}", perm);
assert!(actual.insert(perm.clone()), "perm already encountered: {perm:?}");
}
}

Expand All @@ -712,8 +711,7 @@ quickcheck! {
for next_perm in perms {
assert!(
next_perm > curr_perm,
"next perm isn't greater-than current; next_perm={:?} curr_perm={:?} n={}",
next_perm, curr_perm, n
"next perm isn't greater-than current; next_perm={next_perm:?} curr_perm={curr_perm:?} n={n}"
);

curr_perm = next_perm;
Expand Down Expand Up @@ -1874,7 +1872,7 @@ quickcheck! {
fn fused_filter_map_ok(a: Iter<i16>) -> bool
{
is_fused(a.map(|x| if x % 2 == 0 {Ok(x)} else {Err(x)} )
.filter_map_ok(|x| if x % 3 == 0 {Some(x / 3)} else {None})
.filter_map_ok(|x| (x % 3 == 0).then_some(x / 3))
.fuse())
}

Expand Down
10 changes: 5 additions & 5 deletions tests/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ where
I: Iterator + Clone,
{
macro_rules! check_specialized {
($src:expr, |$it:pat| $closure:expr) => {
($src:expr, |$it:pat_param| $closure:expr) => {
// Many iterators special-case the first elements, so we test specializations for iterators that have already been advanced.
let mut src = $src.clone();
for _ in 0..5 {
Expand Down Expand Up @@ -101,7 +101,7 @@ where
I: DoubleEndedIterator + Clone,
{
macro_rules! check_specialized {
($src:expr, |$it:pat| $closure:expr) => {
($src:expr, |$it:pat_param| $closure:expr) => {
// Many iterators special-case the first elements, so we test specializations for iterators that have already been advanced.
let mut src = $src.clone();
for step in 0..8 {
Expand Down Expand Up @@ -229,7 +229,7 @@ quickcheck! {
}

fn while_some(v: Vec<u8>) -> () {
test_specializations(&v.iter().map(|&x| if x < 100 { Some(2 * x) } else { None }).while_some());
test_specializations(&v.iter().map(|&x| (x < 100).then_some(2 * x)).while_some());
}

fn pad_using(v: Vec<u8>) -> () {
Expand Down Expand Up @@ -460,7 +460,7 @@ quickcheck! {
}

fn filter_map_ok(v: Vec<Result<u8, char>>) -> () {
let it = v.into_iter().filter_map_ok(|i| if i < 20 { Some(i * 2) } else { None });
let it = v.into_iter().filter_map_ok(|i| (i < 20).then_some(i * 2));
test_specializations(&it);
test_double_ended_specializations(&it);
}
Expand All @@ -481,7 +481,7 @@ quickcheck! {

fn helper(it: impl DoubleEndedIterator<Item = Result<u8, u8>> + Clone) {
macro_rules! check_results_specialized {
($src:expr, |$it:pat| $closure:expr) => {
($src:expr, |$it:pat_param| $closure:expr) => {
assert_eq!(
itertools::process_results($src.clone(), |$it| $closure),
itertools::process_results($src.clone(), |i| {
Expand Down
6 changes: 2 additions & 4 deletions tests/test_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1453,9 +1453,7 @@ 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| (x % 5 != 0).then_some(x)).while_some();
it::assert_equal(ns, vec![1, 2, 3, 4]);
}

Expand Down Expand Up @@ -1507,7 +1505,7 @@ fn tree_reduce() {
Some(s.to_string())
};
let num_strings = (0..i).map(|x| x.to_string());
let actual = num_strings.tree_reduce(|a, b| format!("{} {} x", a, b));
let actual = num_strings.tree_reduce(|a, b| format!("{a} {b} x"));
assert_eq!(actual, expected);
}
}
Expand Down