Created
January 21, 2019 17:49
-
-
Save snoyberg/f14da075cc5694847e5a33c6b4416508 to your computer and use it in GitHub Desktop.
NoWrap data type in Rust
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
#[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