Sitelet https://github.com/starkware-libs/cairo/commit/06a9b14b3b9f854af3eb6d45d81985b99cd8f867
Skip to content

Commit 06a9b14

Browse files
oriziclaude
andauthored
fix(corelib): Take::nth(usize::MAX) returns None instead of overflowing (#10022)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 82313ac commit 06a9b14

2 files changed

Lines changed: 7 additions & 2 deletions

File tree

‎corelib/src/iter/adapters/take.cairo‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::num::traits::CheckedSub;
1+
use crate::num::traits::{CheckedAdd, CheckedSub};
22

33
/// An iterator that only iterates over the first `n` iterations of `iter`.
44
///
@@ -29,7 +29,8 @@ impl TakeIterator<I, impl TIter: Iterator<I>, +Drop<I>> of Iterator<Take<I>> {
2929
fn nth<+Destruct<Take<I>>, +Destruct<Self::Item>>(
3030
ref self: Take<I>, n: usize,
3131
) -> Option<Self::Item> {
32-
if let Some(updated_n) = self.n.checked_sub(n + 1) {
32+
if let Some(n_plus_1) = n.checked_add(1)
33+
&& let Some(updated_n) = self.n.checked_sub(n_plus_1) {
3334
self.n = updated_n;
3435
self.iter.nth(n)
3536
} else {

‎corelib/src/test/iter_test.cairo‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,10 @@ fn test_iter_adapter_take_nth() {
135135
// Test when n = 0
136136
let mut iter = (1_u8..=3).into_iter().take(0);
137137
assert_eq!(iter.nth(0), None);
138+
139+
// `nth(usize::MAX)` must return `None`, not overflow on `n + 1`.
140+
let mut iter = (1_u8..=10).into_iter().take(5);
141+
assert_eq!(iter.nth(core::num::traits::Bounded::<usize>::MAX), None);
138142
}
139143

140144
#[test]

0 commit comments

Comments
 (0)