Created
March 4, 2021 06:13
-
-
Save kathampy/00ac3e26d1109d98e60612c090772d5e to your computer and use it in GitHub Desktop.
Checked add signed to usize.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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