Skip to content

@Florob /checked.rs secret
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.