219. checked_add_signed — Move an Unsigned Index by a Signed Delta, No Cast
You have a usize index and a delta: isize that might be negative. idx + delta won’t even compile, and casting your way around it wraps silently on underflow.
The naive fixes are both wrong in their own way:
| |
That cast dance hides bugs: subtract past zero and you get a gigantic index instead of an error.
checked_add_signed adds a signed offset to an unsigned integer and hands back an Option — None exactly when the result would underflow below zero or overflow the type:
| |
So moving a cursor inside bounds becomes one honest expression — no as, no manual if delta < 0 branch:
| |
It’s available on every unsigned type with its matching signed offset (u32 takes i32, usize takes isize, and so on). If you’d rather clamp than reject, the saturating_add_signed sibling pins the result to the type’s bounds instead of returning None. And as of Rust 1.90 the _sub_signed variants round out the set for subtracting a signed amount.