Skip to content

Instantly share code, notes, and snippets.

@snoyberg
Created January 21, 2019 17:49
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 snoyberg/f14da075cc5694847e5a33c6b4416508 to your computer and use it in GitHub Desktop.
Save snoyberg/f14da075cc5694847e5a33c6b4416508 to your computer and use it in GitHub Desktop.
NoWrap data type in Rust
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub struct NoWrap<T>(T);
impl std::ops::Add for NoWrap<u8> {
type Output = Option<Self>;
fn add(self, rhs: Self) -> Self::Output {
self.0.checked_add(rhs.0).map(|x| NoWrap(x))
}
}
fn main() {
let x: NoWrap<u8> = NoWrap(128u8);
let y: NoWrap<u8> = NoWrap(1u8);
assert_eq!(x + y, Some(NoWrap(129)));
assert_eq!(x + x, None);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment