|
12 | 12 |
|
13 | 13 | #[allow(non_uppercase_statics)];
|
14 | 14 |
|
15 |
| -use num::BitCount; |
| 15 | +use num::{BitCount, CheckedAdd, CheckedSub, CheckedMul}; |
| 16 | +use option::{Option, Some, None}; |
| 17 | +use unstable::intrinsics; |
16 | 18 |
|
17 | 19 | pub use self::generated::*;
|
18 | 20 |
|
@@ -51,6 +53,72 @@ impl BitCount for int {
|
51 | 53 | fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int }
|
52 | 54 | }
|
53 | 55 |
|
| 56 | +#[cfg(target_word_size = "32")] |
| 57 | +impl CheckedAdd for int { |
| 58 | + #[inline] |
| 59 | + fn checked_add(&self, v: &int) -> Option<int> { |
| 60 | + unsafe { |
| 61 | + let (x, y) = intrinsics::i32_add_with_overflow(*self as i32, *v as i32); |
| 62 | + if y { None } else { Some(x as int) } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +#[cfg(target_word_size = "64")] |
| 68 | +impl CheckedAdd for int { |
| 69 | + #[inline] |
| 70 | + fn checked_add(&self, v: &int) -> Option<int> { |
| 71 | + unsafe { |
| 72 | + let (x, y) = intrinsics::i64_add_with_overflow(*self as i64, *v as i64); |
| 73 | + if y { None } else { Some(x as int) } |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +#[cfg(target_word_size = "32")] |
| 79 | +impl CheckedSub for int { |
| 80 | + #[inline] |
| 81 | + fn checked_sub(&self, v: &int) -> Option<int> { |
| 82 | + unsafe { |
| 83 | + let (x, y) = intrinsics::i32_sub_with_overflow(*self as i32, *v as i32); |
| 84 | + if y { None } else { Some(x as int) } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +#[cfg(target_word_size = "64")] |
| 90 | +impl CheckedSub for int { |
| 91 | + #[inline] |
| 92 | + fn checked_sub(&self, v: &int) -> Option<int> { |
| 93 | + unsafe { |
| 94 | + let (x, y) = intrinsics::i64_sub_with_overflow(*self as i64, *v as i64); |
| 95 | + if y { None } else { Some(x as int) } |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +#[cfg(target_word_size = "32")] |
| 101 | +impl CheckedMul for int { |
| 102 | + #[inline] |
| 103 | + fn checked_mul(&self, v: &int) -> Option<int> { |
| 104 | + unsafe { |
| 105 | + let (x, y) = intrinsics::i32_mul_with_overflow(*self as i32, *v as i32); |
| 106 | + if y { None } else { Some(x as int) } |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +#[cfg(target_word_size = "64")] |
| 112 | +impl CheckedMul for int { |
| 113 | + #[inline] |
| 114 | + fn checked_mul(&self, v: &int) -> Option<int> { |
| 115 | + unsafe { |
| 116 | + let (x, y) = intrinsics::i64_mul_with_overflow(*self as i64, *v as i64); |
| 117 | + if y { None } else { Some(x as int) } |
| 118 | + } |
| 119 | + } |
| 120 | +} |
| 121 | + |
54 | 122 | /// Returns `base` raised to the power of `exponent`
|
55 | 123 | pub fn pow(base: int, exponent: uint) -> int {
|
56 | 124 | if exponent == 0u {
|
|
0 commit comments