Skip to content

Commit 90b1961

Browse files
committed
Improve Step::forward/backward for optimization
The previous definition did not optimize down to a single add operation, but this version does appear to.
1 parent cef616b commit 90b1961

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

src/libcore/iter/range.rs

+12-14
Original file line numberDiff line numberDiff line change
@@ -202,26 +202,24 @@ macro_rules! step_identical_methods {
202202

203203
#[inline]
204204
fn forward(start: Self, n: usize) -> Self {
205-
match Self::forward_checked(start, n) {
206-
Some(result) => result,
207-
None => {
208-
let result = Add::add(start, n as Self);
209-
// add one modular cycle to ensure overflow occurs
210-
Add::add(Add::add(result as $u, $u::MAX), 1) as Self
211-
}
205+
// In debug builds, trigger a panic on overflow.
206+
// This should optimize completely out in release builds.
207+
if Self::forward_checked(start, n).is_none() {
208+
let _ = Add::add(Self::MAX, 1);
212209
}
210+
// Do wrapping math to allow e.g. `Step::forward(-128u8, 255)`.
211+
start.wrapping_add(n as Self) as Self
213212
}
214213

215214
#[inline]
216215
fn backward(start: Self, n: usize) -> Self {
217-
match Self::backward_checked(start, n) {
218-
Some(result) => result,
219-
None => {
220-
let result = Sub::sub(start, n as Self);
221-
// sub one modular cycle to ensure overflow occurs
222-
Sub::sub(Sub::sub(result as $u, $u::MAX), 1) as Self
223-
}
216+
// In debug builds, trigger a panic on overflow.
217+
// This should optimize completely out in release builds.
218+
if Self::backward_checked(start, n).is_none() {
219+
let _ = Sub::sub(Self::MIN, 1);
224220
}
221+
// Do wrapping math to allow e.g. `Step::backward(127u8, 255)`.
222+
start.wrapping_sub(n as Self) as Self
225223
}
226224
};
227225
}

0 commit comments

Comments
 (0)