Skip to content

Commit 9c7fe03

Browse files
committed
Improved the use of Extend in a few Iterator methods
- Reimplemented `Iterator::partition` to use a full iterator `extend` on one of the two collections, rather than pushing to both of them one element at a time. - Reimplemented `Iterator::unzip` to use a full iterator `extend` on one of the two collections, rather than pushing to both of them at the same time
1 parent 3fa9554 commit 9c7fe03

File tree

1 file changed

+18
-31
lines changed

1 file changed

+18
-31
lines changed

src/libcore/iter/traits/iterator.rs

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1504,30 +1504,23 @@ pub trait Iterator {
15041504
/// assert_eq!(odd, vec![1, 3]);
15051505
/// ```
15061506
#[stable(feature = "rust1", since = "1.0.0")]
1507-
fn partition<B, F>(self, f: F) -> (B, B) where
1507+
fn partition<B, F>(self, mut predicate: F) -> (B, B) where
15081508
Self: Sized,
15091509
B: Default + Extend<Self::Item>,
15101510
F: FnMut(&Self::Item) -> bool
15111511
{
1512-
#[inline]
1513-
fn extend<'a, T, B: Extend<T>>(
1514-
mut f: impl FnMut(&T) -> bool + 'a,
1515-
left: &'a mut B,
1516-
right: &'a mut B,
1517-
) -> impl FnMut(T) + 'a {
1518-
move |x| {
1519-
if f(&x) {
1520-
left.extend(Some(x));
1521-
} else {
1522-
right.extend(Some(x));
1523-
}
1524-
}
1525-
}
1526-
15271512
let mut left: B = Default::default();
15281513
let mut right: B = Default::default();
1514+
let right_ref = &mut right;
15291515

1530-
self.for_each(extend(f, &mut left, &mut right));
1516+
left.extend(self.filter_map(#[inline] move |item| {
1517+
if predicate(&item) {
1518+
Some(item)
1519+
} else {
1520+
right_ref.extend(Some(item));
1521+
None
1522+
}
1523+
}));
15311524

15321525
(left, right)
15331526
}
@@ -2378,22 +2371,16 @@ pub trait Iterator {
23782371
FromB: Default + Extend<B>,
23792372
Self: Sized + Iterator<Item=(A, B)>,
23802373
{
2381-
fn extend<'a, A, B>(
2382-
ts: &'a mut impl Extend<A>,
2383-
us: &'a mut impl Extend<B>,
2384-
) -> impl FnMut((A, B)) + 'a {
2385-
move |(t, u)| {
2386-
ts.extend(Some(t));
2387-
us.extend(Some(u));
2388-
}
2389-
}
2390-
2391-
let mut ts: FromA = Default::default();
2392-
let mut us: FromB = Default::default();
2374+
let mut lhs = FromA::default();
2375+
let mut rhs = FromB::default();
2376+
let rhs_ref = &mut rhs;
23932377

2394-
self.for_each(extend(&mut ts, &mut us));
2378+
lhs.extend(self.map(#[inline] move |(a, b)| {
2379+
rhs_ref.extend(Some(b));
2380+
a
2381+
}));
23952382

2396-
(ts, us)
2383+
(lhs, rhs)
23972384
}
23982385

23992386
/// Creates an iterator which copies all of its elements.

0 commit comments

Comments
 (0)