diff --git a/CHANGELOG.md b/CHANGELOG.md index 11b680958b..6a37e48b4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ([#1695]) - Rename `os_rng` -> `sys_rng`, `OsRng` -> `SysRng`, `OsError` -> `SysError` ([#1697]) ### Additions @@ -26,6 +27,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - Pub export `Xoshiro128PlusPlus`, `Xoshiro256PlusPlus` prngs (#1649) - Pub export `ChaCha8Rng`, `ChaCha12Rng`, `ChaCha20Rng` behind `chacha` feature (#1659) +[#1695]: https://github.com/rust-random/rand/pull/1695 [#1697]: https://github.com/rust-random/rand/pull/1697 ## [0.9.2] - 2025-07-20 diff --git a/src/seq/iterator.rs b/src/seq/iterator.rs index 187ca3c055..65ccb987b6 100644 --- a/src/seq/iterator.rs +++ b/src/seq/iterator.rs @@ -245,8 +245,7 @@ pub trait IteratorRandom: Iterator + Sized { where R: Rng + ?Sized, { - let mut reservoir = Vec::with_capacity(amount); - reservoir.extend(self.by_ref().take(amount)); + let mut reservoir = Vec::from_iter(self.by_ref().take(amount)); // Continue unless the iterator was exhausted // @@ -259,10 +258,6 @@ pub trait IteratorRandom: Iterator + Sized { *slot = elem; } } - } else { - // Don't hang onto extra memory. There is a corner case where - // `amount` was much less than `self.len()`. - reservoir.shrink_to_fit(); } reservoir }