Skip to content

Instantly share code, notes, and snippets.

@Florob
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Florob/0ec238fa00a0c9b40bf7 to your computer and use it in GitHub Desktop.
Save Florob/0ec238fa00a0c9b40bf7 to your computer and use it in GitHub Desktop.
Checked<T> type for more ergonomic checked integer arithmetic
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