-
-
Save Florob/0ec238fa00a0c9b40bf7 to your computer and use it in GitHub Desktop.
Checked<T> type for more ergonomic checked integer arithmetic
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
use std::fmt; | |
struct Checked<T>(T); | |
impl<T: fmt::Show> fmt::Show for Checked<T> { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
let Checked(ref s) = *self; | |
s.fmt(f) | |
} | |
} | |
impl<T: CheckedAdd> Add<Checked<T>, Checked<T>> for Checked<T> { | |
fn add(&self, other: &Checked<T>) -> Checked<T> { | |
let Checked(ref s) = *self; | |
let Checked(ref o) = *other; | |
Checked(s.checked_add(o).expect("addition failed")) | |
} | |
} | |
impl<T: CheckedSub> Sub<Checked<T>, Checked<T>> for Checked<T> { | |
fn sub(&self, other: &Checked<T>) -> Checked<T> { | |
let Checked(ref s) = *self; | |
let Checked(ref o) = *other; | |
Checked(s.checked_sub(o).expect("subtraction failed")) | |
} | |
} | |
impl<T: CheckedMul> Mul<Checked<T>, Checked<T>> for Checked<T> { | |
fn mul(&self, other: &Checked<T>) -> Checked<T> { | |
let Checked(ref s) = *self; | |
let Checked(ref o) = *other; | |
Checked(s.checked_mul(o).expect("multiplication failed")) | |
} | |
} | |
impl<T: CheckedDiv> Div<Checked<T>, Checked<T>> for Checked<T> { | |
fn div(&self, other: &Checked<T>) -> Checked<T> { | |
let Checked(ref s) = *self; | |
let Checked(ref o) = *other; | |
Checked(s.checked_div(o).expect("division failed")) | |
} | |
} | |
fn main() { | |
let a = Checked(250u8); | |
let b = Checked(5); | |
let c = a + b; | |
let c = c - b; | |
let c = c / Checked(2); | |
let c = c * Checked(2); | |
println!("{}", c); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment