Skip to content

Commit f72b7f7

Browse files
committed
Optimize StepBy::nth overflow handling
1 parent f08dec1 commit f72b7f7

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/libcore/iter/mod.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,7 @@ use fmt;
307307
use iter_private::TrustedRandomAccess;
308308
use ops::Try;
309309
use usize;
310+
use intrinsics;
310311

311312
#[stable(feature = "rust1", since = "1.0.0")]
312313
pub use self::iterator::Iterator;
@@ -718,7 +719,11 @@ impl<I> Iterator for StepBy<I> where I: Iterator {
718719
}
719720

720721
// overflow handling
721-
while n.checked_mul(step).is_none() {
722+
loop {
723+
let mul = n.checked_mul(step);
724+
if unsafe { intrinsics::likely(mul.is_some())} {
725+
return self.iter.nth(mul.unwrap() - 1);
726+
}
722727
let div_n = usize::MAX / n;
723728
let div_step = usize::MAX / step;
724729
let nth_n = div_n * n;
@@ -732,7 +737,6 @@ impl<I> Iterator for StepBy<I> where I: Iterator {
732737
};
733738
self.iter.nth(nth - 1);
734739
}
735-
self.iter.nth(n * step - 1)
736740
}
737741
}
738742

0 commit comments

Comments
 (0)