Skip to content

IteratorRandom::sample: allow large "amount"#1695

Merged
dhardy merged 2 commits into
rust-random:masterfrom
stepancheg:iter-sample
Dec 28, 2025
Merged

IteratorRandom::sample: allow large "amount"#1695
dhardy merged 2 commits into
rust-random:masterfrom
stepancheg:iter-sample

Conversation

@stepancheg

Copy link
Copy Markdown
Contributor

Summary

When requested amount is large but, but iterator is small, avoid allocating too large vec.

Motivation

If there's wrapper of such API (e.g. remote API), and it has parameter "sample size", because it is external API, user may pass very large value there, and if a user does that, it is better not to crash.

Details

This change is no-op where iterator lower bound is equal to iterator size.

  • Added a CHANGELOG.md entry

@stepancheg stepancheg force-pushed the iter-sample branch 2 times, most recently from eb80734 to cf6ba84 Compare December 20, 2025 07:51
@dhardy

dhardy commented Dec 22, 2025

Copy link
Copy Markdown
Member

From a look at the Vec::extend code I think we don't need to reserve anything at all.

@stepancheg

Copy link
Copy Markdown
Contributor Author

Yes, I think we should just avoid guessing capacity, because in many cases iterator should provide lower bound, and when it is not, we will do a few reallocations, not a big deal.

I updated the PR.

@dhardy dhardy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR

@dhardy dhardy merged commit ff07ec2 into rust-random:master Dec 28, 2025
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants