diff options
| author | bors <bors@rust-lang.org> | 2013-08-15 13:50:10 -0700 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2013-08-15 13:50:10 -0700 |
| commit | 5c0d1923bc3e26da1b6e043be49147f68ee2444f (patch) | |
| tree | 8a3804b174859bbbd3a918be7c74e0f902f4bcbf /src/libstd | |
| parent | fc3297ff0574f5c4101e76e34c083c7f599cd956 (diff) | |
| parent | 15159a5638d2cf415ea6687e88ea6f62e04bf2ae (diff) | |
| download | rust-5c0d1923bc3e26da1b6e043be49147f68ee2444f.tar.gz rust-5c0d1923bc3e26da1b6e043be49147f68ee2444f.zip | |
auto merge of #8515 : kballard/rust/saturating-checked, r=thestinger
r? @thestinger
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/num/num.rs | 63 |
1 files changed, 25 insertions, 38 deletions
diff --git a/src/libstd/num/num.rs b/src/libstd/num/num.rs index 9e72b355bf9..04a1cc11b26 100644 --- a/src/libstd/num/num.rs +++ b/src/libstd/num/num.rs @@ -468,55 +468,42 @@ impl<T: Zero> Zero for ~T { } /// Saturating math operations -pub trait Saturating: Int { +pub trait Saturating { /// Saturating addition operator. /// Returns a+b, saturating at the numeric bounds instead of overflowing. + fn saturating_add(self, v: Self) -> Self; + + /// Saturating subtraction operator. + /// Returns a-b, saturating at the numeric bounds instead of overflowing. + fn saturating_sub(self, v: Self) -> Self; +} + +impl<T: CheckedAdd+CheckedSub+Zero+Ord+Bounded> Saturating for T { #[inline] - fn saturating_add(self, v: Self) -> Self { - let x = self + v; - if v >= Zero::zero() { - if x < self { - // overflow - Bounded::max_value::<Self>() - } else { x } - } else { - if x > self { - // underflow - Bounded::min_value::<Self>() - } else { x } + fn saturating_add(self, v: T) -> T { + match self.checked_add(&v) { + Some(x) => x, + None => if v >= Zero::zero() { + Bounded::max_value::<T>() + } else { + Bounded::min_value::<T>() + } } } - /// Saturating subtraction operator. - /// Returns a-b, saturating at the numeric bounds instead of overflowing. #[inline] - fn saturating_sub(self, v: Self) -> Self { - let x = self - v; - if v >= Zero::zero() { - if x > self { - // underflow - Bounded::min_value::<Self>() - } else { x } - } else { - if x < self { - // overflow - Bounded::max_value::<Self>() - } else { x } + fn saturating_sub(self, v: T) -> T { + match self.checked_sub(&v) { + Some(x) => x, + None => if v >= Zero::zero() { + Bounded::min_value::<T>() + } else { + Bounded::max_value::<T>() + } } } } -impl Saturating for int {} -impl Saturating for i8 {} -impl Saturating for i16 {} -impl Saturating for i32 {} -impl Saturating for i64 {} -impl Saturating for uint {} -impl Saturating for u8 {} -impl Saturating for u16 {} -impl Saturating for u32 {} -impl Saturating for u64 {} - pub trait CheckedAdd: Add<Self, Self> { fn checked_add(&self, v: &Self) -> Option<Self>; } |
