Skip to content

Commit b6c99ba

Browse files
bors[bot]SkiFire13
andauthored
Merge #563
563: Specialize ProcessResults::fold r=phimuemue a=SkiFire13 Partially fixes #562. `try_fold` can't be added right now because it requires the unstable `Try` trait. Co-authored-by: Giacomo Stevanato <giaco.stevanato@gmail.com>
2 parents d232918 + bc5ab46 commit b6c99ba

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/process_results_impl.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,23 @@ impl<'a, I, T, E> Iterator for ProcessResults<'a, I, E>
3030
fn size_hint(&self) -> (usize, Option<usize>) {
3131
(0, self.iter.size_hint().1)
3232
}
33+
34+
fn fold<B, F>(mut self, init: B, mut f: F) -> B
35+
where
36+
Self: Sized,
37+
F: FnMut(B, Self::Item) -> B,
38+
{
39+
let error = self.error;
40+
self.iter
41+
.try_fold(init, |acc, opt| match opt {
42+
Ok(x) => Ok(f(acc, x)),
43+
Err(e) => {
44+
*error = Err(e);
45+
Err(acc)
46+
}
47+
})
48+
.unwrap_or_else(|e| e)
49+
}
3350
}
3451

3552
/// “Lift” a function of the values of an iterator so that it can process

tests/specializations.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,50 @@ quickcheck! {
104104
test_specializations(&v.into_iter().map_ok(|u| u.checked_add(1)));
105105
}
106106
}
107+
108+
quickcheck! {
109+
fn process_results(v: Vec<Result<u8, u8>>) -> () {
110+
helper(v.iter().copied());
111+
helper(v.iter().copied().filter(Result::is_ok));
112+
113+
fn helper(it: impl Iterator<Item = Result<u8, u8>> + Clone) {
114+
macro_rules! check_results_specialized {
115+
($src:expr, |$it:pat| $closure:expr) => {
116+
assert_eq!(
117+
itertools::process_results($src.clone(), |$it| $closure),
118+
itertools::process_results($src.clone(), |i| {
119+
let $it = Unspecialized(i);
120+
$closure
121+
}),
122+
)
123+
}
124+
}
125+
126+
check_results_specialized!(it, |i| i.count());
127+
check_results_specialized!(it, |i| i.last());
128+
check_results_specialized!(it, |i| i.collect::<Vec<_>>());
129+
check_results_specialized!(it, |i| {
130+
let mut parameters_from_fold = vec![];
131+
let fold_result = i.fold(vec![], |mut acc, v| {
132+
parameters_from_fold.push((acc.clone(), v.clone()));
133+
acc.push(v);
134+
acc
135+
});
136+
(parameters_from_fold, fold_result)
137+
});
138+
check_results_specialized!(it, |mut i| {
139+
let mut parameters_from_all = vec![];
140+
let first = i.next();
141+
let all_result = i.all(|x| {
142+
parameters_from_all.push(x.clone());
143+
Some(x)==first
144+
});
145+
(parameters_from_all, all_result)
146+
});
147+
let size = it.clone().count();
148+
for n in 0..size + 2 {
149+
check_results_specialized!(it, |mut i| i.nth(n));
150+
}
151+
}
152+
}
153+
}

0 commit comments

Comments
 (0)