Skip to content

Rewrite Saturating in terms of CheckedAdd/CheckedSub #8515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 25 additions & 38 deletions src/libstd/num/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
}
Expand Down