Skip to content

Commit

Permalink
auto merge of rust-lang#8459 : thestinger/rust/checked, r=graydon
Browse files Browse the repository at this point in the history
  • Loading branch information
bors committed Aug 19, 2013
2 parents 2246d56 + b244911 commit 4bdceb9
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
21 changes: 20 additions & 1 deletion src/libstd/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ macro_rules! int_module (($T:ty, $bits:expr) => (mod generated {
#[allow(non_uppercase_statics)];

use num::{ToStrRadix, FromStrRadix};
use num::{Zero, One, strconv};
use num::{CheckedDiv, Zero, One, strconv};
use prelude::*;
use str;

Expand All @@ -29,6 +29,17 @@ pub static bytes : uint = ($bits / 8);
pub static min_value: $T = (-1 as $T) << (bits - 1);
pub static max_value: $T = min_value - 1 as $T;

impl CheckedDiv for $T {
#[inline]
fn checked_div(&self, v: &$T) -> Option<$T> {
if *v == 0 || (*self == min_value && *v == -1) {
None
} else {
Some(self / *v)
}
}
}

enum Range { Closed, HalfOpen }

#[inline]
Expand Down Expand Up @@ -551,6 +562,7 @@ mod tests {
use super::*;
use prelude::*;
use int;
use i16;
use i32;
use i64;
Expand Down Expand Up @@ -921,6 +933,13 @@ mod tests {
fn test_range_step_zero_step() {
do range_step(0,10,0) |_i| { true };
}

#[test]
fn test_signed_checked_div() {
assert_eq!(10i.checked_div(&2), Some(5));
assert_eq!(5i.checked_div(&0), None);
assert_eq!(int::min_value.checked_div(&-1), None);
}
}

}))
4 changes: 4 additions & 0 deletions src/libstd/num/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,10 @@ impl CheckedMul for uint {
}
}

pub trait CheckedDiv: Div<Self, Self> {
fn checked_div(&self, v: &Self) -> Option<Self>;
}

/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T:Num + NumCast>(ten: T, two: T) {
Expand Down
19 changes: 18 additions & 1 deletion src/libstd/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (mod generated {

use num::BitCount;
use num::{ToStrRadix, FromStrRadix};
use num::{Zero, One, strconv};
use num::{CheckedDiv, Zero, One, strconv};
use prelude::*;
use str;

Expand All @@ -30,6 +30,17 @@ pub static bytes : uint = ($bits / 8);
pub static min_value: $T = 0 as $T;
pub static max_value: $T = 0 as $T - 1 as $T;

impl CheckedDiv for $T {
#[inline]
fn checked_div(&self, v: &$T) -> Option<$T> {
if *v == 0 {
None
} else {
Some(self / *v)
}
}
}

enum Range { Closed, HalfOpen }

#[inline]
Expand Down Expand Up @@ -694,6 +705,12 @@ mod tests {
fn test_range_step_zero_step_down() {
do range_step(0,-10,0) |_i| { true };
}

#[test]
fn test_unsigned_checked_div() {
assert_eq!(10u.checked_div(&2), Some(5));
assert_eq!(5u.checked_div(&0), None);
}
}

}))

0 comments on commit 4bdceb9

Please sign in to comment.