Skip to content

Commit 9d68a1a

Browse files
committed
Tune RepeatWith::try_fold and Take::for_each and Vec::extend_trusted
1 parent a8954f1 commit 9d68a1a

File tree

6 files changed

+73
-6
lines changed

6 files changed

+73
-6
lines changed

library/alloc/src/vec/mod.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -2874,13 +2874,12 @@ impl<T, A: Allocator> Vec<T, A> {
28742874
);
28752875
self.reserve(additional);
28762876
unsafe {
2877-
let mut ptr = self.as_mut_ptr().add(self.len());
2877+
let ptr = self.as_mut_ptr();
28782878
let mut local_len = SetLenOnDrop::new(&mut self.len);
28792879
iterator.for_each(move |element| {
2880-
ptr::write(ptr, element);
2881-
ptr = ptr.add(1);
2882-
// Since the loop executes user code which can panic we have to bump the pointer
2883-
// after each step.
2880+
ptr::write(ptr.add(local_len.current_len()), element);
2881+
// Since the loop executes user code which can panic we have to update
2882+
// the length every step to correctly drop what we've written.
28842883
// NB can't overflow since we would have had to alloc the address space
28852884
local_len.increment_len(1);
28862885
});

library/alloc/src/vec/set_len_on_drop.rs

+5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ impl<'a> SetLenOnDrop<'a> {
1818
pub(super) fn increment_len(&mut self, increment: usize) {
1919
self.local_len += increment;
2020
}
21+
22+
#[inline]
23+
pub(super) fn current_len(&self) -> usize {
24+
self.local_len
25+
}
2126
}
2227

2328
impl Drop for SetLenOnDrop<'_> {

library/core/src/iter/adapters/take.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ where
7575
#[inline]
7676
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
7777
where
78-
Self: Sized,
7978
Fold: FnMut(Acc, Self::Item) -> R,
8079
R: Try<Output = Acc>,
8180
{
@@ -100,6 +99,26 @@ where
10099

101100
impl_fold_via_try_fold! { fold -> try_fold }
102101

102+
#[inline]
103+
fn for_each<F: FnMut(Self::Item)>(mut self, f: F) {
104+
// The default implementation would use a unit accumulator, so we can
105+
// avoid a stateful closure by folding over the remaining number
106+
// of items we wish to return instead.
107+
fn check<'a, Item>(
108+
mut action: impl FnMut(Item) + 'a,
109+
) -> impl FnMut(usize, Item) -> Option<usize> + 'a {
110+
move |more, x| {
111+
action(x);
112+
more.checked_sub(1)
113+
}
114+
}
115+
116+
let remaining = self.n;
117+
if remaining > 0 {
118+
self.iter.try_fold(remaining - 1, check(f));
119+
}
120+
}
121+
103122
#[inline]
104123
#[rustc_inherit_overflow_checks]
105124
fn advance_by(&mut self, n: usize) -> Result<(), usize> {

library/core/src/iter/sources/repeat_with.rs

+17
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::iter::{FusedIterator, TrustedLen};
2+
use crate::ops::Try;
23

34
/// Creates a new iterator that repeats elements of type `A` endlessly by
45
/// applying the provided closure, the repeater, `F: FnMut() -> A`.
@@ -89,6 +90,22 @@ impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
8990
fn size_hint(&self) -> (usize, Option<usize>) {
9091
(usize::MAX, None)
9192
}
93+
94+
#[inline]
95+
fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R
96+
where
97+
Fold: FnMut(Acc, Self::Item) -> R,
98+
R: Try<Output = Acc>,
99+
{
100+
// This override isn't strictly needed, but avoids the need to optimize
101+
// away the `next`-always-returns-`Some` and emphasizes that the `?`
102+
// is the only way to exit the loop.
103+
104+
loop {
105+
let item = (self.repeater)();
106+
init = fold(init, item)?;
107+
}
108+
}
92109
}
93110

94111
#[stable(feature = "iterator_repeat_with", since = "1.28.0")]

library/core/tests/iter/adapters/take.rs

+20
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,23 @@ fn test_take_try_folds() {
146146
assert_eq!(iter.try_for_each(Err), Err(2));
147147
assert_eq!(iter.try_for_each(Err), Ok(()));
148148
}
149+
150+
#[test]
151+
fn test_byref_take_consumed_items() {
152+
let mut inner = 10..90;
153+
154+
let mut count = 0;
155+
inner.by_ref().take(0).for_each(|_| count += 1);
156+
assert_eq!(count, 0);
157+
assert_eq!(inner, 10..90);
158+
159+
let mut count = 0;
160+
inner.by_ref().take(10).for_each(|_| count += 1);
161+
assert_eq!(count, 10);
162+
assert_eq!(inner, 20..90);
163+
164+
let mut count = 0;
165+
inner.by_ref().take(100).for_each(|_| count += 1);
166+
assert_eq!(count, 70);
167+
assert_eq!(inner, 90..90);
168+
}

src/test/codegen/repeat-trusted-len.rs

+7
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,10 @@ pub fn repeat_take_collect() -> Vec<u8> {
1111
// CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}align 1{{.*}} %{{[0-9]+}}, i8 42, i{{[0-9]+}} 100000, i1 false)
1212
iter::repeat(42).take(100000).collect()
1313
}
14+
15+
// CHECK-LABEL: @repeat_with_take_collect
16+
#[no_mangle]
17+
pub fn repeat_with_take_collect() -> Vec<u8> {
18+
// CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}align 1{{.*}} %{{[0-9]+}}, i8 13, i{{[0-9]+}} 12345, i1 false)
19+
iter::repeat_with(|| 13).take(12345).collect()
20+
}

0 commit comments

Comments
 (0)