Skip to content

Commit 96b3eff

Browse files
authored
Unrolled build for #139690
Rollup merge of #139690 - cuviper:iter_repeat_n_default, r=tgross35 `impl Default for RepeatN` This creates an empty iterator, like `repeat_n(value, 0)` but without needing any such value at hand. There's precedent in many other iterators that the `Default` is empty, like `slice::Iter`. I found myself wanting this for rayon's `RepeatN` as it lowers to a sequential iterator [here][1]. Since rayon is also optimizing to avoid extra clones, it may end up with parallel splits that have count 0 and no item value. Calling `std::iter::repeat_n(x, 0)` just drops that value, but there's no way to construct the same result without a value yet. This would be straightforward with an empty `Default`. [1]: https://github.com/rayon-rs/rayon/blob/ae07384e3e0b238cea89f0c14891f351c65a5cee/src/iter/repeat.rs#L201-L202 r? libs-api (insta-stable)
2 parents 2f201bc + a66b781 commit 96b3eff

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,15 @@ impl<A: fmt::Debug> fmt::Debug for RepeatN<A> {
102102
}
103103
}
104104

105+
/// Creates an empty iterator, like [`repeat_n(value, 0)`][`repeat_n`]
106+
/// but without needing any such value at hand.
107+
#[stable(feature = "iter_repeat_n_default", since = "CURRENT_RUSTC_VERSION")]
108+
impl<A> Default for RepeatN<A> {
109+
fn default() -> Self {
110+
RepeatN { inner: None }
111+
}
112+
}
113+
105114
#[stable(feature = "iter_repeat_n", since = "1.82.0")]
106115
impl<A: Clone> Iterator for RepeatN<A> {
107116
type Item = A;

library/coretests/tests/iter/sources.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,19 @@ fn test_repeat_n_soundness() {
192192
let _z = y;
193193
assert_eq!(0, *x);
194194
}
195+
196+
#[test]
197+
fn test_repeat_n_default() {
198+
#[derive(Clone)]
199+
pub struct PanicOnDrop;
200+
201+
impl Drop for PanicOnDrop {
202+
fn drop(&mut self) {
203+
unreachable!()
204+
}
205+
}
206+
207+
// The default is an empty iterator, so there's never any item to drop.
208+
let iter = RepeatN::<PanicOnDrop>::default();
209+
assert_eq!(iter.count(), 0);
210+
}

0 commit comments

Comments
 (0)