Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
- Remove fns `SeedableRng::from_os_rng`, `try_from_os_rng` (#1674)
- Remove `Clone` support for `StdRng`, `ReseedingRng` (#1677)
- Use `postcard` instead of `bincode` to test the serde feature (#1693)
- Avoid excessive allocation in `IteratorRandom::sample` when `amount` is much larger than iterator size

### Additions
- Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632)
Expand Down
9 changes: 8 additions & 1 deletion src/seq/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,14 @@ pub trait IteratorRandom: Iterator + Sized {
where
R: Rng + ?Sized,
{
let mut reservoir = Vec::with_capacity(amount);
let (size_lower_bound, _size_upper_bound) = self.size_hint();

// If the requested amount is much larger than the iterator size,
// avoid excessive allocation even that it is temporary.
// This also prevents allocation panic for small iterators but large requested amount.
let capacity = core::cmp::min(amount, size_lower_bound);

let mut reservoir = Vec::with_capacity(capacity);
reservoir.extend(self.by_ref().take(amount));

// Continue unless the iterator was exhausted
Expand Down