| 1 |
#![feature(intrinsics)] |
| 2 |
|
| 3 |
#[lang = "sized"] |
| 4 |
pub trait Sized {} |
| 5 |
|
| 6 |
mod intrinsics { |
| 7 |
extern "rust-intrinsic" { |
| 8 |
pub fn add_with_overflow<T>(x: T, y: T) -> (T, bool); |
| 9 |
pub fn sub_with_overflow<T>(x: T, y: T) -> (T, bool); |
| 10 |
pub fn mul_with_overflow<T>(x: T, y: T) -> (T, bool); |
| 11 |
} |
| 12 |
} |
| 13 |
|
| 14 |
pub enum Option<T> { |
| 15 |
None, |
| 16 |
Some(T), |
| 17 |
} |
| 18 |
|
| 19 |
impl i32 { |
| 20 |
pub fn checked_add(self, rhs: Self) -> Option<Self> { |
| 21 |
let (a, b) = self.overflowing_add(rhs); |
| 22 |
if b { |
| 23 |
Option::None |
| 24 |
} else { |
| 25 |
Option::Some(a) |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
pub fn overflowing_add(self, rhs: Self) -> (Self, bool) { |
| 30 |
let (a, b) = unsafe { intrinsics::add_with_overflow(self as i32, rhs as i32) }; |
| 31 |
(a as Self, b) |
| 32 |
} |
| 33 |
|
| 34 |
pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) { |
| 35 |
let (a, b) = unsafe { intrinsics::sub_with_overflow(self as i32, rhs as i32) }; |
| 36 |
(a as Self, b) |
| 37 |
} |
| 38 |
|
| 39 |
pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) { |
| 40 |
let (a, b) = unsafe { intrinsics::mul_with_overflow(self as i32, rhs as i32) }; |
| 41 |
(a as Self, b) |
| 42 |
} |
| 43 |
} |