Skip to content

Commit ff07ec2

Browse files
authored
IteratorRandom::sample: allow large "amount" (#1695)
2 parents ac856a6 + 51ebbd8 commit ff07ec2

File tree

2 files changed

+3
-6
lines changed

2 files changed

+3
-6
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
1919
- Remove fns `SeedableRng::from_os_rng`, `try_from_os_rng` (#1674)
2020
- Remove `Clone` support for `StdRng`, `ReseedingRng` (#1677)
2121
- Use `postcard` instead of `bincode` to test the serde feature (#1693)
22+
- Avoid excessive allocation in `IteratorRandom::sample` when `amount` is much larger than iterator size ([#1695])
2223
- Rename `os_rng` -> `sys_rng`, `OsRng` -> `SysRng`, `OsError` -> `SysError` ([#1697])
2324

2425
### Additions
2526
- Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632)
2627
- Pub export `Xoshiro128PlusPlus`, `Xoshiro256PlusPlus` prngs (#1649)
2728
- Pub export `ChaCha8Rng`, `ChaCha12Rng`, `ChaCha20Rng` behind `chacha` feature (#1659)
2829

30+
[#1695]: https://github.com/rust-random/rand/pull/1695
2931
[#1697]: https://github.com/rust-random/rand/pull/1697
3032

3133
## [0.9.2] - 2025-07-20

src/seq/iterator.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,7 @@ pub trait IteratorRandom: Iterator + Sized {
245245
where
246246
R: Rng + ?Sized,
247247
{
248-
let mut reservoir = Vec::with_capacity(amount);
249-
reservoir.extend(self.by_ref().take(amount));
248+
let mut reservoir = Vec::from_iter(self.by_ref().take(amount));
250249

251250
// Continue unless the iterator was exhausted
252251
//
@@ -259,10 +258,6 @@ pub trait IteratorRandom: Iterator + Sized {
259258
*slot = elem;
260259
}
261260
}
262-
} else {
263-
// Don't hang onto extra memory. There is a corner case where
264-
// `amount` was much less than `self.len()`.
265-
reservoir.shrink_to_fit();
266261
}
267262
reservoir
268263
}

0 commit comments

Comments
 (0)