Skip to content

Instantly share code, notes, and snippets.

@brendanzab

brendanzab/checked_math.rs

Last active Aug 29, 2015
Embed
What would you like to do?
struct Checked<T>(T);
impl<T: CheckedAdd> Add<Checked<T>, Option<Checked<T>>> for Checked<T> {
fn add(&self, other: &Checked<T>) -> Option<Checked<T>> {
let (&Checked(ref x), &Checked(ref y)) = (self, other);
x.checked_add(y).map(|z| Checked(z))
}
}
impl<T: CheckedSub> Sub<Checked<T>, Option<Checked<T>>> for Checked<T> {
fn sub(&self, other: &Checked<T>) -> Option<Checked<T>> {
let (&Checked(ref x), &Checked(ref y)) = (self, other);
x.checked_sub(y).map(|z| Checked(z))
}
}
impl<T: CheckedMul> Mul<Checked<T>, Option<Checked<T>>> for Checked<T> {
fn mul(&self, other: &Checked<T>) -> Option<Checked<T>> {
let (&Checked(ref x), &Checked(ref y)) = (self, other);
x.checked_mul(y).map(|z| Checked(z))
}
}
impl<T: CheckedDiv> Div<Checked<T>, Option<Checked<T>>> for Checked<T> {
fn div(&self, other: &Checked<T>) -> Option<Checked<T>> {
let (&Checked(ref x), &Checked(ref y)) = (self, other);
x.checked_div(y).map(|z| Checked(z))
}
}
struct I8(i8);
impl Add<I8, I8> for I8 {
fn add(&self, other: &I8) -> I8 {
let (&I8(ref x), &I8(ref y)) = (self, other);
I8(x.checked_add(y).unwrap())
}
}
struct UnChecked<T>(T);
impl Add<UnChecked<I8>, UnChecked<I8>> for UnChecked<I8> {
fn add(&self, other: &UnChecked<I8>) -> UnChecked<I8> {
match (self, other) {
(&UnChecked(I8(x)), &UnChecked(I8(y))) => {
UnChecked(I8(x + y))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment