From ec8fb884e94975ed6d82a4cc0ea0a064a4b7155f Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 12 May 2013 21:14:40 -0400 Subject: Remove usage of the #[merge] hack with int modules --- src/libstd/num/i16.rs | 32 ++ src/libstd/num/i32.rs | 32 ++ src/libstd/num/i64.rs | 32 ++ src/libstd/num/i8.rs | 32 ++ src/libstd/num/int-template.rs | 929 ---------------------------------- src/libstd/num/int-template/i16.rs | 41 -- src/libstd/num/int-template/i32.rs | 41 -- src/libstd/num/int-template/i64.rs | 41 -- src/libstd/num/int-template/i8.rs | 41 -- src/libstd/num/int-template/int.rs | 104 ---- src/libstd/num/int.rs | 89 ++++ src/libstd/num/int_macros.rs | 933 +++++++++++++++++++++++++++++++++++ src/libstd/num/u16.rs | 14 + src/libstd/num/u32.rs | 14 + src/libstd/num/u64.rs | 14 + src/libstd/num/u8.rs | 14 + src/libstd/num/uint-template.rs | 641 ------------------------ src/libstd/num/uint-template/u16.rs | 43 -- src/libstd/num/uint-template/u32.rs | 43 -- src/libstd/num/uint-template/u64.rs | 43 -- src/libstd/num/uint-template/u8.rs | 43 -- src/libstd/num/uint-template/uint.rs | 256 ---------- src/libstd/num/uint.rs | 195 ++++++++ src/libstd/num/uint_macros.rs | 667 +++++++++++++++++++++++++ 24 files changed, 2068 insertions(+), 2266 deletions(-) create mode 100644 src/libstd/num/i16.rs create mode 100644 src/libstd/num/i32.rs create mode 100644 src/libstd/num/i64.rs create mode 100644 src/libstd/num/i8.rs delete mode 100644 src/libstd/num/int-template.rs delete mode 100644 src/libstd/num/int-template/i16.rs delete mode 100644 src/libstd/num/int-template/i32.rs delete mode 100644 src/libstd/num/int-template/i64.rs delete mode 100644 src/libstd/num/int-template/i8.rs delete mode 100644 src/libstd/num/int-template/int.rs create mode 100644 src/libstd/num/int.rs create mode 100644 src/libstd/num/int_macros.rs create mode 100644 src/libstd/num/u16.rs create mode 100644 src/libstd/num/u32.rs create mode 100644 src/libstd/num/u64.rs create mode 100644 src/libstd/num/u8.rs delete mode 100644 src/libstd/num/uint-template.rs delete mode 100644 src/libstd/num/uint-template/u16.rs delete mode 100644 src/libstd/num/uint-template/u32.rs delete mode 100644 src/libstd/num/uint-template/u64.rs delete mode 100644 src/libstd/num/uint-template/u8.rs delete mode 100644 src/libstd/num/uint-template/uint.rs create mode 100644 src/libstd/num/uint.rs create mode 100644 src/libstd/num/uint_macros.rs (limited to 'src/libstd/num') diff --git a/src/libstd/num/i16.rs b/src/libstd/num/i16.rs new file mode 100644 index 00000000000..9977247b249 --- /dev/null +++ b/src/libstd/num/i16.rs @@ -0,0 +1,32 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `i16` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i16, 16) + +impl BitCount for i16 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } } +} diff --git a/src/libstd/num/i32.rs b/src/libstd/num/i32.rs new file mode 100644 index 00000000000..0115f306e4e --- /dev/null +++ b/src/libstd/num/i32.rs @@ -0,0 +1,32 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `i32` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i32, 32) + +impl BitCount for i32 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i32 { unsafe { intrinsics::cttz32(*self) } } +} diff --git a/src/libstd/num/i64.rs b/src/libstd/num/i64.rs new file mode 100644 index 00000000000..4e280f01f27 --- /dev/null +++ b/src/libstd/num/i64.rs @@ -0,0 +1,32 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `i64` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i64, 64) + +impl BitCount for i64 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i64 { unsafe { intrinsics::ctpop64(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i64 { unsafe { intrinsics::ctlz64(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i64 { unsafe { intrinsics::cttz64(*self) } } +} diff --git a/src/libstd/num/i8.rs b/src/libstd/num/i8.rs new file mode 100644 index 00000000000..939965b9691 --- /dev/null +++ b/src/libstd/num/i8.rs @@ -0,0 +1,32 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `i8` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i8, 8) + +impl BitCount for i8 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i8 { unsafe { intrinsics::ctpop8(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i8 { unsafe { intrinsics::ctlz8(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i8 { unsafe { intrinsics::cttz8(*self) } } +} diff --git a/src/libstd/num/int-template.rs b/src/libstd/num/int-template.rs deleted file mode 100644 index 068f553ea6b..00000000000 --- a/src/libstd/num/int-template.rs +++ /dev/null @@ -1,929 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use T = self::inst::T; - -use num::{ToStrRadix, FromStrRadix}; -use num::{Zero, One, strconv}; -use prelude::*; - -pub use cmp::{min, max}; - -pub static bits : uint = inst::bits; -pub static bytes : uint = (inst::bits / 8); - -pub static min_value: T = (-1 as T) << (bits - 1); -pub static max_value: T = min_value - 1 as T; - -#[inline(always)] -pub fn add(x: T, y: T) -> T { x + y } -#[inline(always)] -pub fn sub(x: T, y: T) -> T { x - y } -#[inline(always)] -pub fn mul(x: T, y: T) -> T { x * y } -#[inline(always)] -pub fn div(x: T, y: T) -> T { x / y } - -/// -/// Returns the remainder of y / x. -/// -/// # Examples -/// ~~~ -/// assert!(int::rem(5 / 2) == 1); -/// ~~~ -/// -/// When faced with negative numbers, the result copies the sign of the -/// dividend. -/// -/// ~~~ -/// assert!(int::rem(2 / -3) == 2); -/// ~~~ -/// -/// ~~~ -/// assert!(int::rem(-2 / 3) == -2); -/// ~~~ -/// -/// -#[inline(always)] -pub fn rem(x: T, y: T) -> T { x % y } - -#[inline(always)] -pub fn lt(x: T, y: T) -> bool { x < y } -#[inline(always)] -pub fn le(x: T, y: T) -> bool { x <= y } -#[inline(always)] -pub fn eq(x: T, y: T) -> bool { x == y } -#[inline(always)] -pub fn ne(x: T, y: T) -> bool { x != y } -#[inline(always)] -pub fn ge(x: T, y: T) -> bool { x >= y } -#[inline(always)] -pub fn gt(x: T, y: T) -> bool { x > y } - -/// -/// Iterate over the range [`lo`..`hi`) -/// -/// # Arguments -/// -/// * `lo` - lower bound, inclusive -/// * `hi` - higher bound, exclusive -/// -/// # Examples -/// ~~~ -/// let mut sum = 0; -/// for int::range(1, 5) |i| { -/// sum += i; -/// } -/// assert!(sum == 10); -/// ~~~ -/// -#[inline(always)] -/// Iterate over the range [`start`,`start`+`step`..`stop`) -pub fn _range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { - let mut i = start; - if step == 0 { - fail!("range_step called with step == 0"); - } else if step > 0 { // ascending - while i < stop { - if !it(i) { return false; } - // avoiding overflow. break if i + step > max_value - if i > max_value - step { return true; } - i += step; - } - } else { // descending - while i > stop { - if !it(i) { return false; } - // avoiding underflow. break if i + step < min_value - if i < min_value - step { return true; } - i += step; - } - } - return true; -} - -pub fn range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { - _range_step(start, stop, step, it) -} - -#[inline(always)] -/// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { - range_step(lo, hi, 1 as T, it) -} - -#[inline(always)] -/// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { - range_step(hi, lo, -1 as T, it) -} - -/// Computes the bitwise complement -#[inline(always)] -pub fn compl(i: T) -> T { - -1 as T ^ i -} - -/// Computes the absolute value -#[inline(always)] -pub fn abs(i: T) -> T { i.abs() } - -impl Num for T {} - -#[cfg(not(test))] -impl Ord for T { - #[inline(always)] - fn lt(&self, other: &T) -> bool { return (*self) < (*other); } - #[inline(always)] - fn le(&self, other: &T) -> bool { return (*self) <= (*other); } - #[inline(always)] - fn ge(&self, other: &T) -> bool { return (*self) >= (*other); } - #[inline(always)] - fn gt(&self, other: &T) -> bool { return (*self) > (*other); } -} - -#[cfg(not(test))] -impl Eq for T { - #[inline(always)] - fn eq(&self, other: &T) -> bool { return (*self) == (*other); } - #[inline(always)] - fn ne(&self, other: &T) -> bool { return (*self) != (*other); } -} - -impl Orderable for T { - #[inline(always)] - fn min(&self, other: &T) -> T { - if *self < *other { *self } else { *other } - } - - #[inline(always)] - fn max(&self, other: &T) -> T { - if *self > *other { *self } else { *other } - } - - /// Returns the number constrained within the range `mn <= self <= mx`. - #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { - cond!( - (*self > *mx) { *mx } - (*self < *mn) { *mn } - _ { *self } - ) - } -} - -impl Zero for T { - #[inline(always)] - fn zero() -> T { 0 } - - #[inline(always)] - fn is_zero(&self) -> bool { *self == 0 } -} - -impl One for T { - #[inline(always)] - fn one() -> T { 1 } -} - -#[cfg(not(test))] -impl Add for T { - #[inline(always)] - fn add(&self, other: &T) -> T { *self + *other } -} - -#[cfg(not(test))] -impl Sub for T { - #[inline(always)] - fn sub(&self, other: &T) -> T { *self - *other } -} - -#[cfg(not(test))] -impl Mul for T { - #[inline(always)] - fn mul(&self, other: &T) -> T { *self * *other } -} - -#[cfg(not(test))] -impl Div for T { - /// - /// Integer division, truncated towards 0. As this behaviour reflects the underlying - /// machine implementation it is more efficient than `Integer::div_floor`. - /// - /// # Examples - /// - /// ~~~ - /// assert!( 8 / 3 == 2); - /// assert!( 8 / -3 == -2); - /// assert!(-8 / 3 == -2); - /// assert!(-8 / -3 == 2); - - /// assert!( 1 / 2 == 0); - /// assert!( 1 / -2 == 0); - /// assert!(-1 / 2 == 0); - /// assert!(-1 / -2 == 0); - /// ~~~ - /// - #[inline(always)] - fn div(&self, other: &T) -> T { *self / *other } -} - -#[cfg(not(test))] -impl Rem for T { - /// - /// Returns the integer remainder after division, satisfying: - /// - /// ~~~ - /// assert!((n / d) * d + (n % d) == n) - /// ~~~ - /// - /// # Examples - /// - /// ~~~ - /// assert!( 8 % 3 == 2); - /// assert!( 8 % -3 == 2); - /// assert!(-8 % 3 == -2); - /// assert!(-8 % -3 == -2); - - /// assert!( 1 % 2 == 1); - /// assert!( 1 % -2 == 1); - /// assert!(-1 % 2 == -1); - /// assert!(-1 % -2 == -1); - /// ~~~ - /// - #[inline(always)] - fn rem(&self, other: &T) -> T { *self % *other } -} - -#[cfg(not(test))] -impl Neg for T { - #[inline(always)] - fn neg(&self) -> T { -*self } -} - -impl Signed for T { - /// Computes the absolute value - #[inline(always)] - fn abs(&self) -> T { - if self.is_negative() { -*self } else { *self } - } - - /// - /// The positive difference of two numbers. Returns `0` if the number is less than or - /// equal to `other`, otherwise the difference between`self` and `other` is returned. - /// - #[inline(always)] - fn abs_sub(&self, other: &T) -> T { - if *self <= *other { 0 } else { *self - *other } - } - - /// - /// # Returns - /// - /// - `0` if the number is zero - /// - `1` if the number is positive - /// - `-1` if the number is negative - /// - #[inline(always)] - fn signum(&self) -> T { - match *self { - n if n > 0 => 1, - 0 => 0, - _ => -1, - } - } - - /// Returns true if the number is positive - #[inline(always)] - fn is_positive(&self) -> bool { *self > 0 } - - /// Returns true if the number is negative - #[inline(always)] - fn is_negative(&self) -> bool { *self < 0 } -} - -impl Integer for T { - /// - /// Floored integer division - /// - /// # Examples - /// - /// ~~~ - /// assert!(( 8).div_floor( 3) == 2); - /// assert!(( 8).div_floor(-3) == -3); - /// assert!((-8).div_floor( 3) == -3); - /// assert!((-8).div_floor(-3) == 2); - /// - /// assert!(( 1).div_floor( 2) == 0); - /// assert!(( 1).div_floor(-2) == -1); - /// assert!((-1).div_floor( 2) == -1); - /// assert!((-1).div_floor(-2) == 0); - /// ~~~ - /// - #[inline(always)] - fn div_floor(&self, other: &T) -> T { - // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, - // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) - match self.div_rem(other) { - (d, r) if (r > 0 && *other < 0) - || (r < 0 && *other > 0) => d - 1, - (d, _) => d, - } - } - - /// - /// Integer modulo, satisfying: - /// - /// ~~~ - /// assert!(n.div_floor(d) * d + n.mod_floor(d) == n) - /// ~~~ - /// - /// # Examples - /// - /// ~~~ - /// assert!(( 8).mod_floor( 3) == 2); - /// assert!(( 8).mod_floor(-3) == -1); - /// assert!((-8).mod_floor( 3) == 1); - /// assert!((-8).mod_floor(-3) == -2); - /// - /// assert!(( 1).mod_floor( 2) == 1); - /// assert!(( 1).mod_floor(-2) == -1); - /// assert!((-1).mod_floor( 2) == 1); - /// assert!((-1).mod_floor(-2) == -1); - /// ~~~ - /// - #[inline(always)] - fn mod_floor(&self, other: &T) -> T { - // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, - // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) - match *self % *other { - r if (r > 0 && *other < 0) - || (r < 0 && *other > 0) => r + *other, - r => r, - } - } - - /// Calculates `div_floor` and `mod_floor` simultaneously - #[inline(always)] - fn div_mod_floor(&self, other: &T) -> (T,T) { - // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, - // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) - match self.div_rem(other) { - (d, r) if (r > 0 && *other < 0) - || (r < 0 && *other > 0) => (d - 1, r + *other), - (d, r) => (d, r), - } - } - - /// Calculates `div` (`\`) and `rem` (`%`) simultaneously - #[inline(always)] - fn div_rem(&self, other: &T) -> (T,T) { - (*self / *other, *self % *other) - } - - /// - /// Calculates the Greatest Common Divisor (GCD) of the number and `other` - /// - /// The result is always positive - /// - #[inline(always)] - fn gcd(&self, other: &T) -> T { - // Use Euclid's algorithm - let mut m = *self, n = *other; - while m != 0 { - let temp = m; - m = n % temp; - n = temp; - } - n.abs() - } - - /// - /// Calculates the Lowest Common Multiple (LCM) of the number and `other` - /// - #[inline(always)] - fn lcm(&self, other: &T) -> T { - ((*self * *other) / self.gcd(other)).abs() // should not have to recaluculate abs - } - - /// Returns `true` if the number can be divided by `other` without leaving a remainder - #[inline(always)] - fn is_multiple_of(&self, other: &T) -> bool { *self % *other == 0 } - - /// Returns `true` if the number is divisible by `2` - #[inline(always)] - fn is_even(&self) -> bool { self.is_multiple_of(&2) } - - /// Returns `true` if the number is not divisible by `2` - #[inline(always)] - fn is_odd(&self) -> bool { !self.is_even() } -} - -impl Bitwise for T {} - -#[cfg(not(test))] -impl BitOr for T { - #[inline(always)] - fn bitor(&self, other: &T) -> T { *self | *other } -} - -#[cfg(not(test))] -impl BitAnd for T { - #[inline(always)] - fn bitand(&self, other: &T) -> T { *self & *other } -} - -#[cfg(not(test))] -impl BitXor for T { - #[inline(always)] - fn bitxor(&self, other: &T) -> T { *self ^ *other } -} - -#[cfg(not(test))] -impl Shl for T { - #[inline(always)] - fn shl(&self, other: &T) -> T { *self << *other } -} - -#[cfg(not(test))] -impl Shr for T { - #[inline(always)] - fn shr(&self, other: &T) -> T { *self >> *other } -} - -#[cfg(not(test))] -impl Not for T { - #[inline(always)] - fn not(&self) -> T { !*self } -} - -impl Bounded for T { - #[inline(always)] - fn min_value() -> T { min_value } - - #[inline(always)] - fn max_value() -> T { max_value } -} - -impl Int for T {} - -// String conversion functions and impl str -> num - -/// Parse a string as a number in base 10. -#[inline(always)] -pub fn from_str(s: &str) -> Option { - strconv::from_str_common(s, 10u, true, false, false, - strconv::ExpNone, false, false) -} - -/// Parse a string as a number in the given base. -#[inline(always)] -pub fn from_str_radix(s: &str, radix: uint) -> Option { - strconv::from_str_common(s, radix, true, false, false, - strconv::ExpNone, false, false) -} - -/// Parse a byte slice as a number in the given base. -#[inline(always)] -pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { - strconv::from_str_bytes_common(buf, radix, true, false, false, - strconv::ExpNone, false, false) -} - -impl FromStr for T { - #[inline(always)] - fn from_str(s: &str) -> Option { - from_str(s) - } -} - -impl FromStrRadix for T { - #[inline(always)] - fn from_str_radix(s: &str, radix: uint) -> Option { - from_str_radix(s, radix) - } -} - -// String conversion functions and impl num -> str - -/// Convert to a string as a byte slice in a given base. -#[inline(always)] -pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { - let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, - strconv::SignNeg, strconv::DigAll); - f(buf) -} - -/// Convert to a string in base 10. -#[inline(always)] -pub fn to_str(num: T) -> ~str { - let (buf, _) = strconv::to_str_common(&num, 10u, false, - strconv::SignNeg, strconv::DigAll); - buf -} - -/// Convert to a string in a given base. -#[inline(always)] -pub fn to_str_radix(num: T, radix: uint) -> ~str { - let (buf, _) = strconv::to_str_common(&num, radix, false, - strconv::SignNeg, strconv::DigAll); - buf -} - -impl ToStr for T { - #[inline(always)] - fn to_str(&self) -> ~str { - to_str(*self) - } -} - -impl ToStrRadix for T { - #[inline(always)] - fn to_str_radix(&self, radix: uint) -> ~str { - to_str_radix(*self, radix) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use super::inst::T; - use prelude::*; - - #[test] - fn test_num() { - num::test_num(10 as T, 2 as T); - } - - #[test] - fn test_orderable() { - assert_eq!((1 as T).min(&(2 as T)), 1 as T); - assert_eq!((2 as T).min(&(1 as T)), 1 as T); - assert_eq!((1 as T).max(&(2 as T)), 2 as T); - assert_eq!((2 as T).max(&(1 as T)), 2 as T); - assert_eq!((1 as T).clamp(&(2 as T), &(4 as T)), 2 as T); - assert_eq!((8 as T).clamp(&(2 as T), &(4 as T)), 4 as T); - assert_eq!((3 as T).clamp(&(2 as T), &(4 as T)), 3 as T); - } - - #[test] - pub fn test_abs() { - assert_eq!((1 as T).abs(), 1 as T); - assert_eq!((0 as T).abs(), 0 as T); - assert_eq!((-1 as T).abs(), 1 as T); - } - - #[test] - fn test_abs_sub() { - assert_eq!((-1 as T).abs_sub(&(1 as T)), 0 as T); - assert_eq!((1 as T).abs_sub(&(1 as T)), 0 as T); - assert_eq!((1 as T).abs_sub(&(0 as T)), 1 as T); - assert_eq!((1 as T).abs_sub(&(-1 as T)), 2 as T); - } - - #[test] - fn test_signum() { - assert_eq!((1 as T).signum(), 1 as T); - assert_eq!((0 as T).signum(), 0 as T); - assert_eq!((-0 as T).signum(), 0 as T); - assert_eq!((-1 as T).signum(), -1 as T); - } - - #[test] - fn test_is_positive() { - assert!((1 as T).is_positive()); - assert!(!(0 as T).is_positive()); - assert!(!(-0 as T).is_positive()); - assert!(!(-1 as T).is_positive()); - } - - #[test] - fn test_is_negative() { - assert!(!(1 as T).is_negative()); - assert!(!(0 as T).is_negative()); - assert!(!(-0 as T).is_negative()); - assert!((-1 as T).is_negative()); - } - - /// - /// Checks that the division rule holds for: - /// - /// - `n`: numerator (dividend) - /// - `d`: denominator (divisor) - /// - `qr`: quotient and remainder - /// - #[cfg(test)] - fn test_division_rule((n,d): (T,T), (q,r): (T,T)) { - assert_eq!(d * q + r, n); - } - - #[test] - fn test_div_rem() { - fn test_nd_dr(nd: (T,T), qr: (T,T)) { - let (n,d) = nd; - let separate_div_rem = (n / d, n % d); - let combined_div_rem = n.div_rem(&d); - - assert_eq!(separate_div_rem, qr); - assert_eq!(combined_div_rem, qr); - - test_division_rule(nd, separate_div_rem); - test_division_rule(nd, combined_div_rem); - } - - test_nd_dr(( 8, 3), ( 2, 2)); - test_nd_dr(( 8, -3), (-2, 2)); - test_nd_dr((-8, 3), (-2, -2)); - test_nd_dr((-8, -3), ( 2, -2)); - - test_nd_dr(( 1, 2), ( 0, 1)); - test_nd_dr(( 1, -2), ( 0, 1)); - test_nd_dr((-1, 2), ( 0, -1)); - test_nd_dr((-1, -2), ( 0, -1)); - } - - #[test] - fn test_div_mod_floor() { - fn test_nd_dm(nd: (T,T), dm: (T,T)) { - let (n,d) = nd; - let separate_div_mod_floor = (n.div_floor(&d), n.mod_floor(&d)); - let combined_div_mod_floor = n.div_mod_floor(&d); - - assert_eq!(separate_div_mod_floor, dm); - assert_eq!(combined_div_mod_floor, dm); - - test_division_rule(nd, separate_div_mod_floor); - test_division_rule(nd, combined_div_mod_floor); - } - - test_nd_dm(( 8, 3), ( 2, 2)); - test_nd_dm(( 8, -3), (-3, -1)); - test_nd_dm((-8, 3), (-3, 1)); - test_nd_dm((-8, -3), ( 2, -2)); - - test_nd_dm(( 1, 2), ( 0, 1)); - test_nd_dm(( 1, -2), (-1, -1)); - test_nd_dm((-1, 2), (-1, 1)); - test_nd_dm((-1, -2), ( 0, -1)); - } - - #[test] - fn test_gcd() { - assert_eq!((10 as T).gcd(&2), 2 as T); - assert_eq!((10 as T).gcd(&3), 1 as T); - assert_eq!((0 as T).gcd(&3), 3 as T); - assert_eq!((3 as T).gcd(&3), 3 as T); - assert_eq!((56 as T).gcd(&42), 14 as T); - assert_eq!((3 as T).gcd(&-3), 3 as T); - assert_eq!((-6 as T).gcd(&3), 3 as T); - assert_eq!((-4 as T).gcd(&-2), 2 as T); - } - - #[test] - fn test_lcm() { - assert_eq!((1 as T).lcm(&0), 0 as T); - assert_eq!((0 as T).lcm(&1), 0 as T); - assert_eq!((1 as T).lcm(&1), 1 as T); - assert_eq!((-1 as T).lcm(&1), 1 as T); - assert_eq!((1 as T).lcm(&-1), 1 as T); - assert_eq!((-1 as T).lcm(&-1), 1 as T); - assert_eq!((8 as T).lcm(&9), 72 as T); - assert_eq!((11 as T).lcm(&5), 55 as T); - } - - #[test] - fn test_bitwise() { - assert_eq!(0b1110 as T, (0b1100 as T).bitor(&(0b1010 as T))); - assert_eq!(0b1000 as T, (0b1100 as T).bitand(&(0b1010 as T))); - assert_eq!(0b0110 as T, (0b1100 as T).bitxor(&(0b1010 as T))); - assert_eq!(0b1110 as T, (0b0111 as T).shl(&(1 as T))); - assert_eq!(0b0111 as T, (0b1110 as T).shr(&(1 as T))); - assert_eq!(-(0b11 as T) - (1 as T), (0b11 as T).not()); - } - - #[test] - fn test_multiple_of() { - assert!((6 as T).is_multiple_of(&(6 as T))); - assert!((6 as T).is_multiple_of(&(3 as T))); - assert!((6 as T).is_multiple_of(&(1 as T))); - assert!((-8 as T).is_multiple_of(&(4 as T))); - assert!((8 as T).is_multiple_of(&(-1 as T))); - assert!((-8 as T).is_multiple_of(&(-2 as T))); - } - - #[test] - fn test_even() { - assert_eq!((-4 as T).is_even(), true); - assert_eq!((-3 as T).is_even(), false); - assert_eq!((-2 as T).is_even(), true); - assert_eq!((-1 as T).is_even(), false); - assert_eq!((0 as T).is_even(), true); - assert_eq!((1 as T).is_even(), false); - assert_eq!((2 as T).is_even(), true); - assert_eq!((3 as T).is_even(), false); - assert_eq!((4 as T).is_even(), true); - } - - #[test] - fn test_odd() { - assert_eq!((-4 as T).is_odd(), false); - assert_eq!((-3 as T).is_odd(), true); - assert_eq!((-2 as T).is_odd(), false); - assert_eq!((-1 as T).is_odd(), true); - assert_eq!((0 as T).is_odd(), false); - assert_eq!((1 as T).is_odd(), true); - assert_eq!((2 as T).is_odd(), false); - assert_eq!((3 as T).is_odd(), true); - assert_eq!((4 as T).is_odd(), false); - } - - #[test] - fn test_bitcount() { - assert_eq!((0b010101 as T).population_count(), 3); - } - - #[test] - fn test_primitive() { - assert_eq!(Primitive::bits::(), sys::size_of::() * 8); - assert_eq!(Primitive::bytes::(), sys::size_of::()); - } - - #[test] - fn test_from_str() { - assert_eq!(from_str("0"), Some(0 as T)); - assert_eq!(from_str("3"), Some(3 as T)); - assert_eq!(from_str("10"), Some(10 as T)); - assert_eq!(i32::from_str("123456789"), Some(123456789 as i32)); - assert_eq!(from_str("00100"), Some(100 as T)); - - assert_eq!(from_str("-1"), Some(-1 as T)); - assert_eq!(from_str("-3"), Some(-3 as T)); - assert_eq!(from_str("-10"), Some(-10 as T)); - assert_eq!(i32::from_str("-123456789"), Some(-123456789 as i32)); - assert_eq!(from_str("-00100"), Some(-100 as T)); - - assert!(from_str(" ").is_none()); - assert!(from_str("x").is_none()); - } - - #[test] - fn test_parse_bytes() { - use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123 as T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9 as T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83 as T)); - assert_eq!(i32::parse_bytes(to_bytes("123"), 16u), Some(291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("ffff"), 16u), Some(65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("FFFF"), 16u), Some(65535 as i32)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35 as T)); - assert_eq!(parse_bytes(to_bytes("Z"), 36u), Some(35 as T)); - - assert_eq!(parse_bytes(to_bytes("-123"), 10u), Some(-123 as T)); - assert_eq!(parse_bytes(to_bytes("-1001"), 2u), Some(-9 as T)); - assert_eq!(parse_bytes(to_bytes("-123"), 8u), Some(-83 as T)); - assert_eq!(i32::parse_bytes(to_bytes("-123"), 16u), Some(-291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("-ffff"), 16u), Some(-65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("-FFFF"), 16u), Some(-65535 as i32)); - assert_eq!(parse_bytes(to_bytes("-z"), 36u), Some(-35 as T)); - assert_eq!(parse_bytes(to_bytes("-Z"), 36u), Some(-35 as T)); - - assert!(parse_bytes(to_bytes("Z"), 35u).is_none()); - assert!(parse_bytes(to_bytes("-9"), 2u).is_none()); - } - - #[test] - fn test_to_str() { - assert_eq!(to_str_radix(0 as T, 10u), ~"0"); - assert_eq!(to_str_radix(1 as T, 10u), ~"1"); - assert_eq!(to_str_radix(-1 as T, 10u), ~"-1"); - assert_eq!(to_str_radix(127 as T, 16u), ~"7f"); - assert_eq!(to_str_radix(100 as T, 10u), ~"100"); - - } - - #[test] - fn test_int_to_str_overflow() { - let mut i8_val: i8 = 127_i8; - assert_eq!(i8::to_str(i8_val), ~"127"); - - i8_val += 1 as i8; - assert_eq!(i8::to_str(i8_val), ~"-128"); - - let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16::to_str(i16_val), ~"32767"); - - i16_val += 1 as i16; - assert_eq!(i16::to_str(i16_val), ~"-32768"); - - let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32::to_str(i32_val), ~"2147483647"); - - i32_val += 1 as i32; - assert_eq!(i32::to_str(i32_val), ~"-2147483648"); - - let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64::to_str(i64_val), ~"9223372036854775807"); - - i64_val += 1 as i64; - assert_eq!(i64::to_str(i64_val), ~"-9223372036854775808"); - } - - #[test] - fn test_int_from_str_overflow() { - let mut i8_val: i8 = 127_i8; - assert_eq!(i8::from_str("127"), Some(i8_val)); - assert!(i8::from_str("128").is_none()); - - i8_val += 1 as i8; - assert_eq!(i8::from_str("-128"), Some(i8_val)); - assert!(i8::from_str("-129").is_none()); - - let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16::from_str("32767"), Some(i16_val)); - assert!(i16::from_str("32768").is_none()); - - i16_val += 1 as i16; - assert_eq!(i16::from_str("-32768"), Some(i16_val)); - assert!(i16::from_str("-32769").is_none()); - - let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32::from_str("2147483647"), Some(i32_val)); - assert!(i32::from_str("2147483648").is_none()); - - i32_val += 1 as i32; - assert_eq!(i32::from_str("-2147483648"), Some(i32_val)); - assert!(i32::from_str("-2147483649").is_none()); - - let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64::from_str("9223372036854775807"), Some(i64_val)); - assert!(i64::from_str("9223372036854775808").is_none()); - - i64_val += 1 as i64; - assert_eq!(i64::from_str("-9223372036854775808"), Some(i64_val)); - assert!(i64::from_str("-9223372036854775809").is_none()); - } - - #[test] - fn test_ranges() { - let mut l = ~[]; - - for range(0,3) |i| { - l.push(i); - } - for range_rev(13,10) |i| { - l.push(i); - } - for range_step(20,26,2) |i| { - l.push(i); - } - for range_step(36,30,-2) |i| { - l.push(i); - } - for range_step(max_value - 2, max_value, 2) |i| { - l.push(i); - } - for range_step(max_value - 3, max_value, 2) |i| { - l.push(i); - } - for range_step(min_value + 2, min_value, -2) |i| { - l.push(i); - } - for range_step(min_value + 3, min_value, -2) |i| { - l.push(i); - } - assert_eq!(l, ~[0,1,2, - 13,12,11, - 20,22,24, - 36,34,32, - max_value-2, - max_value-3,max_value-1, - min_value+2, - min_value+3,min_value+1]); - - // None of the `fail`s should execute. - for range(10,0) |_i| { - fail!("unreachable"); - } - for range_rev(0,10) |_i| { - fail!("unreachable"); - } - for range_step(10,0,1) |_i| { - fail!("unreachable"); - } - for range_step(0,10,-1) |_i| { - fail!("unreachable"); - } - } - - #[test] - #[should_fail] - #[ignore(cfg(windows))] - fn test_range_step_zero_step() { - for range_step(0,10,0) |_i| {} - } -} diff --git a/src/libstd/num/int-template/i16.rs b/src/libstd/num/int-template/i16.rs deleted file mode 100644 index 28263378555..00000000000 --- a/src/libstd/num/int-template/i16.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `i16` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i16; - pub static bits: uint = ::u16::bits; - - impl Primitive for i16 { - #[inline(always)] - fn bits() -> uint { 16 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i16 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } } - } -} diff --git a/src/libstd/num/int-template/i32.rs b/src/libstd/num/int-template/i32.rs deleted file mode 100644 index 959cf8f7d77..00000000000 --- a/src/libstd/num/int-template/i32.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `i32` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i32; - pub static bits: uint = ::u32::bits; - - impl Primitive for i32 { - #[inline(always)] - fn bits() -> uint { 32 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i32 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i32 { unsafe { intrinsics::cttz32(*self) } } - } -} diff --git a/src/libstd/num/int-template/i64.rs b/src/libstd/num/int-template/i64.rs deleted file mode 100644 index 3b51c70be12..00000000000 --- a/src/libstd/num/int-template/i64.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `i64` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i64; - pub static bits: uint = ::u64::bits; - - impl Primitive for i64 { - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i64 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i64 { unsafe { intrinsics::ctpop64(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i64 { unsafe { intrinsics::ctlz64(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i64 { unsafe { intrinsics::cttz64(*self) } } - } -} diff --git a/src/libstd/num/int-template/i8.rs b/src/libstd/num/int-template/i8.rs deleted file mode 100644 index 896fb4dbf50..00000000000 --- a/src/libstd/num/int-template/i8.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `i8` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i8; - pub static bits: uint = ::u8::bits; - - impl Primitive for i8 { - #[inline(always)] - fn bits() -> uint { 8 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i8 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i8 { unsafe { intrinsics::ctpop8(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i8 { unsafe { intrinsics::ctlz8(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i8 { unsafe { intrinsics::cttz8(*self) } } - } -} diff --git a/src/libstd/num/int-template/int.rs b/src/libstd/num/int-template/int.rs deleted file mode 100644 index 64f6f2d2a9a..00000000000 --- a/src/libstd/num/int-template/int.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `int` - -pub use self::inst::pow; - -mod inst { - use num::{Primitive, BitCount}; - - pub type T = int; - pub static bits: uint = ::uint::bits; - - impl Primitive for int { - #[cfg(target_word_size = "32")] - #[inline(always)] - fn bits() -> uint { 32 } - - #[cfg(target_word_size = "64")] - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - #[cfg(target_word_size = "32")] - #[inline(always)] - impl BitCount for int { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> int { (*self as i32).population_count() as int } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } - } - - #[cfg(target_word_size = "64")] - #[inline(always)] - impl BitCount for int { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> int { (*self as i64).population_count() as int } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } - } - - /// Returns `base` raised to the power of `exponent` - pub fn pow(base: int, exponent: uint) -> int { - if exponent == 0u { - //Not mathemtically true if ~[base == 0] - return 1; - } - if base == 0 { return 0; } - let mut my_pow = exponent; - let mut acc = 1; - let mut multiplier = base; - while(my_pow > 0u) { - if my_pow % 2u == 1u { - acc *= multiplier; - } - my_pow /= 2u; - multiplier *= multiplier; - } - return acc; - } - - #[test] - fn test_pow() { - assert_eq!(pow(0, 0u), 1); - assert_eq!(pow(0, 1u), 0); - assert_eq!(pow(0, 2u), 0); - assert_eq!(pow(-1, 0u), 1); - assert_eq!(pow(1, 0u), 1); - assert_eq!(pow(-3, 2u), 9); - assert_eq!(pow(-3, 3u), -27); - assert_eq!(pow(4, 9u), 262144); - } - - #[test] - fn test_overflows() { - assert!((::int::max_value > 0)); - assert!((::int::min_value <= 0)); - assert_eq!(::int::min_value + ::int::max_value + 1, 0); - } -} diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs new file mode 100644 index 00000000000..96ef7e9e341 --- /dev/null +++ b/src/libstd/num/int.rs @@ -0,0 +1,89 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `int` + +use num::BitCount; + +pub use self::generated::*; + +#[cfg(target_word_size = "32")] pub static bits: uint = 32; +#[cfg(target_word_size = "64")] pub static bits: uint = 64; + +int_module!(int, super::bits) + +#[cfg(target_word_size = "32")] +impl BitCount for int { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> int { (*self as i32).population_count() as int } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } +} + +#[cfg(target_word_size = "64")] +impl BitCount for int { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> int { (*self as i64).population_count() as int } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } +} + +/// Returns `base` raised to the power of `exponent` +pub fn pow(base: int, exponent: uint) -> int { + if exponent == 0u { + //Not mathemtically true if ~[base == 0] + return 1; + } + if base == 0 { return 0; } + let mut my_pow = exponent; + let mut acc = 1; + let mut multiplier = base; + while(my_pow > 0u) { + if my_pow % 2u == 1u { + acc *= multiplier; + } + my_pow /= 2u; + multiplier *= multiplier; + } + return acc; +} + +#[test] +fn test_pow() { + assert!((pow(0, 0u) == 1)); + assert!((pow(0, 1u) == 0)); + assert!((pow(0, 2u) == 0)); + assert!((pow(-1, 0u) == 1)); + assert!((pow(1, 0u) == 1)); + assert!((pow(-3, 2u) == 9)); + assert!((pow(-3, 3u) == -27)); + assert!((pow(4, 9u) == 262144)); +} + +#[test] +fn test_overflows() { + assert!((::int::max_value > 0)); + assert!((::int::min_value <= 0)); + assert!((::int::min_value + ::int::max_value + 1 == 0)); +} diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs new file mode 100644 index 00000000000..6fde30fdb50 --- /dev/null +++ b/src/libstd/num/int_macros.rs @@ -0,0 +1,933 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// FIXME(#4375): this shouldn't have to be a nested module named 'generated' + +#[macro_escape]; + +macro_rules! int_module (($T:ty, $bits:expr) => (mod generated { + +use num::{ToStrRadix, FromStrRadix}; +use num::{Zero, One, strconv}; +use prelude::*; + +pub use cmp::{min, max}; + +pub static bits : uint = $bits; +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; + +#[inline(always)] +pub fn add(x: $T, y: $T) -> $T { x + y } +#[inline(always)] +pub fn sub(x: $T, y: $T) -> $T { x - y } +#[inline(always)] +pub fn mul(x: $T, y: $T) -> $T { x * y } +#[inline(always)] +pub fn div(x: $T, y: $T) -> $T { x / y } + +/// +/// Returns the remainder of y / x. +/// +/// # Examples +/// ~~~ +/// assert!(int::rem(5 / 2) == 1); +/// ~~~ +/// +/// When faced with negative numbers, the result copies the sign of the +/// dividend. +/// +/// ~~~ +/// assert!(int::rem(2 / -3) == 2); +/// ~~~ +/// +/// ~~~ +/// assert!(int::rem(-2 / 3) == -2); +/// ~~~ +/// +/// +#[inline(always)] +pub fn rem(x: $T, y: $T) -> $T { x % y } + +#[inline(always)] +pub fn lt(x: $T, y: $T) -> bool { x < y } +#[inline(always)] +pub fn le(x: $T, y: $T) -> bool { x <= y } +#[inline(always)] +pub fn eq(x: $T, y: $T) -> bool { x == y } +#[inline(always)] +pub fn ne(x: $T, y: $T) -> bool { x != y } +#[inline(always)] +pub fn ge(x: $T, y: $T) -> bool { x >= y } +#[inline(always)] +pub fn gt(x: $T, y: $T) -> bool { x > y } + +/// +/// Iterate over the range [`lo`..`hi`) +/// +/// # Arguments +/// +/// * `lo` - lower bound, inclusive +/// * `hi` - higher bound, exclusive +/// +/// # Examples +/// ~~~ +/// let mut sum = 0; +/// for int::range(1, 5) |i| { +/// sum += i; +/// } +/// assert!(sum == 10); +/// ~~~ +/// +#[inline(always)] +pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool { + let mut i = start; + if step == 0 { + fail!(~"range_step called with step == 0"); + } else if step > 0 { // ascending + while i < stop { + if !it(i) { return false; } + // avoiding overflow. break if i + step > max_value + if i > max_value - step { return true; } + i += step; + } + } else { // descending + while i > stop { + if !it(i) { return false; } + // avoiding underflow. break if i + step < min_value + if i < min_value - step { return true; } + i += step; + } + } + return true; +} + +#[inline(always)] +/// Iterate over the range [`lo`..`hi`) +pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool { + range_step(lo, hi, 1 as $T, it) +} + +#[inline(always)] +/// Iterate over the range [`hi`..`lo`) +pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool { + range_step(hi, lo, -1 as $T, it) +} + +/// Computes the bitwise complement +#[inline(always)] +pub fn compl(i: $T) -> $T { + -1 as $T ^ i +} + +/// Computes the absolute value +#[inline(always)] +pub fn abs(i: $T) -> $T { i.abs() } + +impl Num for $T {} + +#[cfg(not(test))] +impl Ord for $T { + #[inline(always)] + fn lt(&self, other: &$T) -> bool { return (*self) < (*other); } + #[inline(always)] + fn le(&self, other: &$T) -> bool { return (*self) <= (*other); } + #[inline(always)] + fn ge(&self, other: &$T) -> bool { return (*self) >= (*other); } + #[inline(always)] + fn gt(&self, other: &$T) -> bool { return (*self) > (*other); } +} + +#[cfg(not(test))] +impl Eq for $T { + #[inline(always)] + fn eq(&self, other: &$T) -> bool { return (*self) == (*other); } + #[inline(always)] + fn ne(&self, other: &$T) -> bool { return (*self) != (*other); } +} + +impl Orderable for $T { + #[inline(always)] + fn min(&self, other: &$T) -> $T { + if *self < *other { *self } else { *other } + } + + #[inline(always)] + fn max(&self, other: &$T) -> $T { + if *self > *other { *self } else { *other } + } + + #[inline(always)] + fn clamp(&self, mn: &$T, mx: &$T) -> $T { + if *self > *mx { *mx } else + if *self < *mn { *mn } else { *self } + } +} + +impl Zero for $T { + #[inline(always)] + fn zero() -> $T { 0 } + + #[inline(always)] + fn is_zero(&self) -> bool { *self == 0 } +} + +impl One for $T { + #[inline(always)] + fn one() -> $T { 1 } +} + +#[cfg(not(test))] +impl Add<$T,$T> for $T { + #[inline(always)] + fn add(&self, other: &$T) -> $T { *self + *other } +} + +#[cfg(not(test))] +impl Sub<$T,$T> for $T { + #[inline(always)] + fn sub(&self, other: &$T) -> $T { *self - *other } +} + +#[cfg(not(test))] +impl Mul<$T,$T> for $T { + #[inline(always)] + fn mul(&self, other: &$T) -> $T { *self * *other } +} + +#[cfg(not(test))] +impl Div<$T,$T> for $T { + /// + /// Integer division, truncated towards 0. As this behaviour reflects the underlying + /// machine implementation it is more efficient than `Integer::div_floor`. + /// + /// # Examples + /// + /// ~~~ + /// assert!( 8 / 3 == 2); + /// assert!( 8 / -3 == -2); + /// assert!(-8 / 3 == -2); + /// assert!(-8 / -3 == 2); + + /// assert!( 1 / 2 == 0); + /// assert!( 1 / -2 == 0); + /// assert!(-1 / 2 == 0); + /// assert!(-1 / -2 == 0); + /// ~~~ + /// + #[inline(always)] + fn div(&self, other: &$T) -> $T { *self / *other } +} + +#[cfg(not(test))] +impl Rem<$T,$T> for $T { + /// + /// Returns the integer remainder after division, satisfying: + /// + /// ~~~ + /// assert!((n / d) * d + (n % d) == n) + /// ~~~ + /// + /// # Examples + /// + /// ~~~ + /// assert!( 8 % 3 == 2); + /// assert!( 8 % -3 == 2); + /// assert!(-8 % 3 == -2); + /// assert!(-8 % -3 == -2); + + /// assert!( 1 % 2 == 1); + /// assert!( 1 % -2 == 1); + /// assert!(-1 % 2 == -1); + /// assert!(-1 % -2 == -1); + /// ~~~ + /// + #[inline(always)] + fn rem(&self, other: &$T) -> $T { *self % *other } +} + +#[cfg(not(test))] +impl Neg<$T> for $T { + #[inline(always)] + fn neg(&self) -> $T { -*self } +} + +impl Signed for $T { + /// Computes the absolute value + #[inline(always)] + fn abs(&self) -> $T { + if self.is_negative() { -*self } else { *self } + } + + /// + /// The positive difference of two numbers. Returns `0` if the number is less than or + /// equal to `other`, otherwise the difference between`self` and `other` is returned. + /// + #[inline(always)] + fn abs_sub(&self, other: &$T) -> $T { + if *self <= *other { 0 } else { *self - *other } + } + + /// + /// # Returns + /// + /// - `0` if the number is zero + /// - `1` if the number is positive + /// - `-1` if the number is negative + /// + #[inline(always)] + fn signum(&self) -> $T { + match *self { + n if n > 0 => 1, + 0 => 0, + _ => -1, + } + } + + /// Returns true if the number is positive + #[inline(always)] + fn is_positive(&self) -> bool { *self > 0 } + + /// Returns true if the number is negative + #[inline(always)] + fn is_negative(&self) -> bool { *self < 0 } +} + +impl Integer for $T { + /// + /// Floored integer division + /// + /// # Examples + /// + /// ~~~ + /// assert!(( 8).div_floor( 3) == 2); + /// assert!(( 8).div_floor(-3) == -3); + /// assert!((-8).div_floor( 3) == -3); + /// assert!((-8).div_floor(-3) == 2); + /// + /// assert!(( 1).div_floor( 2) == 0); + /// assert!(( 1).div_floor(-2) == -1); + /// assert!((-1).div_floor( 2) == -1); + /// assert!((-1).div_floor(-2) == 0); + /// ~~~ + /// + #[inline(always)] + fn div_floor(&self, other: &$T) -> $T { + // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, + // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) + match self.div_rem(other) { + (d, r) if (r > 0 && *other < 0) + || (r < 0 && *other > 0) => d - 1, + (d, _) => d, + } + } + + /// + /// Integer modulo, satisfying: + /// + /// ~~~ + /// assert!(n.div_floor(d) * d + n.mod_floor(d) == n) + /// ~~~ + /// + /// # Examples + /// + /// ~~~ + /// assert!(( 8).mod_floor( 3) == 2); + /// assert!(( 8).mod_floor(-3) == -1); + /// assert!((-8).mod_floor( 3) == 1); + /// assert!((-8).mod_floor(-3) == -2); + /// + /// assert!(( 1).mod_floor( 2) == 1); + /// assert!(( 1).mod_floor(-2) == -1); + /// assert!((-1).mod_floor( 2) == 1); + /// assert!((-1).mod_floor(-2) == -1); + /// ~~~ + /// + #[inline(always)] + fn mod_floor(&self, other: &$T) -> $T { + // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, + // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) + match *self % *other { + r if (r > 0 && *other < 0) + || (r < 0 && *other > 0) => r + *other, + r => r, + } + } + + /// Calculates `div_floor` and `mod_floor` simultaneously + #[inline(always)] + fn div_mod_floor(&self, other: &$T) -> ($T,$T) { + // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, + // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) + match self.div_rem(other) { + (d, r) if (r > 0 && *other < 0) + || (r < 0 && *other > 0) => (d - 1, r + *other), + (d, r) => (d, r), + } + } + + /// Calculates `div` (`\`) and `rem` (`%`) simultaneously + #[inline(always)] + fn div_rem(&self, other: &$T) -> ($T,$T) { + (*self / *other, *self % *other) + } + + /// + /// Calculates the Greatest Common Divisor (GCD) of the number and `other` + /// + /// The result is always positive + /// + #[inline(always)] + fn gcd(&self, other: &$T) -> $T { + // Use Euclid's algorithm + let mut m = *self, n = *other; + while m != 0 { + let temp = m; + m = n % temp; + n = temp; + } + n.abs() + } + + /// + /// Calculates the Lowest Common Multiple (LCM) of the number and `other` + /// + #[inline(always)] + fn lcm(&self, other: &$T) -> $T { + ((*self * *other) / self.gcd(other)).abs() // should not have to recaluculate abs + } + + /// Returns `true` if the number can be divided by `other` without leaving a remainder + #[inline(always)] + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + + /// Returns `true` if the number is divisible by `2` + #[inline(always)] + fn is_even(&self) -> bool { self.is_multiple_of(&2) } + + /// Returns `true` if the number is not divisible by `2` + #[inline(always)] + fn is_odd(&self) -> bool { !self.is_even() } +} + +impl Bitwise for $T {} + +#[cfg(not(test))] +impl BitOr<$T,$T> for $T { + #[inline(always)] + fn bitor(&self, other: &$T) -> $T { *self | *other } +} + +#[cfg(not(test))] +impl BitAnd<$T,$T> for $T { + #[inline(always)] + fn bitand(&self, other: &$T) -> $T { *self & *other } +} + +#[cfg(not(test))] +impl BitXor<$T,$T> for $T { + #[inline(always)] + fn bitxor(&self, other: &$T) -> $T { *self ^ *other } +} + +#[cfg(not(test))] +impl Shl<$T,$T> for $T { + #[inline(always)] + fn shl(&self, other: &$T) -> $T { *self << *other } +} + +#[cfg(not(test))] +impl Shr<$T,$T> for $T { + #[inline(always)] + fn shr(&self, other: &$T) -> $T { *self >> *other } +} + +#[cfg(not(test))] +impl Not<$T> for $T { + #[inline(always)] + fn not(&self) -> $T { !*self } +} + +impl Bounded for $T { + #[inline(always)] + fn min_value() -> $T { min_value } + + #[inline(always)] + fn max_value() -> $T { max_value } +} + +impl Int for $T {} + +impl Primitive for $T { + #[inline(always)] + fn bits() -> uint { bits } + + #[inline(always)] + fn bytes() -> uint { bits / 8 } +} + +// String conversion functions and impl str -> num + +/// Parse a string as a number in base 10. +#[inline(always)] +pub fn from_str(s: &str) -> Option<$T> { + strconv::from_str_common(s, 10u, true, false, false, + strconv::ExpNone, false, false) +} + +/// Parse a string as a number in the given base. +#[inline(always)] +pub fn from_str_radix(s: &str, radix: uint) -> Option<$T> { + strconv::from_str_common(s, radix, true, false, false, + strconv::ExpNone, false, false) +} + +/// Parse a byte slice as a number in the given base. +#[inline(always)] +pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> { + strconv::from_str_bytes_common(buf, radix, true, false, false, + strconv::ExpNone, false, false) +} + +impl FromStr for $T { + #[inline(always)] + fn from_str(s: &str) -> Option<$T> { + from_str(s) + } +} + +impl FromStrRadix for $T { + #[inline(always)] + fn from_str_radix(s: &str, radix: uint) -> Option<$T> { + from_str_radix(s, radix) + } +} + +// String conversion functions and impl num -> str + +/// Convert to a string as a byte slice in a given base. +#[inline(always)] +pub fn to_str_bytes(n: $T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { + let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, + strconv::SignNeg, strconv::DigAll); + f(buf) +} + +/// Convert to a string in base 10. +#[inline(always)] +pub fn to_str(num: $T) -> ~str { + let (buf, _) = strconv::to_str_common(&num, 10u, false, + strconv::SignNeg, strconv::DigAll); + buf +} + +/// Convert to a string in a given base. +#[inline(always)] +pub fn to_str_radix(num: $T, radix: uint) -> ~str { + let (buf, _) = strconv::to_str_common(&num, radix, false, + strconv::SignNeg, strconv::DigAll); + buf +} + +impl ToStr for $T { + #[inline(always)] + fn to_str(&self) -> ~str { + to_str(*self) + } +} + +impl ToStrRadix for $T { + #[inline(always)] + fn to_str_radix(&self, radix: uint) -> ~str { + to_str_radix(*self, radix) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use prelude::*; + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_orderable() { + assert_eq!((1 as $T).min(&(2 as $T)), 1 as $T); + assert_eq!((2 as $T).min(&(1 as $T)), 1 as $T); + assert_eq!((1 as $T).max(&(2 as $T)), 2 as $T); + assert_eq!((2 as $T).max(&(1 as $T)), 2 as $T); + assert_eq!((1 as $T).clamp(&(2 as $T), &(4 as $T)), 2 as $T); + assert_eq!((8 as $T).clamp(&(2 as $T), &(4 as $T)), 4 as $T); + assert_eq!((3 as $T).clamp(&(2 as $T), &(4 as $T)), 3 as $T); + } + + #[test] + pub fn test_abs() { + assert_eq!((1 as $T).abs(), 1 as $T); + assert_eq!((0 as $T).abs(), 0 as $T); + assert_eq!((-1 as $T).abs(), 1 as $T); + } + + #[test] + fn test_abs_sub() { + assert_eq!((-1 as $T).abs_sub(&(1 as $T)), 0 as $T); + assert_eq!((1 as $T).abs_sub(&(1 as $T)), 0 as $T); + assert_eq!((1 as $T).abs_sub(&(0 as $T)), 1 as $T); + assert_eq!((1 as $T).abs_sub(&(-1 as $T)), 2 as $T); + } + + #[test] + fn test_signum() { + assert_eq!((1 as $T).signum(), 1 as $T); + assert_eq!((0 as $T).signum(), 0 as $T); + assert_eq!((-0 as $T).signum(), 0 as $T); + assert_eq!((-1 as $T).signum(), -1 as $T); + } + + #[test] + fn test_is_positive() { + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); + } + + #[test] + fn test_is_negative() { + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); + } + + /// + /// Checks that the division rule holds for: + /// + /// - `n`: numerator (dividend) + /// - `d`: denominator (divisor) + /// - `qr`: quotient and remainder + /// + #[cfg(test)] + fn test_division_rule((n,d): ($T,$T), (q,r): ($T,$T)) { + assert_eq!(d * q + r, n); + } + + #[test] + fn test_div_rem() { + fn test_nd_dr(nd: ($T,$T), qr: ($T,$T)) { + let (n,d) = nd; + let separate_div_rem = (n / d, n % d); + let combined_div_rem = n.div_rem(&d); + + assert_eq!(separate_div_rem, qr); + assert_eq!(combined_div_rem, qr); + + test_division_rule(nd, separate_div_rem); + test_division_rule(nd, combined_div_rem); + } + + test_nd_dr(( 8, 3), ( 2, 2)); + test_nd_dr(( 8, -3), (-2, 2)); + test_nd_dr((-8, 3), (-2, -2)); + test_nd_dr((-8, -3), ( 2, -2)); + + test_nd_dr(( 1, 2), ( 0, 1)); + test_nd_dr(( 1, -2), ( 0, 1)); + test_nd_dr((-1, 2), ( 0, -1)); + test_nd_dr((-1, -2), ( 0, -1)); + } + + #[test] + fn test_div_mod_floor() { + fn test_nd_dm(nd: ($T,$T), dm: ($T,$T)) { + let (n,d) = nd; + let separate_div_mod_floor = (n.div_floor(&d), n.mod_floor(&d)); + let combined_div_mod_floor = n.div_mod_floor(&d); + + assert_eq!(separate_div_mod_floor, dm); + assert_eq!(combined_div_mod_floor, dm); + + test_division_rule(nd, separate_div_mod_floor); + test_division_rule(nd, combined_div_mod_floor); + } + + test_nd_dm(( 8, 3), ( 2, 2)); + test_nd_dm(( 8, -3), (-3, -1)); + test_nd_dm((-8, 3), (-3, 1)); + test_nd_dm((-8, -3), ( 2, -2)); + + test_nd_dm(( 1, 2), ( 0, 1)); + test_nd_dm(( 1, -2), (-1, -1)); + test_nd_dm((-1, 2), (-1, 1)); + test_nd_dm((-1, -2), ( 0, -1)); + } + + #[test] + fn test_gcd() { + assert_eq!((10 as $T).gcd(&2), 2 as $T); + assert_eq!((10 as $T).gcd(&3), 1 as $T); + assert_eq!((0 as $T).gcd(&3), 3 as $T); + assert_eq!((3 as $T).gcd(&3), 3 as $T); + assert_eq!((56 as $T).gcd(&42), 14 as $T); + assert_eq!((3 as $T).gcd(&-3), 3 as $T); + assert_eq!((-6 as $T).gcd(&3), 3 as $T); + assert_eq!((-4 as $T).gcd(&-2), 2 as $T); + } + + #[test] + fn test_lcm() { + assert_eq!((1 as $T).lcm(&0), 0 as $T); + assert_eq!((0 as $T).lcm(&1), 0 as $T); + assert_eq!((1 as $T).lcm(&1), 1 as $T); + assert_eq!((-1 as $T).lcm(&1), 1 as $T); + assert_eq!((1 as $T).lcm(&-1), 1 as $T); + assert_eq!((-1 as $T).lcm(&-1), 1 as $T); + assert_eq!((8 as $T).lcm(&9), 72 as $T); + assert_eq!((11 as $T).lcm(&5), 55 as $T); + } + + #[test] + fn test_bitwise() { + assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(&(0b1010 as $T))); + assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(&(0b1010 as $T))); + assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert_eq!(0b1110 as $T, (0b0111 as $T).shl(&(1 as $T))); + assert_eq!(0b0111 as $T, (0b1110 as $T).shr(&(1 as $T))); + assert_eq!(-(0b11 as $T) - (1 as $T), (0b11 as $T).not()); + } + + #[test] + fn test_multiple_of() { + assert!((6 as $T).is_multiple_of(&(6 as $T))); + assert!((6 as $T).is_multiple_of(&(3 as $T))); + assert!((6 as $T).is_multiple_of(&(1 as $T))); + assert!((-8 as $T).is_multiple_of(&(4 as $T))); + assert!((8 as $T).is_multiple_of(&(-1 as $T))); + assert!((-8 as $T).is_multiple_of(&(-2 as $T))); + } + + #[test] + fn test_even() { + assert_eq!((-4 as $T).is_even(), true); + assert_eq!((-3 as $T).is_even(), false); + assert_eq!((-2 as $T).is_even(), true); + assert_eq!((-1 as $T).is_even(), false); + assert_eq!((0 as $T).is_even(), true); + assert_eq!((1 as $T).is_even(), false); + assert_eq!((2 as $T).is_even(), true); + assert_eq!((3 as $T).is_even(), false); + assert_eq!((4 as $T).is_even(), true); + } + + #[test] + fn test_odd() { + assert_eq!((-4 as $T).is_odd(), false); + assert_eq!((-3 as $T).is_odd(), true); + assert_eq!((-2 as $T).is_odd(), false); + assert_eq!((-1 as $T).is_odd(), true); + assert_eq!((0 as $T).is_odd(), false); + assert_eq!((1 as $T).is_odd(), true); + assert_eq!((2 as $T).is_odd(), false); + assert_eq!((3 as $T).is_odd(), true); + assert_eq!((4 as $T).is_odd(), false); + } + + #[test] + fn test_bitcount() { + assert_eq!((0b010101 as $T).population_count(), 3); + } + + #[test] + fn test_primitive() { + assert_eq!(Primitive::bits::<$T>(), sys::size_of::<$T>() * 8); + assert_eq!(Primitive::bytes::<$T>(), sys::size_of::<$T>()); + } + + #[test] + fn test_from_str() { + assert_eq!(from_str(~"0"), Some(0 as $T)); + assert_eq!(from_str(~"3"), Some(3 as $T)); + assert_eq!(from_str(~"10"), Some(10 as $T)); + assert_eq!(i32::from_str(~"123456789"), Some(123456789 as i32)); + assert_eq!(from_str(~"00100"), Some(100 as $T)); + + assert_eq!(from_str(~"-1"), Some(-1 as $T)); + assert_eq!(from_str(~"-3"), Some(-3 as $T)); + assert_eq!(from_str(~"-10"), Some(-10 as $T)); + assert_eq!(i32::from_str(~"-123456789"), Some(-123456789 as i32)); + assert_eq!(from_str(~"-00100"), Some(-100 as $T)); + + assert!(from_str(~" ").is_none()); + assert!(from_str(~"x").is_none()); + } + + #[test] + fn test_parse_bytes() { + use str::to_bytes; + assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123 as $T)); + assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9 as $T)); + assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83 as $T)); + assert_eq!(i32::parse_bytes(to_bytes(~"123"), 16u), Some(291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"FFFF"), 16u), Some(65535 as i32)); + assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35 as $T)); + assert_eq!(parse_bytes(to_bytes(~"Z"), 36u), Some(35 as $T)); + + assert_eq!(parse_bytes(to_bytes(~"-123"), 10u), Some(-123 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-1001"), 2u), Some(-9 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-123"), 8u), Some(-83 as $T)); + assert_eq!(i32::parse_bytes(to_bytes(~"-123"), 16u), Some(-291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"-ffff"), 16u), Some(-65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"-FFFF"), 16u), Some(-65535 as i32)); + assert_eq!(parse_bytes(to_bytes(~"-z"), 36u), Some(-35 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-Z"), 36u), Some(-35 as $T)); + + assert!(parse_bytes(to_bytes(~"Z"), 35u).is_none()); + assert!(parse_bytes(to_bytes(~"-9"), 2u).is_none()); + } + + #[test] + fn test_to_str() { + assert_eq!(to_str_radix(0 as $T, 10u), ~"0"); + assert_eq!(to_str_radix(1 as $T, 10u), ~"1"); + assert_eq!(to_str_radix(-1 as $T, 10u), ~"-1"); + assert_eq!(to_str_radix(127 as $T, 16u), ~"7f"); + assert_eq!(to_str_radix(100 as $T, 10u), ~"100"); + + } + + #[test] + fn test_int_to_str_overflow() { + let mut i8_val: i8 = 127_i8; + assert_eq!(i8::to_str(i8_val), ~"127"); + + i8_val += 1 as i8; + assert_eq!(i8::to_str(i8_val), ~"-128"); + + let mut i16_val: i16 = 32_767_i16; + assert_eq!(i16::to_str(i16_val), ~"32767"); + + i16_val += 1 as i16; + assert_eq!(i16::to_str(i16_val), ~"-32768"); + + let mut i32_val: i32 = 2_147_483_647_i32; + assert_eq!(i32::to_str(i32_val), ~"2147483647"); + + i32_val += 1 as i32; + assert_eq!(i32::to_str(i32_val), ~"-2147483648"); + + let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; + assert_eq!(i64::to_str(i64_val), ~"9223372036854775807"); + + i64_val += 1 as i64; + assert_eq!(i64::to_str(i64_val), ~"-9223372036854775808"); + } + + #[test] + fn test_int_from_str_overflow() { + let mut i8_val: i8 = 127_i8; + assert_eq!(i8::from_str(~"127"), Some(i8_val)); + assert!(i8::from_str(~"128").is_none()); + + i8_val += 1 as i8; + assert_eq!(i8::from_str(~"-128"), Some(i8_val)); + assert!(i8::from_str(~"-129").is_none()); + + let mut i16_val: i16 = 32_767_i16; + assert_eq!(i16::from_str(~"32767"), Some(i16_val)); + assert!(i16::from_str(~"32768").is_none()); + + i16_val += 1 as i16; + assert_eq!(i16::from_str(~"-32768"), Some(i16_val)); + assert!(i16::from_str(~"-32769").is_none()); + + let mut i32_val: i32 = 2_147_483_647_i32; + assert_eq!(i32::from_str(~"2147483647"), Some(i32_val)); + assert!(i32::from_str(~"2147483648").is_none()); + + i32_val += 1 as i32; + assert_eq!(i32::from_str(~"-2147483648"), Some(i32_val)); + assert!(i32::from_str(~"-2147483649").is_none()); + + let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; + assert_eq!(i64::from_str(~"9223372036854775807"), Some(i64_val)); + assert!(i64::from_str(~"9223372036854775808").is_none()); + + i64_val += 1 as i64; + assert_eq!(i64::from_str(~"-9223372036854775808"), Some(i64_val)); + assert!(i64::from_str(~"-9223372036854775809").is_none()); + } + + #[test] + fn test_ranges() { + let mut l = ~[]; + + for range(0,3) |i| { + l.push(i); + } + for range_rev(13,10) |i| { + l.push(i); + } + for range_step(20,26,2) |i| { + l.push(i); + } + for range_step(36,30,-2) |i| { + l.push(i); + } + for range_step(max_value - 2, max_value, 2) |i| { + l.push(i); + } + for range_step(max_value - 3, max_value, 2) |i| { + l.push(i); + } + for range_step(min_value + 2, min_value, -2) |i| { + l.push(i); + } + for range_step(min_value + 3, min_value, -2) |i| { + l.push(i); + } + assert_eq!(l, ~[0,1,2, + 13,12,11, + 20,22,24, + 36,34,32, + max_value-2, + max_value-3,max_value-1, + min_value+2, + min_value+3,min_value+1]); + + // None of the `fail`s should execute. + for range(10,0) |_i| { + fail!(~"unreachable"); + } + for range_rev(0,10) |_i| { + fail!(~"unreachable"); + } + for range_step(10,0,1) |_i| { + fail!(~"unreachable"); + } + for range_step(0,10,-1) |_i| { + fail!(~"unreachable"); + } + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + fn test_range_step_zero_step() { + for range_step(0,10,0) |_i| {} + } +} + +})) diff --git a/src/libstd/num/u16.rs b/src/libstd/num/u16.rs new file mode 100644 index 00000000000..3a4c2420f9e --- /dev/null +++ b/src/libstd/num/u16.rs @@ -0,0 +1,14 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `u16` + +pub use self::generated::*; +uint_module!(u16, i16, 16) diff --git a/src/libstd/num/u32.rs b/src/libstd/num/u32.rs new file mode 100644 index 00000000000..f87fa7fcd42 --- /dev/null +++ b/src/libstd/num/u32.rs @@ -0,0 +1,14 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `u32` + +pub use self::generated::*; +uint_module!(u32, i32, 32) diff --git a/src/libstd/num/u64.rs b/src/libstd/num/u64.rs new file mode 100644 index 00000000000..792db155569 --- /dev/null +++ b/src/libstd/num/u64.rs @@ -0,0 +1,14 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `u64` + +pub use self::generated::*; +uint_module!(u64, i64, 64) diff --git a/src/libstd/num/u8.rs b/src/libstd/num/u8.rs new file mode 100644 index 00000000000..e21e80f8406 --- /dev/null +++ b/src/libstd/num/u8.rs @@ -0,0 +1,14 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `u8` + +pub use self::generated::*; +uint_module!(u8, i8, 8) diff --git a/src/libstd/num/uint-template.rs b/src/libstd/num/uint-template.rs deleted file mode 100644 index 9784fe24206..00000000000 --- a/src/libstd/num/uint-template.rs +++ /dev/null @@ -1,641 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use T = self::inst::T; -use T_SIGNED = self::inst::T_SIGNED; - -use num::{ToStrRadix, FromStrRadix}; -use num::{Zero, One, strconv}; -use prelude::*; - -pub use cmp::{min, max}; - -pub static bits : uint = inst::bits; -pub static bytes : uint = (inst::bits / 8); - -pub static min_value: T = 0 as T; -pub static max_value: T = 0 as T - 1 as T; - -#[inline(always)] -pub fn add(x: T, y: T) -> T { x + y } -#[inline(always)] -pub fn sub(x: T, y: T) -> T { x - y } -#[inline(always)] -pub fn mul(x: T, y: T) -> T { x * y } -#[inline(always)] -pub fn div(x: T, y: T) -> T { x / y } -#[inline(always)] -pub fn rem(x: T, y: T) -> T { x % y } - -#[inline(always)] -pub fn lt(x: T, y: T) -> bool { x < y } -#[inline(always)] -pub fn le(x: T, y: T) -> bool { x <= y } -#[inline(always)] -pub fn eq(x: T, y: T) -> bool { x == y } -#[inline(always)] -pub fn ne(x: T, y: T) -> bool { x != y } -#[inline(always)] -pub fn ge(x: T, y: T) -> bool { x >= y } -#[inline(always)] -pub fn gt(x: T, y: T) -> bool { x > y } - -#[inline(always)] -/// -/// Iterate over the range [`start`,`start`+`step`..`stop`) -/// -pub fn _range_step(start: T, - stop: T, - step: T_SIGNED, - it: &fn(T) -> bool) -> bool { - let mut i = start; - if step == 0 { - fail!("range_step called with step == 0"); - } - if step >= 0 { - while i < stop { - if !it(i) { return false; } - // avoiding overflow. break if i + step > max_value - if i > max_value - (step as T) { return true; } - i += step as T; - } - } else { - while i > stop { - if !it(i) { return false; } - // avoiding underflow. break if i + step < min_value - if i < min_value + ((-step) as T) { return true; } - i -= -step as T; - } - } - return true; -} - -pub fn range_step(start: T, stop: T, step: T_SIGNED, it: &fn(T) -> bool) -> bool { - _range_step(start, stop, step, it) -} - -#[inline(always)] -/// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { - range_step(lo, hi, 1 as T_SIGNED, it) -} - -#[inline(always)] -/// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { - range_step(hi, lo, -1 as T_SIGNED, it) -} - -/// Computes the bitwise complement -#[inline(always)] -pub fn compl(i: T) -> T { - max_value ^ i -} - -impl Num for T {} - -#[cfg(not(test))] -impl Ord for T { - #[inline(always)] - fn lt(&self, other: &T) -> bool { (*self) < (*other) } - #[inline(always)] - fn le(&self, other: &T) -> bool { (*self) <= (*other) } - #[inline(always)] - fn ge(&self, other: &T) -> bool { (*self) >= (*other) } - #[inline(always)] - fn gt(&self, other: &T) -> bool { (*self) > (*other) } -} - -#[cfg(not(test))] -impl Eq for T { - #[inline(always)] - fn eq(&self, other: &T) -> bool { return (*self) == (*other); } - #[inline(always)] - fn ne(&self, other: &T) -> bool { return (*self) != (*other); } -} - -impl Orderable for T { - #[inline(always)] - fn min(&self, other: &T) -> T { - if *self < *other { *self } else { *other } - } - - #[inline(always)] - fn max(&self, other: &T) -> T { - if *self > *other { *self } else { *other } - } - - /// Returns the number constrained within the range `mn <= self <= mx`. - #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { - cond!( - (*self > *mx) { *mx } - (*self < *mn) { *mn } - _ { *self } - ) - } -} - -impl Zero for T { - #[inline(always)] - fn zero() -> T { 0 } - - #[inline(always)] - fn is_zero(&self) -> bool { *self == 0 } -} - -impl One for T { - #[inline(always)] - fn one() -> T { 1 } -} - -#[cfg(not(test))] -impl Add for T { - #[inline(always)] - fn add(&self, other: &T) -> T { *self + *other } -} - -#[cfg(not(test))] -impl Sub for T { - #[inline(always)] - fn sub(&self, other: &T) -> T { *self - *other } -} - -#[cfg(not(test))] -impl Mul for T { - #[inline(always)] - fn mul(&self, other: &T) -> T { *self * *other } -} - -#[cfg(not(test))] -impl Div for T { - #[inline(always)] - fn div(&self, other: &T) -> T { *self / *other } -} - -#[cfg(not(test))] -impl Rem for T { - #[inline(always)] - fn rem(&self, other: &T) -> T { *self % *other } -} - -#[cfg(not(test))] -impl Neg for T { - #[inline(always)] - fn neg(&self) -> T { -*self } -} - -impl Unsigned for T {} - -impl Integer for T { - /// Calculates `div` (`\`) and `rem` (`%`) simultaneously - #[inline(always)] - fn div_rem(&self, other: &T) -> (T,T) { - (*self / *other, *self % *other) - } - - /// Unsigned integer division. Returns the same result as `div` (`/`). - #[inline(always)] - fn div_floor(&self, other: &T) -> T { *self / *other } - - /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). - #[inline(always)] - fn mod_floor(&self, other: &T) -> T { *self / *other } - - /// Calculates `div_floor` and `modulo_floor` simultaneously - #[inline(always)] - fn div_mod_floor(&self, other: &T) -> (T,T) { - (*self / *other, *self % *other) - } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other` - #[inline(always)] - fn gcd(&self, other: &T) -> T { - // Use Euclid's algorithm - let mut m = *self, n = *other; - while m != 0 { - let temp = m; - m = n % temp; - n = temp; - } - n - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other` - #[inline(always)] - fn lcm(&self, other: &T) -> T { - (*self * *other) / self.gcd(other) - } - - /// Returns `true` if the number can be divided by `other` without leaving a remainder - #[inline(always)] - fn is_multiple_of(&self, other: &T) -> bool { *self % *other == 0 } - - /// Returns `true` if the number is divisible by `2` - #[inline(always)] - fn is_even(&self) -> bool { self.is_multiple_of(&2) } - - /// Returns `true` if the number is not divisible by `2` - #[inline(always)] - fn is_odd(&self) -> bool { !self.is_even() } -} - -impl Bitwise for T {} - -#[cfg(not(test))] -impl BitOr for T { - #[inline(always)] - fn bitor(&self, other: &T) -> T { *self | *other } -} - -#[cfg(not(test))] -impl BitAnd for T { - #[inline(always)] - fn bitand(&self, other: &T) -> T { *self & *other } -} - -#[cfg(not(test))] -impl BitXor for T { - #[inline(always)] - fn bitxor(&self, other: &T) -> T { *self ^ *other } -} - -#[cfg(not(test))] -impl Shl for T { - #[inline(always)] - fn shl(&self, other: &T) -> T { *self << *other } -} - -#[cfg(not(test))] -impl Shr for T { - #[inline(always)] - fn shr(&self, other: &T) -> T { *self >> *other } -} - -#[cfg(not(test))] -impl Not for T { - #[inline(always)] - fn not(&self) -> T { !*self } -} - -impl Bounded for T { - #[inline(always)] - fn min_value() -> T { min_value } - - #[inline(always)] - fn max_value() -> T { max_value } -} - -impl Int for T {} - -// String conversion functions and impl str -> num - -/// Parse a string as a number in base 10. -#[inline(always)] -pub fn from_str(s: &str) -> Option { - strconv::from_str_common(s, 10u, false, false, false, - strconv::ExpNone, false, false) -} - -/// Parse a string as a number in the given base. -#[inline(always)] -pub fn from_str_radix(s: &str, radix: uint) -> Option { - strconv::from_str_common(s, radix, false, false, false, - strconv::ExpNone, false, false) -} - -/// Parse a byte slice as a number in the given base. -#[inline(always)] -pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { - strconv::from_str_bytes_common(buf, radix, false, false, false, - strconv::ExpNone, false, false) -} - -impl FromStr for T { - #[inline(always)] - fn from_str(s: &str) -> Option { - from_str(s) - } -} - -impl FromStrRadix for T { - #[inline(always)] - fn from_str_radix(s: &str, radix: uint) -> Option { - from_str_radix(s, radix) - } -} - -// String conversion functions and impl num -> str - -/// Convert to a string as a byte slice in a given base. -#[inline(always)] -pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { - let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, - strconv::SignNeg, strconv::DigAll); - f(buf) -} - -/// Convert to a string in base 10. -#[inline(always)] -pub fn to_str(num: T) -> ~str { - let (buf, _) = strconv::to_str_common(&num, 10u, false, - strconv::SignNeg, strconv::DigAll); - buf -} - -/// Convert to a string in a given base. -#[inline(always)] -pub fn to_str_radix(num: T, radix: uint) -> ~str { - let (buf, _) = strconv::to_str_common(&num, radix, false, - strconv::SignNeg, strconv::DigAll); - buf -} - -impl ToStr for T { - #[inline(always)] - fn to_str(&self) -> ~str { - to_str(*self) - } -} - -impl ToStrRadix for T { - #[inline(always)] - fn to_str_radix(&self, radix: uint) -> ~str { - to_str_radix(*self, radix) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use super::inst::T; - use prelude::*; - - #[test] - fn test_num() { - num::test_num(10 as T, 2 as T); - } - - #[test] - fn test_orderable() { - assert_eq!((1 as T).min(&(2 as T)), 1 as T); - assert_eq!((2 as T).min(&(1 as T)), 1 as T); - assert_eq!((1 as T).max(&(2 as T)), 2 as T); - assert_eq!((2 as T).max(&(1 as T)), 2 as T); - assert_eq!((1 as T).clamp(&(2 as T), &(4 as T)), 2 as T); - assert_eq!((8 as T).clamp(&(2 as T), &(4 as T)), 4 as T); - assert_eq!((3 as T).clamp(&(2 as T), &(4 as T)), 3 as T); - } - - #[test] - fn test_gcd() { - assert_eq!((10 as T).gcd(&2), 2 as T); - assert_eq!((10 as T).gcd(&3), 1 as T); - assert_eq!((0 as T).gcd(&3), 3 as T); - assert_eq!((3 as T).gcd(&3), 3 as T); - assert_eq!((56 as T).gcd(&42), 14 as T); - } - - #[test] - fn test_lcm() { - assert_eq!((1 as T).lcm(&0), 0 as T); - assert_eq!((0 as T).lcm(&1), 0 as T); - assert_eq!((1 as T).lcm(&1), 1 as T); - assert_eq!((8 as T).lcm(&9), 72 as T); - assert_eq!((11 as T).lcm(&5), 55 as T); - assert_eq!((99 as T).lcm(&17), 1683 as T); - } - - #[test] - fn test_multiple_of() { - assert!((6 as T).is_multiple_of(&(6 as T))); - assert!((6 as T).is_multiple_of(&(3 as T))); - assert!((6 as T).is_multiple_of(&(1 as T))); - } - - #[test] - fn test_even() { - assert_eq!((0 as T).is_even(), true); - assert_eq!((1 as T).is_even(), false); - assert_eq!((2 as T).is_even(), true); - assert_eq!((3 as T).is_even(), false); - assert_eq!((4 as T).is_even(), true); - } - - #[test] - fn test_odd() { - assert_eq!((0 as T).is_odd(), false); - assert_eq!((1 as T).is_odd(), true); - assert_eq!((2 as T).is_odd(), false); - assert_eq!((3 as T).is_odd(), true); - assert_eq!((4 as T).is_odd(), false); - } - - #[test] - fn test_bitwise() { - assert_eq!(0b1110 as T, (0b1100 as T).bitor(&(0b1010 as T))); - assert_eq!(0b1000 as T, (0b1100 as T).bitand(&(0b1010 as T))); - assert_eq!(0b0110 as T, (0b1100 as T).bitxor(&(0b1010 as T))); - assert_eq!(0b1110 as T, (0b0111 as T).shl(&(1 as T))); - assert_eq!(0b0111 as T, (0b1110 as T).shr(&(1 as T))); - assert_eq!(max_value - (0b1011 as T), (0b1011 as T).not()); - } - - #[test] - fn test_bitcount() { - assert_eq!((0b010101 as T).population_count(), 3); - } - - #[test] - fn test_primitive() { - assert_eq!(Primitive::bits::(), sys::size_of::() * 8); - assert_eq!(Primitive::bytes::(), sys::size_of::()); - } - - #[test] - pub fn test_to_str() { - assert_eq!(to_str_radix(0 as T, 10u), ~"0"); - assert_eq!(to_str_radix(1 as T, 10u), ~"1"); - assert_eq!(to_str_radix(2 as T, 10u), ~"2"); - assert_eq!(to_str_radix(11 as T, 10u), ~"11"); - assert_eq!(to_str_radix(11 as T, 16u), ~"b"); - assert_eq!(to_str_radix(255 as T, 16u), ~"ff"); - assert_eq!(to_str_radix(0xff as T, 10u), ~"255"); - } - - #[test] - pub fn test_from_str() { - assert_eq!(from_str("0"), Some(0u as T)); - assert_eq!(from_str("3"), Some(3u as T)); - assert_eq!(from_str("10"), Some(10u as T)); - assert_eq!(u32::from_str("123456789"), Some(123456789 as u32)); - assert_eq!(from_str("00100"), Some(100u as T)); - - assert!(from_str("").is_none()); - assert!(from_str(" ").is_none()); - assert!(from_str("x").is_none()); - } - - #[test] - pub fn test_parse_bytes() { - use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123u as T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9u as T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83u as T)); - assert_eq!(u16::parse_bytes(to_bytes("123"), 16u), Some(291u as u16)); - assert_eq!(u16::parse_bytes(to_bytes("ffff"), 16u), Some(65535u as u16)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35u as T)); - - assert!(parse_bytes(to_bytes("Z"), 10u).is_none()); - assert!(parse_bytes(to_bytes("_"), 2u).is_none()); - } - - #[test] - fn test_uint_to_str_overflow() { - let mut u8_val: u8 = 255_u8; - assert_eq!(u8::to_str(u8_val), ~"255"); - - u8_val += 1 as u8; - assert_eq!(u8::to_str(u8_val), ~"0"); - - let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16::to_str(u16_val), ~"65535"); - - u16_val += 1 as u16; - assert_eq!(u16::to_str(u16_val), ~"0"); - - let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32::to_str(u32_val), ~"4294967295"); - - u32_val += 1 as u32; - assert_eq!(u32::to_str(u32_val), ~"0"); - - let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64::to_str(u64_val), ~"18446744073709551615"); - - u64_val += 1 as u64; - assert_eq!(u64::to_str(u64_val), ~"0"); - } - - #[test] - fn test_uint_from_str_overflow() { - let mut u8_val: u8 = 255_u8; - assert_eq!(u8::from_str("255"), Some(u8_val)); - assert!(u8::from_str("256").is_none()); - - u8_val += 1 as u8; - assert_eq!(u8::from_str("0"), Some(u8_val)); - assert!(u8::from_str("-1").is_none()); - - let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16::from_str("65535"), Some(u16_val)); - assert!(u16::from_str("65536").is_none()); - - u16_val += 1 as u16; - assert_eq!(u16::from_str("0"), Some(u16_val)); - assert!(u16::from_str("-1").is_none()); - - let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32::from_str("4294967295"), Some(u32_val)); - assert!(u32::from_str("4294967296").is_none()); - - u32_val += 1 as u32; - assert_eq!(u32::from_str("0"), Some(u32_val)); - assert!(u32::from_str("-1").is_none()); - - let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64::from_str("18446744073709551615"), Some(u64_val)); - assert!(u64::from_str("18446744073709551616").is_none()); - - u64_val += 1 as u64; - assert_eq!(u64::from_str("0"), Some(u64_val)); - assert!(u64::from_str("-1").is_none()); - } - - #[test] - #[should_fail] - #[ignore(cfg(windows))] - pub fn to_str_radix1() { - uint::to_str_radix(100u, 1u); - } - - #[test] - #[should_fail] - #[ignore(cfg(windows))] - pub fn to_str_radix37() { - uint::to_str_radix(100u, 37u); - } - - #[test] - pub fn test_ranges() { - let mut l = ~[]; - - for range(0,3) |i| { - l.push(i); - } - for range_rev(13,10) |i| { - l.push(i); - } - for range_step(20,26,2) |i| { - l.push(i); - } - for range_step(36,30,-2) |i| { - l.push(i); - } - for range_step(max_value - 2, max_value, 2) |i| { - l.push(i); - } - for range_step(max_value - 3, max_value, 2) |i| { - l.push(i); - } - for range_step(min_value + 2, min_value, -2) |i| { - l.push(i); - } - for range_step(min_value + 3, min_value, -2) |i| { - l.push(i); - } - - assert_eq!(l, ~[0,1,2, - 13,12,11, - 20,22,24, - 36,34,32, - max_value-2, - max_value-3,max_value-1, - min_value+2, - min_value+3,min_value+1]); - - // None of the `fail`s should execute. - for range(0,0) |_i| { - fail!("unreachable"); - } - for range_rev(0,0) |_i| { - fail!("unreachable"); - } - for range_step(10,0,1) |_i| { - fail!("unreachable"); - } - for range_step(0,1,-10) |_i| { - fail!("unreachable"); - } - } - - #[test] - #[should_fail] - #[ignore(cfg(windows))] - fn test_range_step_zero_step_up() { - for range_step(0,10,0) |_i| {} - } - #[test] - #[should_fail] - #[ignore(cfg(windows))] - fn test_range_step_zero_step_down() { - for range_step(0,-10,0) |_i| {} - } -} diff --git a/src/libstd/num/uint-template/u16.rs b/src/libstd/num/uint-template/u16.rs deleted file mode 100644 index cc262f6b4de..00000000000 --- a/src/libstd/num/uint-template/u16.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `u16` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u16; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i16; - pub static bits: uint = 16; - - impl Primitive for u16 { - #[inline(always)] - fn bits() -> uint { 16 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u16 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u16 { unsafe { intrinsics::ctpop16(*self as i16) as u16 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u16 { unsafe { intrinsics::ctlz16(*self as i16) as u16 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u16 { unsafe { intrinsics::cttz16(*self as i16) as u16 } } - } -} diff --git a/src/libstd/num/uint-template/u32.rs b/src/libstd/num/uint-template/u32.rs deleted file mode 100644 index 7d7c8e3be30..00000000000 --- a/src/libstd/num/uint-template/u32.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `u32` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u32; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i32; - pub static bits: uint = 32; - - impl Primitive for u32 { - #[inline(always)] - fn bits() -> uint { 32 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u32 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u32 { unsafe { intrinsics::ctpop32(*self as i32) as u32 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } } - } -} diff --git a/src/libstd/num/uint-template/u64.rs b/src/libstd/num/uint-template/u64.rs deleted file mode 100644 index 756c29950c3..00000000000 --- a/src/libstd/num/uint-template/u64.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `u64` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u64; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i64; - pub static bits: uint = 64; - - impl Primitive for u64 { - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u64 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u64 { unsafe { intrinsics::ctpop64(*self as i64) as u64 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u64 { unsafe { intrinsics::ctlz64(*self as i64) as u64 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u64 { unsafe { intrinsics::cttz64(*self as i64) as u64 } } - } -} diff --git a/src/libstd/num/uint-template/u8.rs b/src/libstd/num/uint-template/u8.rs deleted file mode 100644 index 5ac860c0359..00000000000 --- a/src/libstd/num/uint-template/u8.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `u8` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u8; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i8; - pub static bits: uint = 8; - - impl Primitive for u8 { - #[inline(always)] - fn bits() -> uint { 8 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u8 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u8 { unsafe { intrinsics::ctpop8(*self as i8) as u8 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u8 { unsafe { intrinsics::ctlz8(*self as i8) as u8 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u8 { unsafe { intrinsics::cttz8(*self as i8) as u8 } } - } -} diff --git a/src/libstd/num/uint-template/uint.rs b/src/libstd/num/uint-template/uint.rs deleted file mode 100644 index 763c305f221..00000000000 --- a/src/libstd/num/uint-template/uint.rs +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Operations and constants for `uint` - -pub use self::inst::{ - div_ceil, div_round, div_floor, iterate, - next_power_of_two -}; - -pub mod inst { - use iter; - use num::{Primitive, BitCount}; - use sys; - - pub type T = uint; - #[allow(non_camel_case_types)] - pub type T_SIGNED = int; - - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - pub static bits: uint = 32; - - #[cfg(target_arch = "x86_64")] - pub static bits: uint = 64; - - impl Primitive for uint { - #[cfg(target_word_size = "32")] - #[inline(always)] - fn bits() -> uint { 32 } - - #[cfg(target_word_size = "64")] - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - #[cfg(target_word_size = "32")] - #[inline(always)] - impl BitCount for uint { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> uint { (*self as i32).population_count() as uint } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> uint { (*self as i32).leading_zeros() as uint } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> uint { (*self as i32).trailing_zeros() as uint } - } - - #[cfg(target_word_size = "64")] - #[inline(always)] - impl BitCount for uint { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> uint { (*self as i64).population_count() as uint } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> uint { (*self as i64).leading_zeros() as uint } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> uint { (*self as i64).trailing_zeros() as uint } - } - - /// - /// Divide two numbers, return the result, rounded up. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The smallest integer `q` such that `x/y <= q`. - /// - pub fn div_ceil(x: uint, y: uint) -> uint { - let div = x / y; - if x % y == 0u { div } - else { div + 1u } - } - - /// - /// Divide two numbers, return the result, rounded to the closest integer. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The integer `q` closest to `x/y`. - /// - pub fn div_round(x: uint, y: uint) -> uint { - let div = x / y; - if x % y * 2u < y { div } - else { div + 1u } - } - - /// - /// Divide two numbers, return the result, rounded down. - /// - /// Note: This is the same function as `div`. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The smallest integer `q` such that `x/y <= q`. This - /// is either `x/y` or `x/y + 1`. - /// - pub fn div_floor(x: uint, y: uint) -> uint { return x / y; } - - /// - /// Iterate over the range [`lo`..`hi`), or stop when requested - /// - /// # Arguments - /// - /// * lo - The integer at which to start the loop (included) - /// * hi - The integer at which to stop the loop (excluded) - /// * it - A block to execute with each consecutive integer of the range. - /// Return `true` to continue, `false` to stop. - /// - /// # Return value - /// - /// `true` If execution proceeded correctly, `false` if it was interrupted, - /// that is if `it` returned `false` at any point. - /// - pub fn iterate(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool { - let mut i = lo; - while i < hi { - if (!it(i)) { return false; } - i += 1u; - } - return true; - } - - impl iter::Times for uint { - #[inline(always)] - /// - /// A convenience form for basic iteration. Given a uint `x`, - /// `for x.times { ... }` executes the given block x times. - /// - /// Equivalent to `for uint::range(0, x) |_| { ... }`. - /// - /// Not defined on all integer types to permit unambiguous - /// use with integer literals of inferred integer-type as - /// the self-value (eg. `for 100.times { ... }`). - /// - fn times(&self, it: &fn() -> bool) -> bool { - let mut i = *self; - while i > 0 { - if !it() { return false; } - i -= 1; - } - return true; - } - } - - /// Returns the smallest power of 2 greater than or equal to `n` - #[inline(always)] - pub fn next_power_of_two(n: uint) -> uint { - let halfbits: uint = sys::size_of::() * 4u; - let mut tmp: uint = n - 1u; - let mut shift: uint = 1u; - while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } - return tmp + 1u; - } - - #[test] - fn test_next_power_of_two() { - assert_eq!(next_power_of_two(0u), 0u); - assert_eq!(next_power_of_two(1u), 1u); - assert_eq!(next_power_of_two(2u), 2u); - assert_eq!(next_power_of_two(3u), 4u); - assert_eq!(next_power_of_two(4u), 4u); - assert_eq!(next_power_of_two(5u), 8u); - assert_eq!(next_power_of_two(6u), 8u); - assert_eq!(next_power_of_two(7u), 8u); - assert_eq!(next_power_of_two(8u), 8u); - assert_eq!(next_power_of_two(9u), 16u); - assert_eq!(next_power_of_two(10u), 16u); - assert_eq!(next_power_of_two(11u), 16u); - assert_eq!(next_power_of_two(12u), 16u); - assert_eq!(next_power_of_two(13u), 16u); - assert_eq!(next_power_of_two(14u), 16u); - assert_eq!(next_power_of_two(15u), 16u); - assert_eq!(next_power_of_two(16u), 16u); - assert_eq!(next_power_of_two(17u), 32u); - assert_eq!(next_power_of_two(18u), 32u); - assert_eq!(next_power_of_two(19u), 32u); - assert_eq!(next_power_of_two(20u), 32u); - assert_eq!(next_power_of_two(21u), 32u); - assert_eq!(next_power_of_two(22u), 32u); - assert_eq!(next_power_of_two(23u), 32u); - assert_eq!(next_power_of_two(24u), 32u); - assert_eq!(next_power_of_two(25u), 32u); - assert_eq!(next_power_of_two(26u), 32u); - assert_eq!(next_power_of_two(27u), 32u); - assert_eq!(next_power_of_two(28u), 32u); - assert_eq!(next_power_of_two(29u), 32u); - assert_eq!(next_power_of_two(30u), 32u); - assert_eq!(next_power_of_two(31u), 32u); - assert_eq!(next_power_of_two(32u), 32u); - assert_eq!(next_power_of_two(33u), 64u); - assert_eq!(next_power_of_two(34u), 64u); - assert_eq!(next_power_of_two(35u), 64u); - assert_eq!(next_power_of_two(36u), 64u); - assert_eq!(next_power_of_two(37u), 64u); - assert_eq!(next_power_of_two(38u), 64u); - assert_eq!(next_power_of_two(39u), 64u); - } - - #[test] - fn test_overflows() { - use uint; - assert!((uint::max_value > 0u)); - assert!((uint::min_value <= 0u)); - assert_eq!(uint::min_value + uint::max_value + 1u, 0u); - } - - #[test] - fn test_div() { - assert_eq!(div_floor(3u, 4u), 0u); - assert_eq!(div_ceil(3u, 4u), 1u); - assert_eq!(div_round(3u, 4u), 1u); - } - - #[test] - pub fn test_times() { - use iter::Times; - let ten = 10 as uint; - let mut accum = 0; - for ten.times { accum += 1; } - assert_eq!(accum, 10); - } -} diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs new file mode 100644 index 00000000000..bcb97ff5a07 --- /dev/null +++ b/src/libstd/num/uint.rs @@ -0,0 +1,195 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Operations and constants for `uint` + +use iter; +use sys; + +pub use self::generated::*; + +uint_module!(uint, int, ::int::bits) + +/// +/// Divide two numbers, return the result, rounded up. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The smallest integer `q` such that `x/y <= q`. +/// +pub fn div_ceil(x: uint, y: uint) -> uint { + let div = x / y; + if x % y == 0u { div } + else { div + 1u } +} + +/// +/// Divide two numbers, return the result, rounded to the closest integer. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The integer `q` closest to `x/y`. +/// +pub fn div_round(x: uint, y: uint) -> uint { + let div = x / y; + if x % y * 2u < y { div } + else { div + 1u } +} + +/// +/// Divide two numbers, return the result, rounded down. +/// +/// Note: This is the same function as `div`. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The smallest integer `q` such that `x/y <= q`. This +/// is either `x/y` or `x/y + 1`. +/// +pub fn div_floor(x: uint, y: uint) -> uint { return x / y; } + +/// +/// Iterate over the range [`lo`..`hi`), or stop when requested +/// +/// # Arguments +/// +/// * lo - The integer at which to start the loop (included) +/// * hi - The integer at which to stop the loop (excluded) +/// * it - A block to execute with each consecutive integer of the range. +/// Return `true` to continue, `false` to stop. +/// +/// # Return value +/// +/// `true` If execution proceeded correctly, `false` if it was interrupted, +/// that is if `it` returned `false` at any point. +/// +pub fn iterate(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool { + let mut i = lo; + while i < hi { + if (!it(i)) { return false; } + i += 1u; + } + return true; +} + +impl iter::Times for uint { + #[inline(always)] + /// + /// A convenience form for basic iteration. Given a uint `x`, + /// `for x.times { ... }` executes the given block x times. + /// + /// Equivalent to `for uint::range(0, x) |_| { ... }`. + /// + /// Not defined on all integer types to permit unambiguous + /// use with integer literals of inferred integer-type as + /// the self-value (eg. `for 100.times { ... }`). + /// + fn times(&self, it: &fn() -> bool) -> bool { + let mut i = *self; + while i > 0 { + if !it() { return false; } + i -= 1; + } + return true; + } +} + +/// Returns the smallest power of 2 greater than or equal to `n` +#[inline(always)] +pub fn next_power_of_two(n: uint) -> uint { + let halfbits: uint = sys::size_of::() * 4u; + let mut tmp: uint = n - 1u; + let mut shift: uint = 1u; + while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } + return tmp + 1u; +} + +#[test] +fn test_next_power_of_two() { + assert!((next_power_of_two(0u) == 0u)); + assert!((next_power_of_two(1u) == 1u)); + assert!((next_power_of_two(2u) == 2u)); + assert!((next_power_of_two(3u) == 4u)); + assert!((next_power_of_two(4u) == 4u)); + assert!((next_power_of_two(5u) == 8u)); + assert!((next_power_of_two(6u) == 8u)); + assert!((next_power_of_two(7u) == 8u)); + assert!((next_power_of_two(8u) == 8u)); + assert!((next_power_of_two(9u) == 16u)); + assert!((next_power_of_two(10u) == 16u)); + assert!((next_power_of_two(11u) == 16u)); + assert!((next_power_of_two(12u) == 16u)); + assert!((next_power_of_two(13u) == 16u)); + assert!((next_power_of_two(14u) == 16u)); + assert!((next_power_of_two(15u) == 16u)); + assert!((next_power_of_two(16u) == 16u)); + assert!((next_power_of_two(17u) == 32u)); + assert!((next_power_of_two(18u) == 32u)); + assert!((next_power_of_two(19u) == 32u)); + assert!((next_power_of_two(20u) == 32u)); + assert!((next_power_of_two(21u) == 32u)); + assert!((next_power_of_two(22u) == 32u)); + assert!((next_power_of_two(23u) == 32u)); + assert!((next_power_of_two(24u) == 32u)); + assert!((next_power_of_two(25u) == 32u)); + assert!((next_power_of_two(26u) == 32u)); + assert!((next_power_of_two(27u) == 32u)); + assert!((next_power_of_two(28u) == 32u)); + assert!((next_power_of_two(29u) == 32u)); + assert!((next_power_of_two(30u) == 32u)); + assert!((next_power_of_two(31u) == 32u)); + assert!((next_power_of_two(32u) == 32u)); + assert!((next_power_of_two(33u) == 64u)); + assert!((next_power_of_two(34u) == 64u)); + assert!((next_power_of_two(35u) == 64u)); + assert!((next_power_of_two(36u) == 64u)); + assert!((next_power_of_two(37u) == 64u)); + assert!((next_power_of_two(38u) == 64u)); + assert!((next_power_of_two(39u) == 64u)); +} + +#[test] +fn test_overflows() { + use uint; + assert!((uint::max_value > 0u)); + assert!((uint::min_value <= 0u)); + assert!((uint::min_value + uint::max_value + 1u == 0u)); +} + +#[test] +fn test_div() { + assert!((div_floor(3u, 4u) == 0u)); + assert!((div_ceil(3u, 4u) == 1u)); + assert!((div_round(3u, 4u) == 1u)); +} + +#[test] +pub fn test_times() { + use iter::Times; + let ten = 10 as uint; + let mut accum = 0; + for ten.times { accum += 1; } + assert!((accum == 10)); +} diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs new file mode 100644 index 00000000000..3448314c436 --- /dev/null +++ b/src/libstd/num/uint_macros.rs @@ -0,0 +1,667 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// FIXME(#4375): this shouldn't have to be a nested module named 'generated' + +#[macro_escape]; + +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 prelude::*; + +pub use cmp::{min, max}; + +pub static bits : uint = $bits; +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; + +#[inline(always)] +pub fn add(x: $T, y: $T) -> $T { x + y } +#[inline(always)] +pub fn sub(x: $T, y: $T) -> $T { x - y } +#[inline(always)] +pub fn mul(x: $T, y: $T) -> $T { x * y } +#[inline(always)] +pub fn div(x: $T, y: $T) -> $T { x / y } +#[inline(always)] +pub fn rem(x: $T, y: $T) -> $T { x % y } + +#[inline(always)] +pub fn lt(x: $T, y: $T) -> bool { x < y } +#[inline(always)] +pub fn le(x: $T, y: $T) -> bool { x <= y } +#[inline(always)] +pub fn eq(x: $T, y: $T) -> bool { x == y } +#[inline(always)] +pub fn ne(x: $T, y: $T) -> bool { x != y } +#[inline(always)] +pub fn ge(x: $T, y: $T) -> bool { x >= y } +#[inline(always)] +pub fn gt(x: $T, y: $T) -> bool { x > y } + +#[inline(always)] +/// +/// Iterate over the range [`start`,`start`+`step`..`stop`) +/// +pub fn range_step(start: $T, stop: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool { + let mut i = start; + if step == 0 { + fail!("range_step called with step == 0"); + } + if step >= 0 { + while i < stop { + if !it(i) { return false; } + // avoiding overflow. break if i + step > max_value + if i > max_value - (step as $T) { return true; } + i += step as $T; + } + } else { + while i > stop { + if !it(i) { return false; } + // avoiding underflow. break if i + step < min_value + if i < min_value + ((-step) as $T) { return true; } + i -= -step as $T; + } + } + return true; +} + +#[inline(always)] +/// Iterate over the range [`lo`..`hi`) +pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool { + range_step(lo, hi, 1 as $T_SIGNED, it) +} + +#[inline(always)] +/// Iterate over the range [`hi`..`lo`) +pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool { + range_step(hi, lo, -1 as $T_SIGNED, it) +} + +/// Computes the bitwise complement +#[inline(always)] +pub fn compl(i: $T) -> $T { + max_value ^ i +} + +impl Num for $T {} + +#[cfg(not(test))] +impl Ord for $T { + #[inline(always)] + fn lt(&self, other: &$T) -> bool { (*self) < (*other) } + #[inline(always)] + fn le(&self, other: &$T) -> bool { (*self) <= (*other) } + #[inline(always)] + fn ge(&self, other: &$T) -> bool { (*self) >= (*other) } + #[inline(always)] + fn gt(&self, other: &$T) -> bool { (*self) > (*other) } +} + +#[cfg(not(test))] +impl Eq for $T { + #[inline(always)] + fn eq(&self, other: &$T) -> bool { return (*self) == (*other); } + #[inline(always)] + fn ne(&self, other: &$T) -> bool { return (*self) != (*other); } +} + +impl Orderable for $T { + #[inline(always)] + fn min(&self, other: &$T) -> $T { + if *self < *other { *self } else { *other } + } + + #[inline(always)] + fn max(&self, other: &$T) -> $T { + if *self > *other { *self } else { *other } + } + + /// Returns the number constrained within the range `mn <= self <= mx`. + #[inline(always)] + fn clamp(&self, mn: &$T, mx: &$T) -> $T { + cond!( + (*self > *mx) { *mx } + (*self < *mn) { *mn } + _ { *self } + ) + } +} + +impl Zero for $T { + #[inline(always)] + fn zero() -> $T { 0 } + + #[inline(always)] + fn is_zero(&self) -> bool { *self == 0 } +} + +impl One for $T { + #[inline(always)] + fn one() -> $T { 1 } +} + +#[cfg(not(test))] +impl Add<$T,$T> for $T { + #[inline(always)] + fn add(&self, other: &$T) -> $T { *self + *other } +} + +#[cfg(not(test))] +impl Sub<$T,$T> for $T { + #[inline(always)] + fn sub(&self, other: &$T) -> $T { *self - *other } +} + +#[cfg(not(test))] +impl Mul<$T,$T> for $T { + #[inline(always)] + fn mul(&self, other: &$T) -> $T { *self * *other } +} + +#[cfg(not(test))] +impl Div<$T,$T> for $T { + #[inline(always)] + fn div(&self, other: &$T) -> $T { *self / *other } +} + +#[cfg(not(test))] +impl Rem<$T,$T> for $T { + #[inline(always)] + fn rem(&self, other: &$T) -> $T { *self % *other } +} + +#[cfg(not(test))] +impl Neg<$T> for $T { + #[inline(always)] + fn neg(&self) -> $T { -*self } +} + +impl Unsigned for $T {} + +impl Integer for $T { + /// Calculates `div` (`\`) and `rem` (`%`) simultaneously + #[inline(always)] + fn div_rem(&self, other: &$T) -> ($T,$T) { + (*self / *other, *self % *other) + } + + /// Unsigned integer division. Returns the same result as `div` (`/`). + #[inline(always)] + fn div_floor(&self, other: &$T) -> $T { *self / *other } + + /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). + #[inline(always)] + fn mod_floor(&self, other: &$T) -> $T { *self / *other } + + /// Calculates `div_floor` and `modulo_floor` simultaneously + #[inline(always)] + fn div_mod_floor(&self, other: &$T) -> ($T,$T) { + (*self / *other, *self % *other) + } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other` + #[inline(always)] + fn gcd(&self, other: &$T) -> $T { + // Use Euclid's algorithm + let mut m = *self, n = *other; + while m != 0 { + let temp = m; + m = n % temp; + n = temp; + } + n + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other` + #[inline(always)] + fn lcm(&self, other: &$T) -> $T { + (*self * *other) / self.gcd(other) + } + + /// Returns `true` if the number can be divided by `other` without leaving a remainder + #[inline(always)] + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + + /// Returns `true` if the number is divisible by `2` + #[inline(always)] + fn is_even(&self) -> bool { self.is_multiple_of(&2) } + + /// Returns `true` if the number is not divisible by `2` + #[inline(always)] + fn is_odd(&self) -> bool { !self.is_even() } +} + +impl Bitwise for $T {} + +#[cfg(not(test))] +impl BitOr<$T,$T> for $T { + #[inline(always)] + fn bitor(&self, other: &$T) -> $T { *self | *other } +} + +#[cfg(not(test))] +impl BitAnd<$T,$T> for $T { + #[inline(always)] + fn bitand(&self, other: &$T) -> $T { *self & *other } +} + +#[cfg(not(test))] +impl BitXor<$T,$T> for $T { + #[inline(always)] + fn bitxor(&self, other: &$T) -> $T { *self ^ *other } +} + +#[cfg(not(test))] +impl Shl<$T,$T> for $T { + #[inline(always)] + fn shl(&self, other: &$T) -> $T { *self << *other } +} + +#[cfg(not(test))] +impl Shr<$T,$T> for $T { + #[inline(always)] + fn shr(&self, other: &$T) -> $T { *self >> *other } +} + +#[cfg(not(test))] +impl Not<$T> for $T { + #[inline(always)] + fn not(&self) -> $T { !*self } +} + +impl Bounded for $T { + #[inline(always)] + fn min_value() -> $T { min_value } + + #[inline(always)] + fn max_value() -> $T { max_value } +} + +impl Int for $T {} + +// String conversion functions and impl str -> num + +/// Parse a string as a number in base 10. +#[inline(always)] +pub fn from_str(s: &str) -> Option<$T> { + strconv::from_str_common(s, 10u, false, false, false, + strconv::ExpNone, false, false) +} + +/// Parse a string as a number in the given base. +#[inline(always)] +pub fn from_str_radix(s: &str, radix: uint) -> Option<$T> { + strconv::from_str_common(s, radix, false, false, false, + strconv::ExpNone, false, false) +} + +/// Parse a byte slice as a number in the given base. +#[inline(always)] +pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> { + strconv::from_str_bytes_common(buf, radix, false, false, false, + strconv::ExpNone, false, false) +} + +impl FromStr for $T { + #[inline(always)] + fn from_str(s: &str) -> Option<$T> { + from_str(s) + } +} + +impl FromStrRadix for $T { + #[inline(always)] + fn from_str_radix(s: &str, radix: uint) -> Option<$T> { + from_str_radix(s, radix) + } +} + +// String conversion functions and impl num -> str + +/// Convert to a string as a byte slice in a given base. +#[inline(always)] +pub fn to_str_bytes(n: $T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { + let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, + strconv::SignNeg, strconv::DigAll); + f(buf) +} + +/// Convert to a string in base 10. +#[inline(always)] +pub fn to_str(num: $T) -> ~str { + let (buf, _) = strconv::to_str_common(&num, 10u, false, + strconv::SignNeg, strconv::DigAll); + buf +} + +/// Convert to a string in a given base. +#[inline(always)] +pub fn to_str_radix(num: $T, radix: uint) -> ~str { + let (buf, _) = strconv::to_str_common(&num, radix, false, + strconv::SignNeg, strconv::DigAll); + buf +} + +impl ToStr for $T { + #[inline(always)] + fn to_str(&self) -> ~str { + to_str(*self) + } +} + +impl ToStrRadix for $T { + #[inline(always)] + fn to_str_radix(&self, radix: uint) -> ~str { + to_str_radix(*self, radix) + } +} + +impl Primitive for $T { + #[inline(always)] + fn bits() -> uint { bits } + + #[inline(always)] + fn bytes() -> uint { bits / 8 } +} + +impl BitCount for $T { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> $T { + (*self as $T_SIGNED).population_count() as $T + } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> $T { + (*self as $T_SIGNED).leading_zeros() as $T + } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> $T { + (*self as $T_SIGNED).trailing_zeros() as $T + } +} + +#[cfg(test)] +mod tests { + use super::*; + use prelude::*; + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_orderable() { + assert_eq!((1 as $T).min(&(2 as $T)), 1 as $T); + assert_eq!((2 as $T).min(&(1 as $T)), 1 as $T); + assert_eq!((1 as $T).max(&(2 as $T)), 2 as $T); + assert_eq!((2 as $T).max(&(1 as $T)), 2 as $T); + assert_eq!((1 as $T).clamp(&(2 as $T), &(4 as $T)), 2 as $T); + assert_eq!((8 as $T).clamp(&(2 as $T), &(4 as $T)), 4 as $T); + assert_eq!((3 as $T).clamp(&(2 as $T), &(4 as $T)), 3 as $T); + } + + #[test] + fn test_gcd() { + assert_eq!((10 as $T).gcd(&2), 2 as $T); + assert_eq!((10 as $T).gcd(&3), 1 as $T); + assert_eq!((0 as $T).gcd(&3), 3 as $T); + assert_eq!((3 as $T).gcd(&3), 3 as $T); + assert_eq!((56 as $T).gcd(&42), 14 as $T); + } + + #[test] + fn test_lcm() { + assert_eq!((1 as $T).lcm(&0), 0 as $T); + assert_eq!((0 as $T).lcm(&1), 0 as $T); + assert_eq!((1 as $T).lcm(&1), 1 as $T); + assert_eq!((8 as $T).lcm(&9), 72 as $T); + assert_eq!((11 as $T).lcm(&5), 55 as $T); + assert_eq!((99 as $T).lcm(&17), 1683 as $T); + } + + #[test] + fn test_multiple_of() { + assert!((6 as $T).is_multiple_of(&(6 as $T))); + assert!((6 as $T).is_multiple_of(&(3 as $T))); + assert!((6 as $T).is_multiple_of(&(1 as $T))); + } + + #[test] + fn test_even() { + assert_eq!((0 as $T).is_even(), true); + assert_eq!((1 as $T).is_even(), false); + assert_eq!((2 as $T).is_even(), true); + assert_eq!((3 as $T).is_even(), false); + assert_eq!((4 as $T).is_even(), true); + } + + #[test] + fn test_odd() { + assert_eq!((0 as $T).is_odd(), false); + assert_eq!((1 as $T).is_odd(), true); + assert_eq!((2 as $T).is_odd(), false); + assert_eq!((3 as $T).is_odd(), true); + assert_eq!((4 as $T).is_odd(), false); + } + + #[test] + fn test_bitwise() { + assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(&(0b1010 as $T))); + assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(&(0b1010 as $T))); + assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert_eq!(0b1110 as $T, (0b0111 as $T).shl(&(1 as $T))); + assert_eq!(0b0111 as $T, (0b1110 as $T).shr(&(1 as $T))); + assert_eq!(max_value - (0b1011 as $T), (0b1011 as $T).not()); + } + + #[test] + fn test_bitcount() { + assert_eq!((0b010101 as $T).population_count(), 3); + } + + #[test] + fn test_primitive() { + assert_eq!(Primitive::bits::<$T>(), sys::size_of::<$T>() * 8); + assert_eq!(Primitive::bytes::<$T>(), sys::size_of::<$T>()); + } + + #[test] + pub fn test_to_str() { + assert_eq!(to_str_radix(0 as $T, 10u), ~"0"); + assert_eq!(to_str_radix(1 as $T, 10u), ~"1"); + assert_eq!(to_str_radix(2 as $T, 10u), ~"2"); + assert_eq!(to_str_radix(11 as $T, 10u), ~"11"); + assert_eq!(to_str_radix(11 as $T, 16u), ~"b"); + assert_eq!(to_str_radix(255 as $T, 16u), ~"ff"); + assert_eq!(to_str_radix(0xff as $T, 10u), ~"255"); + } + + #[test] + pub fn test_from_str() { + assert_eq!(from_str(~"0"), Some(0u as $T)); + assert_eq!(from_str(~"3"), Some(3u as $T)); + assert_eq!(from_str(~"10"), Some(10u as $T)); + assert_eq!(u32::from_str(~"123456789"), Some(123456789 as u32)); + assert_eq!(from_str(~"00100"), Some(100u as $T)); + + assert!(from_str(~"").is_none()); + assert!(from_str(~" ").is_none()); + assert!(from_str(~"x").is_none()); + } + + #[test] + pub fn test_parse_bytes() { + use str::to_bytes; + assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123u as $T)); + assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9u as $T)); + assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83u as $T)); + assert_eq!(u16::parse_bytes(to_bytes(~"123"), 16u), Some(291u as u16)); + assert_eq!(u16::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535u as u16)); + assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35u as $T)); + + assert!(parse_bytes(to_bytes(~"Z"), 10u).is_none()); + assert!(parse_bytes(to_bytes(~"_"), 2u).is_none()); + } + + #[test] + fn test_uint_to_str_overflow() { + let mut u8_val: u8 = 255_u8; + assert_eq!(u8::to_str(u8_val), ~"255"); + + u8_val += 1 as u8; + assert_eq!(u8::to_str(u8_val), ~"0"); + + let mut u16_val: u16 = 65_535_u16; + assert_eq!(u16::to_str(u16_val), ~"65535"); + + u16_val += 1 as u16; + assert_eq!(u16::to_str(u16_val), ~"0"); + + let mut u32_val: u32 = 4_294_967_295_u32; + assert_eq!(u32::to_str(u32_val), ~"4294967295"); + + u32_val += 1 as u32; + assert_eq!(u32::to_str(u32_val), ~"0"); + + let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; + assert_eq!(u64::to_str(u64_val), ~"18446744073709551615"); + + u64_val += 1 as u64; + assert_eq!(u64::to_str(u64_val), ~"0"); + } + + #[test] + fn test_uint_from_str_overflow() { + let mut u8_val: u8 = 255_u8; + assert_eq!(u8::from_str(~"255"), Some(u8_val)); + assert!(u8::from_str(~"256").is_none()); + + u8_val += 1 as u8; + assert_eq!(u8::from_str(~"0"), Some(u8_val)); + assert!(u8::from_str(~"-1").is_none()); + + let mut u16_val: u16 = 65_535_u16; + assert_eq!(u16::from_str(~"65535"), Some(u16_val)); + assert!(u16::from_str(~"65536").is_none()); + + u16_val += 1 as u16; + assert_eq!(u16::from_str(~"0"), Some(u16_val)); + assert!(u16::from_str(~"-1").is_none()); + + let mut u32_val: u32 = 4_294_967_295_u32; + assert_eq!(u32::from_str(~"4294967295"), Some(u32_val)); + assert!(u32::from_str(~"4294967296").is_none()); + + u32_val += 1 as u32; + assert_eq!(u32::from_str(~"0"), Some(u32_val)); + assert!(u32::from_str(~"-1").is_none()); + + let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; + assert_eq!(u64::from_str(~"18446744073709551615"), Some(u64_val)); + assert!(u64::from_str(~"18446744073709551616").is_none()); + + u64_val += 1 as u64; + assert_eq!(u64::from_str(~"0"), Some(u64_val)); + assert!(u64::from_str(~"-1").is_none()); + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + pub fn to_str_radix1() { + uint::to_str_radix(100u, 1u); + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + pub fn to_str_radix37() { + uint::to_str_radix(100u, 37u); + } + + #[test] + pub fn test_ranges() { + let mut l = ~[]; + + for range(0,3) |i| { + l.push(i); + } + for range_rev(13,10) |i| { + l.push(i); + } + for range_step(20,26,2) |i| { + l.push(i); + } + for range_step(36,30,-2) |i| { + l.push(i); + } + for range_step(max_value - 2, max_value, 2) |i| { + l.push(i); + } + for range_step(max_value - 3, max_value, 2) |i| { + l.push(i); + } + for range_step(min_value + 2, min_value, -2) |i| { + l.push(i); + } + for range_step(min_value + 3, min_value, -2) |i| { + l.push(i); + } + + assert_eq!(l, ~[0,1,2, + 13,12,11, + 20,22,24, + 36,34,32, + max_value-2, + max_value-3,max_value-1, + min_value+2, + min_value+3,min_value+1]); + + // None of the `fail`s should execute. + for range(0,0) |_i| { + fail!("unreachable"); + } + for range_rev(0,0) |_i| { + fail!("unreachable"); + } + for range_step(10,0,1) |_i| { + fail!("unreachable"); + } + for range_step(0,1,-10) |_i| { + fail!("unreachable"); + } + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + fn test_range_step_zero_step_up() { + for range_step(0,10,0) |_i| {} + } + #[test] + #[should_fail] + #[ignore(cfg(windows))] + fn test_range_step_zero_step_down() { + for range_step(0,-10,0) |_i| {} + } +} + +})) -- cgit 1.4.1-3-g733a5