@@ -202,26 +202,24 @@ macro_rules! step_identical_methods {
202
202
203
203
#[ inline]
204
204
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 ) ;
212
209
}
210
+ // Do wrapping math to allow e.g. `Step::forward(-128u8, 255)`.
211
+ start. wrapping_add( n as Self ) as Self
213
212
}
214
213
215
214
#[ inline]
216
215
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 ) ;
224
220
}
221
+ // Do wrapping math to allow e.g. `Step::backward(127u8, 255)`.
222
+ start. wrapping_sub( n as Self ) as Self
225
223
}
226
224
} ;
227
225
}
0 commit comments