Skip to content

Instantly share code, notes, and snippets.

@kathampy
Created March 4, 2021 06:13
Show Gist options
  • Save kathampy/00ac3e26d1109d98e60612c090772d5e to your computer and use it in GitHub Desktop.
Save kathampy/00ac3e26d1109d98e60612c090772d5e to your computer and use it in GitHub Desktop.
Checked add signed to usize.
fn add(u: usize, i: i32) -> Option<usize> {
if i.is_negative() {
u.checked_sub(i.wrapping_abs() as u32 as usize)
} else {
u.checked_add(i as usize)
}
}
fn main() {
let u = 7;
let i1 = -1;
let i2 = 1;
assert_eq!(add(u, i1), Some(6));
assert_eq!(add(u, i2), Some(8));
assert_eq!(add(0, -1), None);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment