fix(corelib): Take::nth(usize::MAX) returns None instead of overflowing - #10022
Conversation
`self.n.checked_sub(n + 1)` evaluated `n + 1` before the bounds check, so it overflowed for `n == usize::MAX`. Use `n.checked_add(1)` in a let-chain so an overflow falls through to the not-enough-elements branch (None) rather than panicking. Add a regression case to test_iter_adapter_take_nth. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This stack of pull requests is managed by Graphite. Learn more about stacking. |
PR SummaryLow Risk Overview A regression test in Reviewed by Cursor Bugbot for commit e0dc81d. Bugbot is set up for automated code reviews on this repo. Configure here. |
eytan-starkware
left a comment
There was a problem hiding this comment.
@eytan-starkware reviewed 2 files and all commit messages, and made 1 comment.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on orizi).

Summary
Fixes an integer overflow in
Take::nth()when called withn = usize::MAX. Previously, the implementation computedn + 1directly before callingchecked_sub, which would overflow whennisusize::MAX. The fix splits the operation into two checked steps: first usingchecked_add(1)onn, then passing the result tochecked_sub, so that overflow is handled safely andNoneis returned instead of panicking or producing incorrect results.Type of change
Please check one:
Why is this change needed?
Calling
iter.take(n).nth(usize::MAX)would overflow when computingn + 1before the checked subtraction, causing incorrect behavior instead of safely returningNone.What was the behavior or documentation before?
Take::nth(usize::MAX)would overflow on then + 1arithmetic, since the addition was performed before any overflow check.What is the behavior or documentation after?
Take::nth(usize::MAX)now correctly returnsNonewithout overflowing, becausen.checked_add(1)is evaluated first and short-circuits the rest of the expression on overflow.Related issue or discussion (if any)
None.
Additional context
A regression test was added to
iter_test.cairoto assert thatnth(usize::MAX)returnsNoneon aTakeiterator, preventing this overflow from being reintroduced.