From c124be549f274365dd194c3d30ed3d4be772897e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Tue, 16 Feb 2016 00:19:23 +0100 Subject: [PATCH 01/31] Move traits to separate crate --- Cargo.toml | 3 + integer/Cargo.toml | 6 + integer/src/lib.rs | 630 +++++++++ src/bigint.rs | 7 +- src/lib.rs | 4 +- src/traits.rs | 2552 ---------------------------------- traits/Cargo.toml | 6 + traits/src/bounds.rs | 69 + traits/src/cast.rs | 434 ++++++ traits/src/float.rs | 1126 +++++++++++++++ traits/src/identities.rs | 95 ++ traits/src/int.rs | 360 +++++ traits/src/lib.rs | 215 +++ traits/src/ops/checked.rs | 91 ++ traits/src/ops/mod.rs | 2 + traits/src/ops/saturating.rs | 26 + traits/src/sign.rs | 126 ++ 17 files changed, 3195 insertions(+), 2557 deletions(-) create mode 100644 integer/Cargo.toml create mode 100644 integer/src/lib.rs delete mode 100644 src/traits.rs create mode 100644 traits/Cargo.toml create mode 100644 traits/src/bounds.rs create mode 100644 traits/src/cast.rs create mode 100644 traits/src/float.rs create mode 100644 traits/src/identities.rs create mode 100644 traits/src/int.rs create mode 100644 traits/src/lib.rs create mode 100644 traits/src/ops/checked.rs create mode 100644 traits/src/ops/mod.rs create mode 100644 traits/src/ops/saturating.rs create mode 100644 traits/src/sign.rs diff --git a/Cargo.toml b/Cargo.toml index fdacaef..7eb975f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,9 @@ rand = { version = "0.3.8", optional = true } rustc-serialize = { version = "0.3.13", optional = true } serde = { version = "^0.7.0", optional = true } +[dependencies.num-traits] +path = "./traits" + [dev-dependencies] # Some tests of non-rand functionality still use rand because the tests # themselves are randomized. diff --git a/integer/Cargo.toml b/integer/Cargo.toml new file mode 100644 index 0000000..651a69d --- /dev/null +++ b/integer/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "integer" +version = "0.1.0" +authors = ["Łukasz Jan Niemier "] + +[dependencies] diff --git a/integer/src/lib.rs b/integer/src/lib.rs new file mode 100644 index 0000000..eca274f --- /dev/null +++ b/integer/src/lib.rs @@ -0,0 +1,630 @@ +// Copyright 2013-2014 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. + +//! Integer trait and functions. + +use {Num, Signed}; + +pub trait Integer + : Sized + + Num + + PartialOrd + Ord + Eq +{ + /// Floored integer division. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// 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); + /// ~~~ + fn div_floor(&self, other: &Self) -> Self; + + /// Floored integer modulo, satisfying: + /// + /// ~~~ + /// # use num::Integer; + /// # let n = 1; let d = 1; + /// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n) + /// ~~~ + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// 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); + /// ~~~ + fn mod_floor(&self, other: &Self) -> Self; + + /// Greatest Common Divisor (GCD). + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(6.gcd(&8), 2); + /// assert_eq!(7.gcd(&3), 1); + /// ~~~ + fn gcd(&self, other: &Self) -> Self; + + /// Lowest Common Multiple (LCM). + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(7.lcm(&3), 21); + /// assert_eq!(2.lcm(&4), 4); + /// ~~~ + fn lcm(&self, other: &Self) -> Self; + + /// Deprecated, use `is_multiple_of` instead. + fn divides(&self, other: &Self) -> bool; + + /// Returns `true` if `other` is a multiple of `self`. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(9.is_multiple_of(&3), true); + /// assert_eq!(3.is_multiple_of(&9), false); + /// ~~~ + fn is_multiple_of(&self, other: &Self) -> bool; + + /// Returns `true` if the number is even. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(3.is_even(), false); + /// assert_eq!(4.is_even(), true); + /// ~~~ + fn is_even(&self) -> bool; + + /// Returns `true` if the number is odd. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(3.is_odd(), true); + /// assert_eq!(4.is_odd(), false); + /// ~~~ + fn is_odd(&self) -> bool; + + /// Simultaneous truncated integer division and modulus. + /// Returns `(quotient, remainder)`. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(( 8).div_rem( &3), ( 2, 2)); + /// assert_eq!(( 8).div_rem(&-3), (-2, 2)); + /// assert_eq!((-8).div_rem( &3), (-2, -2)); + /// assert_eq!((-8).div_rem(&-3), ( 2, -2)); + /// + /// assert_eq!(( 1).div_rem( &2), ( 0, 1)); + /// assert_eq!(( 1).div_rem(&-2), ( 0, 1)); + /// assert_eq!((-1).div_rem( &2), ( 0, -1)); + /// assert_eq!((-1).div_rem(&-2), ( 0, -1)); + /// ~~~ + #[inline] + fn div_rem(&self, other: &Self) -> (Self, Self); + + /// Simultaneous floored integer division and modulus. + /// Returns `(quotient, remainder)`. + /// + /// # Examples + /// + /// ~~~ + /// # use num::Integer; + /// assert_eq!(( 8).div_mod_floor( &3), ( 2, 2)); + /// assert_eq!(( 8).div_mod_floor(&-3), (-3, -1)); + /// assert_eq!((-8).div_mod_floor( &3), (-3, 1)); + /// assert_eq!((-8).div_mod_floor(&-3), ( 2, -2)); + /// + /// assert_eq!(( 1).div_mod_floor( &2), ( 0, 1)); + /// assert_eq!(( 1).div_mod_floor(&-2), (-1, -1)); + /// assert_eq!((-1).div_mod_floor( &2), (-1, 1)); + /// assert_eq!((-1).div_mod_floor(&-2), ( 0, -1)); + /// ~~~ + fn div_mod_floor(&self, other: &Self) -> (Self, Self) { + (self.div_floor(other), self.mod_floor(other)) + } +} + +/// Simultaneous integer division and modulus +#[inline] pub fn div_rem(x: T, y: T) -> (T, T) { x.div_rem(&y) } +/// Floored integer division +#[inline] pub fn div_floor(x: T, y: T) -> T { x.div_floor(&y) } +/// Floored integer modulus +#[inline] pub fn mod_floor(x: T, y: T) -> T { x.mod_floor(&y) } +/// Simultaneous floored integer division and modulus +#[inline] pub fn div_mod_floor(x: T, y: T) -> (T, T) { x.div_mod_floor(&y) } + +/// Calculates the Greatest Common Divisor (GCD) of the number and `other`. The +/// result is always positive. +#[inline(always)] pub fn gcd(x: T, y: T) -> T { x.gcd(&y) } +/// Calculates the Lowest Common Multiple (LCM) of the number and `other`. +#[inline(always)] pub fn lcm(x: T, y: T) -> T { x.lcm(&y) } + +macro_rules! impl_integer_for_isize { + ($T:ty, $test_mod:ident) => ( + impl Integer for $T { + /// Floored integer division + #[inline] + 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, + } + } + + /// Floored integer modulo + #[inline] + 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] + 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 the Greatest Common Divisor (GCD) of the number and + /// `other`. The result is always positive. + #[inline] + fn gcd(&self, other: &$T) -> $T { + // Use Stein's algorithm + let mut m = *self; + let mut n = *other; + if m == 0 || n == 0 { return (m | n).abs() } + + // find common factors of 2 + let shift = (m | n).trailing_zeros(); + + // The algorithm needs positive numbers, but the minimum value + // can't be represented as a positive one. + // It's also a power of two, so the gcd can be + // calculated by bitshifting in that case + + // Assuming two's complement, the number created by the shift + // is positive for all numbers except gcd = abs(min value) + // The call to .abs() causes a panic in debug mode + if m == <$T>::min_value() || n == <$T>::min_value() { + return (1 << shift).abs() + } + + // guaranteed to be positive now, rest like unsigned algorithm + m = m.abs(); + n = n.abs(); + + // divide n and m by 2 until odd + // m inside loop + n >>= n.trailing_zeros(); + + while m != 0 { + m >>= m.trailing_zeros(); + if n > m { ::std::mem::swap(&mut n, &mut m) } + m -= n; + } + + n << shift + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and + /// `other`. + #[inline] + fn lcm(&self, other: &$T) -> $T { + // should not have to recalculate abs + ((*self * *other) / self.gcd(other)).abs() + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + + /// Returns `true` if the number is divisible by `2` + #[inline] + fn is_even(&self) -> bool { (*self) & 1 == 0 } + + /// Returns `true` if the number is not divisible by `2` + #[inline] + fn is_odd(&self) -> bool { !self.is_even() } + + /// Simultaneous truncated integer division and modulus. + #[inline] + fn div_rem(&self, other: &$T) -> ($T, $T) { + (*self / *other, *self % *other) + } + } + + #[cfg(test)] + mod $test_mod { + use Integer; + + /// 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_gcd_cmp_with_euclidean() { + fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { + while m != 0 { + ::std::mem::swap(&mut m, &mut n); + m %= n; + } + + n.abs() + } + + // gcd(-128, b) = 128 is not representable as positive value + // for i8 + for i in -127..127 { + for j in -127..127 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + } + + // last value + // FIXME: Use inclusive ranges for above loop when implemented + let i = 127; + for j in -127..127 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + assert_eq!(127.gcd(&127), 127); + } + + #[test] + fn test_gcd_min_val() { + let min = <$T>::min_value(); + let max = <$T>::max_value(); + let max_pow2 = max / 2 + 1; + assert_eq!(min.gcd(&max), 1 as $T); + assert_eq!(max.gcd(&min), 1 as $T); + assert_eq!(min.gcd(&max_pow2), max_pow2); + assert_eq!(max_pow2.gcd(&min), max_pow2); + assert_eq!(min.gcd(&42), 2 as $T); + assert_eq!((42 as $T).gcd(&min), 2 as $T); + } + + #[test] + #[should_panic] + fn test_gcd_min_val_min_val() { + let min = <$T>::min_value(); + assert!(min.gcd(&min) >= 0); + } + + #[test] + #[should_panic] + fn test_gcd_min_val_0() { + let min = <$T>::min_value(); + assert!(min.gcd(&0) >= 0); + } + + #[test] + #[should_panic] + fn test_gcd_0_min_val() { + let min = <$T>::min_value(); + assert!((0 as $T).gcd(&min) >= 0); + } + + #[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_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); + } + } + ) +} + +impl_integer_for_isize!(i8, test_integer_i8); +impl_integer_for_isize!(i16, test_integer_i16); +impl_integer_for_isize!(i32, test_integer_i32); +impl_integer_for_isize!(i64, test_integer_i64); +impl_integer_for_isize!(isize, test_integer_isize); + +macro_rules! impl_integer_for_usize { + ($T:ty, $test_mod:ident) => ( + impl Integer for $T { + /// Unsigned integer division. Returns the same result as `div` (`/`). + #[inline] + fn div_floor(&self, other: &$T) -> $T { *self / *other } + + /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). + #[inline] + fn mod_floor(&self, other: &$T) -> $T { *self % *other } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other` + #[inline] + fn gcd(&self, other: &$T) -> $T { + // Use Stein's algorithm + let mut m = *self; + let mut n = *other; + if m == 0 || n == 0 { return m | n } + + // find common factors of 2 + let shift = (m | n).trailing_zeros(); + + // divide n and m by 2 until odd + // m inside loop + n >>= n.trailing_zeros(); + + while m != 0 { + m >>= m.trailing_zeros(); + if n > m { ::std::mem::swap(&mut n, &mut m) } + m -= n; + } + + n << shift + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. + #[inline] + fn lcm(&self, other: &$T) -> $T { + (*self * *other) / self.gcd(other) + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + + /// Returns `true` if the number is divisible by `2`. + #[inline] + fn is_even(&self) -> bool { (*self) & 1 == 0 } + + /// Returns `true` if the number is not divisible by `2`. + #[inline] + fn is_odd(&self) -> bool { !(*self).is_even() } + + /// Simultaneous truncated integer division and modulus. + #[inline] + fn div_rem(&self, other: &$T) -> ($T, $T) { + (*self / *other, *self % *other) + } + } + + #[cfg(test)] + mod $test_mod { + use Integer; + + #[test] + fn test_div_mod_floor() { + assert_eq!((10 as $T).div_floor(&(3 as $T)), 3 as $T); + assert_eq!((10 as $T).mod_floor(&(3 as $T)), 1 as $T); + assert_eq!((10 as $T).div_mod_floor(&(3 as $T)), (3 as $T, 1 as $T)); + assert_eq!((5 as $T).div_floor(&(5 as $T)), 1 as $T); + assert_eq!((5 as $T).mod_floor(&(5 as $T)), 0 as $T); + assert_eq!((5 as $T).div_mod_floor(&(5 as $T)), (1 as $T, 0 as $T)); + assert_eq!((3 as $T).div_floor(&(7 as $T)), 0 as $T); + assert_eq!((3 as $T).mod_floor(&(7 as $T)), 3 as $T); + assert_eq!((3 as $T).div_mod_floor(&(7 as $T)), (0 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_gcd_cmp_with_euclidean() { + fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { + while m != 0 { + ::std::mem::swap(&mut m, &mut n); + m %= n; + } + n + } + + for i in 0..255 { + for j in 0..255 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + } + + // last value + // FIXME: Use inclusive ranges for above loop when implemented + let i = 255; + for j in 0..255 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + assert_eq!(255.gcd(&255), 255); + } + + #[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!((15 as $T).lcm(&17), 255 as $T); + } + + #[test] + fn test_is_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); + } + } + ) +} + +impl_integer_for_usize!(u8, test_integer_u8); +impl_integer_for_usize!(u16, test_integer_u16); +impl_integer_for_usize!(u32, test_integer_u32); +impl_integer_for_usize!(u64, test_integer_u64); +impl_integer_for_usize!(usize, test_integer_usize); diff --git a/src/bigint.rs b/src/bigint.rs index ede5e78..a98752d 100644 --- a/src/bigint.rs +++ b/src/bigint.rs @@ -88,8 +88,7 @@ use serde; #[cfg(any(feature = "rand", test))] use rand::Rng; -use traits::{ToPrimitive, FromPrimitive}; -use traits::Float; +use traits::{ToPrimitive, FromPrimitive, Float}; use {Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, Signed, Zero, One}; use self::Sign::{Minus, NoSign, Plus}; @@ -364,7 +363,7 @@ fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint { } impl Num for BigUint { - type FromStrRadixErr = ParseBigIntError; + type Error = ParseBigIntError; /// Creates and initializes a `BigUint`. fn from_str_radix(s: &str, radix: u32) -> Result { @@ -1946,7 +1945,7 @@ impl FromStr for BigInt { } impl Num for BigInt { - type FromStrRadixErr = ParseBigIntError; + type Error = ParseBigIntError; /// Creates and initializes a BigInt. #[inline] diff --git a/src/lib.rs b/src/lib.rs index c9a3099..48ef305 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,6 +57,8 @@ html_root_url = "http://rust-num.github.io/num/", html_playground_url = "http://play.rust-lang.org/")] +extern crate num_traits; + #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; @@ -92,7 +94,7 @@ pub mod bigint; pub mod complex; pub mod integer; pub mod iter; -pub mod traits; +pub mod traits { pub use num_traits::*; } #[cfg(feature = "rational")] pub mod rational; diff --git a/src/traits.rs b/src/traits.rs deleted file mode 100644 index a4205d7..0000000 --- a/src/traits.rs +++ /dev/null @@ -1,2552 +0,0 @@ -// Copyright 2013-2014 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. - -//! Numeric traits for generic mathematics - -use std::ops::{Add, Sub, Mul, Div, Rem, Neg}; -use std::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; -use std::{usize, u8, u16, u32, u64}; -use std::{isize, i8, i16, i32, i64}; -use std::{f32, f64}; -use std::mem::{self, size_of}; -use std::num::FpCategory; - -/// The base trait for numeric types -pub trait Num: PartialEq + Zero + One - + Add + Sub - + Mul + Div + Rem -{ - /// Parse error for `from_str_radix` - type FromStrRadixErr; - - /// Convert from a string and radix <= 36. - fn from_str_radix(str: &str, radix: u32) -> Result; -} - -macro_rules! int_trait_impl { - ($name:ident for $($t:ty)*) => ($( - impl $name for $t { - type FromStrRadixErr = ::std::num::ParseIntError; - fn from_str_radix(s: &str, radix: u32) - -> Result - { - <$t>::from_str_radix(s, radix) - } - } - )*) -} - -// FIXME: std::num::ParseFloatError is stable in 1.0, but opaque to us, -// so there's not really any way for us to reuse it. -#[derive(Debug)] -pub struct ParseFloatError { pub kind: FloatErrorKind } -#[derive(Debug)] -pub enum FloatErrorKind { Empty, Invalid } - -// FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck -// with this implementation ourselves until we want to make a breaking change. -// (would have to drop it from `Num` though) -macro_rules! float_trait_impl { - ($name:ident for $($t:ty)*) => ($( - impl $name for $t { - type FromStrRadixErr = ParseFloatError; - fn from_str_radix(src: &str, radix: u32) - -> Result - { - use self::FloatErrorKind::*; - use self::ParseFloatError as PFE; - - // Special values - match src { - "inf" => return Ok(Float::infinity()), - "-inf" => return Ok(Float::neg_infinity()), - "NaN" => return Ok(Float::nan()), - _ => {}, - } - - fn slice_shift_char(src: &str) -> Option<(char, &str)> { - src.chars().nth(0).map(|ch| (ch, &src[1..])) - } - - let (is_positive, src) = match slice_shift_char(src) { - None => return Err(PFE { kind: Empty }), - Some(('-', "")) => return Err(PFE { kind: Empty }), - Some(('-', src)) => (false, src), - Some((_, _)) => (true, src), - }; - - // The significand to accumulate - let mut sig = if is_positive { 0.0 } else { -0.0 }; - // Necessary to detect overflow - let mut prev_sig = sig; - let mut cs = src.chars().enumerate(); - // Exponent prefix and exponent index offset - let mut exp_info = None::<(char, usize)>; - - // Parse the integer part of the significand - for (i, c) in cs.by_ref() { - match c.to_digit(radix) { - Some(digit) => { - // shift significand one digit left - sig = sig * (radix as $t); - - // add/subtract current digit depending on sign - if is_positive { - sig = sig + ((digit as isize) as $t); - } else { - sig = sig - ((digit as isize) as $t); - } - - // Detect overflow by comparing to last value, except - // if we've not seen any non-zero digits. - if prev_sig != 0.0 { - if is_positive && sig <= prev_sig - { return Ok(Float::infinity()); } - if !is_positive && sig >= prev_sig - { return Ok(Float::neg_infinity()); } - - // Detect overflow by reversing the shift-and-add process - if is_positive && (prev_sig != (sig - digit as $t) / radix as $t) - { return Ok(Float::infinity()); } - if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t) - { return Ok(Float::neg_infinity()); } - } - prev_sig = sig; - }, - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_info = Some((c, i + 1)); - break; // start of exponent - }, - '.' => { - break; // start of fractional part - }, - _ => { - return Err(PFE { kind: Invalid }); - }, - }, - } - } - - // If we are not yet at the exponent parse the fractional - // part of the significand - if exp_info.is_none() { - let mut power = 1.0; - for (i, c) in cs.by_ref() { - match c.to_digit(radix) { - Some(digit) => { - // Decrease power one order of magnitude - power = power / (radix as $t); - // add/subtract current digit depending on sign - sig = if is_positive { - sig + (digit as $t) * power - } else { - sig - (digit as $t) * power - }; - // Detect overflow by comparing to last value - if is_positive && sig < prev_sig - { return Ok(Float::infinity()); } - if !is_positive && sig > prev_sig - { return Ok(Float::neg_infinity()); } - prev_sig = sig; - }, - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_info = Some((c, i + 1)); - break; // start of exponent - }, - _ => { - return Err(PFE { kind: Invalid }); - }, - }, - } - } - } - - // Parse and calculate the exponent - let exp = match exp_info { - Some((c, offset)) => { - let base = match c { - 'E' | 'e' if radix == 10 => 10.0, - 'P' | 'p' if radix == 16 => 2.0, - _ => return Err(PFE { kind: Invalid }), - }; - - // Parse the exponent as decimal integer - let src = &src[offset..]; - let (is_positive, exp) = match slice_shift_char(src) { - Some(('-', src)) => (false, src.parse::()), - Some(('+', src)) => (true, src.parse::()), - Some((_, _)) => (true, src.parse::()), - None => return Err(PFE { kind: Invalid }), - }; - - match (is_positive, exp) { - (true, Ok(exp)) => base.powi(exp as i32), - (false, Ok(exp)) => 1.0 / base.powi(exp as i32), - (_, Err(_)) => return Err(PFE { kind: Invalid }), - } - }, - None => 1.0, // no exponent - }; - - Ok(sig * exp) - - } - } - )*) -} - -int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); -float_trait_impl!(Num for f32 f64); - -/// Defines an additive identity element for `Self`. -pub trait Zero: Sized + Add { - /// Returns the additive identity element of `Self`, `0`. - /// - /// # Laws - /// - /// ```{.text} - /// a + 0 = a ∀ a ∈ Self - /// 0 + a = a ∀ a ∈ Self - /// ``` - /// - /// # Purity - /// - /// This function should return the same result at all times regardless of - /// external mutable state, for example values stored in TLS or in - /// `static mut`s. - // FIXME (#5527): This should be an associated constant - fn zero() -> Self; - - /// Returns `true` if `self` is equal to the additive identity. - #[inline] - fn is_zero(&self) -> bool; -} - -macro_rules! zero_impl { - ($t:ty, $v:expr) => { - impl Zero for $t { - #[inline] - fn zero() -> $t { $v } - #[inline] - fn is_zero(&self) -> bool { *self == $v } - } - } -} - -zero_impl!(usize, 0usize); -zero_impl!(u8, 0u8); -zero_impl!(u16, 0u16); -zero_impl!(u32, 0u32); -zero_impl!(u64, 0u64); - -zero_impl!(isize, 0isize); -zero_impl!(i8, 0i8); -zero_impl!(i16, 0i16); -zero_impl!(i32, 0i32); -zero_impl!(i64, 0i64); - -zero_impl!(f32, 0.0f32); -zero_impl!(f64, 0.0f64); - -/// Defines a multiplicative identity element for `Self`. -pub trait One: Sized + Mul { - /// Returns the multiplicative identity element of `Self`, `1`. - /// - /// # Laws - /// - /// ```{.text} - /// a * 1 = a ∀ a ∈ Self - /// 1 * a = a ∀ a ∈ Self - /// ``` - /// - /// # Purity - /// - /// This function should return the same result at all times regardless of - /// external mutable state, for example values stored in TLS or in - /// `static mut`s. - // FIXME (#5527): This should be an associated constant - fn one() -> Self; -} - -macro_rules! one_impl { - ($t:ty, $v:expr) => { - impl One for $t { - #[inline] - fn one() -> $t { $v } - } - } -} - -one_impl!(usize, 1usize); -one_impl!(u8, 1u8); -one_impl!(u16, 1u16); -one_impl!(u32, 1u32); -one_impl!(u64, 1u64); - -one_impl!(isize, 1isize); -one_impl!(i8, 1i8); -one_impl!(i16, 1i16); -one_impl!(i32, 1i32); -one_impl!(i64, 1i64); - -one_impl!(f32, 1.0f32); -one_impl!(f64, 1.0f64); - -/// Useful functions for signed numbers (i.e. numbers that can be negative). -pub trait Signed: Sized + Num + Neg { - /// Computes the absolute value. - /// - /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`. - /// - /// For signed integers, `::MIN` will be returned if the number is `::MIN`. - fn abs(&self) -> Self; - - /// The positive difference of two numbers. - /// - /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference - /// between `self` and `other` is returned. - fn abs_sub(&self, other: &Self) -> Self; - - /// Returns the sign of the number. - /// - /// For `f32` and `f64`: - /// - /// * `1.0` if the number is positive, `+0.0` or `INFINITY` - /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - /// * `NaN` if the number is `NaN` - /// - /// For signed integers: - /// - /// * `0` if the number is zero - /// * `1` if the number is positive - /// * `-1` if the number is negative - fn signum(&self) -> Self; - - /// Returns true if the number is positive and false if the number is zero or negative. - fn is_positive(&self) -> bool; - - /// Returns true if the number is negative and false if the number is zero or positive. - fn is_negative(&self) -> bool; -} - -macro_rules! signed_impl { - ($($t:ty)*) => ($( - impl Signed for $t { - #[inline] - fn abs(&self) -> $t { - if self.is_negative() { -*self } else { *self } - } - - #[inline] - fn abs_sub(&self, other: &$t) -> $t { - if *self <= *other { 0 } else { *self - *other } - } - - #[inline] - fn signum(&self) -> $t { - match *self { - n if n > 0 => 1, - 0 => 0, - _ => -1, - } - } - - #[inline] - fn is_positive(&self) -> bool { *self > 0 } - - #[inline] - fn is_negative(&self) -> bool { *self < 0 } - } - )*) -} - -signed_impl!(isize i8 i16 i32 i64); - -macro_rules! signed_float_impl { - ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr) => { - impl Signed for $t { - /// Computes the absolute value. Returns `NAN` if the number is `NAN`. - #[inline] - fn abs(&self) -> $t { - <$t>::abs(*self) - } - - /// The positive difference of two numbers. Returns `0.0` if the number is - /// less than or equal to `other`, otherwise the difference between`self` - /// and `other` is returned. - #[inline] - fn abs_sub(&self, other: &$t) -> $t { - <$t>::abs_sub(*self, *other) - } - - /// # Returns - /// - /// - `1.0` if the number is positive, `+0.0` or `INFINITY` - /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - /// - `NAN` if the number is NaN - #[inline] - fn signum(&self) -> $t { - <$t>::signum(*self) - } - - /// Returns `true` if the number is positive, including `+0.0` and `INFINITY` - #[inline] - fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf } - - /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY` - #[inline] - fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf } - } - } -} - -signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY); -signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY); - -/// A trait for values which cannot be negative -pub trait Unsigned: Num {} - -macro_rules! empty_trait_impl { - ($name:ident for $($t:ty)*) => ($( - impl $name for $t {} - )*) -} - -empty_trait_impl!(Unsigned for usize u8 u16 u32 u64); - -/// Numbers which have upper and lower bounds -pub trait Bounded { - // FIXME (#5527): These should be associated constants - /// returns the smallest finite number this type can represent - fn min_value() -> Self; - /// returns the largest finite number this type can represent - fn max_value() -> Self; -} - -macro_rules! bounded_impl { - ($t:ty, $min:expr, $max:expr) => { - impl Bounded for $t { - #[inline] - fn min_value() -> $t { $min } - - #[inline] - fn max_value() -> $t { $max } - } - } -} - -bounded_impl!(usize, usize::MIN, usize::MAX); -bounded_impl!(u8, u8::MIN, u8::MAX); -bounded_impl!(u16, u16::MIN, u16::MAX); -bounded_impl!(u32, u32::MIN, u32::MAX); -bounded_impl!(u64, u64::MIN, u64::MAX); - -bounded_impl!(isize, isize::MIN, isize::MAX); -bounded_impl!(i8, i8::MIN, i8::MAX); -bounded_impl!(i16, i16::MIN, i16::MAX); -bounded_impl!(i32, i32::MIN, i32::MAX); -bounded_impl!(i64, i64::MIN, i64::MAX); - -bounded_impl!(f32, f32::MIN, f32::MAX); -bounded_impl!(f64, f64::MIN, f64::MAX); - -macro_rules! for_each_tuple_ { - ( $m:ident !! ) => ( - $m! { } - ); - ( $m:ident !! $h:ident, $($t:ident,)* ) => ( - $m! { $h $($t)* } - for_each_tuple_! { $m !! $($t,)* } - ); -} -macro_rules! for_each_tuple { - ( $m:ident ) => ( - for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, } - ); -} - -macro_rules! bounded_tuple { - ( $($name:ident)* ) => ( - impl<$($name: Bounded,)*> Bounded for ($($name,)*) { - fn min_value() -> Self { - ($($name::min_value(),)*) - } - fn max_value() -> Self { - ($($name::max_value(),)*) - } - } - ); -} - -for_each_tuple!(bounded_tuple); - -/// Saturating math operations -pub trait Saturating { - /// Saturating addition operator. - /// Returns a+b, saturating at the numeric bounds instead of overflowing. - fn saturating_add(self, v: Self) -> Self; - - /// Saturating subtraction operator. - /// Returns a-b, saturating at the numeric bounds instead of overflowing. - fn saturating_sub(self, v: Self) -> Self; -} - -impl Saturating for T { - #[inline] - fn saturating_add(self, v: T) -> T { - match self.checked_add(&v) { - Some(x) => x, - None => if v >= Zero::zero() { - Bounded::max_value() - } else { - Bounded::min_value() - } - } - } - - #[inline] - fn saturating_sub(self, v: T) -> T { - match self.checked_sub(&v) { - Some(x) => x, - None => if v >= Zero::zero() { - Bounded::min_value() - } else { - Bounded::max_value() - } - } - } -} - -/// Performs addition that returns `None` instead of wrapping around on -/// overflow. -pub trait CheckedAdd: Sized + Add { - /// Adds two numbers, checking for overflow. If overflow happens, `None` is - /// returned. - fn checked_add(&self, v: &Self) -> Option; -} - -macro_rules! checked_impl { - ($trait_name:ident, $method:ident, $t:ty) => { - impl $trait_name for $t { - #[inline] - fn $method(&self, v: &$t) -> Option<$t> { - <$t>::$method(*self, *v) - } - } - } -} - -checked_impl!(CheckedAdd, checked_add, u8); -checked_impl!(CheckedAdd, checked_add, u16); -checked_impl!(CheckedAdd, checked_add, u32); -checked_impl!(CheckedAdd, checked_add, u64); -checked_impl!(CheckedAdd, checked_add, usize); - -checked_impl!(CheckedAdd, checked_add, i8); -checked_impl!(CheckedAdd, checked_add, i16); -checked_impl!(CheckedAdd, checked_add, i32); -checked_impl!(CheckedAdd, checked_add, i64); -checked_impl!(CheckedAdd, checked_add, isize); - -/// Performs subtraction that returns `None` instead of wrapping around on underflow. -pub trait CheckedSub: Sized + Sub { - /// Subtracts two numbers, checking for underflow. If underflow happens, - /// `None` is returned. - fn checked_sub(&self, v: &Self) -> Option; -} - -checked_impl!(CheckedSub, checked_sub, u8); -checked_impl!(CheckedSub, checked_sub, u16); -checked_impl!(CheckedSub, checked_sub, u32); -checked_impl!(CheckedSub, checked_sub, u64); -checked_impl!(CheckedSub, checked_sub, usize); - -checked_impl!(CheckedSub, checked_sub, i8); -checked_impl!(CheckedSub, checked_sub, i16); -checked_impl!(CheckedSub, checked_sub, i32); -checked_impl!(CheckedSub, checked_sub, i64); -checked_impl!(CheckedSub, checked_sub, isize); - -/// Performs multiplication that returns `None` instead of wrapping around on underflow or -/// overflow. -pub trait CheckedMul: Sized + Mul { - /// Multiplies two numbers, checking for underflow or overflow. If underflow - /// or overflow happens, `None` is returned. - fn checked_mul(&self, v: &Self) -> Option; -} - -checked_impl!(CheckedMul, checked_mul, u8); -checked_impl!(CheckedMul, checked_mul, u16); -checked_impl!(CheckedMul, checked_mul, u32); -checked_impl!(CheckedMul, checked_mul, u64); -checked_impl!(CheckedMul, checked_mul, usize); - -checked_impl!(CheckedMul, checked_mul, i8); -checked_impl!(CheckedMul, checked_mul, i16); -checked_impl!(CheckedMul, checked_mul, i32); -checked_impl!(CheckedMul, checked_mul, i64); -checked_impl!(CheckedMul, checked_mul, isize); - -/// Performs division that returns `None` instead of panicking on division by zero and instead of -/// wrapping around on underflow and overflow. -pub trait CheckedDiv: Sized + Div { - /// Divides two numbers, checking for underflow, overflow and division by - /// zero. If any of that happens, `None` is returned. - fn checked_div(&self, v: &Self) -> Option; -} - -macro_rules! checkeddiv_int_impl { - ($t:ty, $min:expr) => { - impl CheckedDiv for $t { - #[inline] - fn checked_div(&self, v: &$t) -> Option<$t> { - if *v == 0 || (*self == $min && *v == -1) { - None - } else { - Some(*self / *v) - } - } - } - } -} - -checkeddiv_int_impl!(isize, isize::MIN); -checkeddiv_int_impl!(i8, i8::MIN); -checkeddiv_int_impl!(i16, i16::MIN); -checkeddiv_int_impl!(i32, i32::MIN); -checkeddiv_int_impl!(i64, i64::MIN); - -macro_rules! checkeddiv_uint_impl { - ($($t:ty)*) => ($( - impl CheckedDiv for $t { - #[inline] - fn checked_div(&self, v: &$t) -> Option<$t> { - if *v == 0 { - None - } else { - Some(*self / *v) - } - } - } - )*) -} - -checkeddiv_uint_impl!(usize u8 u16 u32 u64); - -pub trait PrimInt - : Sized - + Copy - + Num + NumCast - + Bounded - + PartialOrd + Ord + Eq - + Not - + BitAnd - + BitOr - + BitXor - + Shl - + Shr - + CheckedAdd - + CheckedSub - + CheckedMul - + CheckedDiv - + Saturating -{ - /// Returns the number of ones in the binary representation of `self`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0b01001100u8; - /// - /// assert_eq!(n.count_ones(), 3); - /// ``` - fn count_ones(self) -> u32; - - /// Returns the number of zeros in the binary representation of `self`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0b01001100u8; - /// - /// assert_eq!(n.count_zeros(), 5); - /// ``` - fn count_zeros(self) -> u32; - - /// Returns the number of leading zeros in the binary representation - /// of `self`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0b0101000u16; - /// - /// assert_eq!(n.leading_zeros(), 10); - /// ``` - fn leading_zeros(self) -> u32; - - /// Returns the number of trailing zeros in the binary representation - /// of `self`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0b0101000u16; - /// - /// assert_eq!(n.trailing_zeros(), 3); - /// ``` - fn trailing_zeros(self) -> u32; - - /// Shifts the bits to the left by a specified amount amount, `n`, wrapping - /// the truncated bits to the end of the resulting integer. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0x3456789ABCDEF012u64; - /// - /// assert_eq!(n.rotate_left(12), m); - /// ``` - fn rotate_left(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, wrapping - /// the truncated bits to the beginning of the resulting integer. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0xDEF0123456789ABCu64; - /// - /// assert_eq!(n.rotate_right(12), m); - /// ``` - fn rotate_right(self, n: u32) -> Self; - - /// Shifts the bits to the left by a specified amount amount, `n`, filling - /// zeros in the least significant bits. - /// - /// This is bitwise equivalent to signed `Shl`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0x3456789ABCDEF000u64; - /// - /// assert_eq!(n.signed_shl(12), m); - /// ``` - fn signed_shl(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, copying - /// the "sign bit" in the most significant bits even for unsigned types. - /// - /// This is bitwise equivalent to signed `Shr`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0xFEDCBA9876543210u64; - /// let m = 0xFFFFEDCBA9876543u64; - /// - /// assert_eq!(n.signed_shr(12), m); - /// ``` - fn signed_shr(self, n: u32) -> Self; - - /// Shifts the bits to the left by a specified amount amount, `n`, filling - /// zeros in the least significant bits. - /// - /// This is bitwise equivalent to unsigned `Shl`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFi64; - /// let m = 0x3456789ABCDEF000i64; - /// - /// assert_eq!(n.unsigned_shl(12), m); - /// ``` - fn unsigned_shl(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, filling - /// zeros in the most significant bits. - /// - /// This is bitwise equivalent to unsigned `Shr`. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0xFEDCBA9876543210i64; - /// let m = 0x000FEDCBA9876543i64; - /// - /// assert_eq!(n.unsigned_shr(12), m); - /// ``` - fn unsigned_shr(self, n: u32) -> Self; - - /// Reverses the byte order of the integer. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0xEFCDAB8967452301u64; - /// - /// assert_eq!(n.swap_bytes(), m); - /// ``` - fn swap_bytes(self) -> Self; - - /// Convert an integer from big endian to the target's endianness. - /// - /// On big endian this is a no-op. On little endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "big") { - /// assert_eq!(u64::from_be(n), n) - /// } else { - /// assert_eq!(u64::from_be(n), n.swap_bytes()) - /// } - /// ``` - fn from_be(x: Self) -> Self; - - /// Convert an integer from little endian to the target's endianness. - /// - /// On little endian this is a no-op. On big endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "little") { - /// assert_eq!(u64::from_le(n), n) - /// } else { - /// assert_eq!(u64::from_le(n), n.swap_bytes()) - /// } - /// ``` - fn from_le(x: Self) -> Self; - - /// Convert `self` to big endian from the target's endianness. - /// - /// On big endian this is a no-op. On little endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "big") { - /// assert_eq!(n.to_be(), n) - /// } else { - /// assert_eq!(n.to_be(), n.swap_bytes()) - /// } - /// ``` - fn to_be(self) -> Self; - - /// Convert `self` to little endian from the target's endianness. - /// - /// On little endian this is a no-op. On big endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "little") { - /// assert_eq!(n.to_le(), n) - /// } else { - /// assert_eq!(n.to_le(), n.swap_bytes()) - /// } - /// ``` - fn to_le(self) -> Self; - - /// Raises self to the power of `exp`, using exponentiation by squaring. - /// - /// # Examples - /// - /// ``` - /// use num::traits::PrimInt; - /// - /// assert_eq!(2i32.pow(4), 16); - /// ``` - fn pow(self, mut exp: u32) -> Self; -} - -macro_rules! prim_int_impl { - ($T:ty, $S:ty, $U:ty) => ( - impl PrimInt for $T { - fn count_ones(self) -> u32 { - <$T>::count_ones(self) - } - - fn count_zeros(self) -> u32 { - <$T>::count_zeros(self) - } - - fn leading_zeros(self) -> u32 { - <$T>::leading_zeros(self) - } - - fn trailing_zeros(self) -> u32 { - <$T>::trailing_zeros(self) - } - - fn rotate_left(self, n: u32) -> Self { - <$T>::rotate_left(self, n) - } - - fn rotate_right(self, n: u32) -> Self { - <$T>::rotate_right(self, n) - } - - fn signed_shl(self, n: u32) -> Self { - ((self as $S) << n) as $T - } - - fn signed_shr(self, n: u32) -> Self { - ((self as $S) >> n) as $T - } - - fn unsigned_shl(self, n: u32) -> Self { - ((self as $U) << n) as $T - } - - fn unsigned_shr(self, n: u32) -> Self { - ((self as $U) >> n) as $T - } - - fn swap_bytes(self) -> Self { - <$T>::swap_bytes(self) - } - - fn from_be(x: Self) -> Self { - <$T>::from_be(x) - } - - fn from_le(x: Self) -> Self { - <$T>::from_le(x) - } - - fn to_be(self) -> Self { - <$T>::to_be(self) - } - - fn to_le(self) -> Self { - <$T>::to_le(self) - } - - fn pow(self, exp: u32) -> Self { - <$T>::pow(self, exp) - } - } - ) -} - -// prim_int_impl!(type, signed, unsigned); -prim_int_impl!(u8, i8, u8); -prim_int_impl!(u16, i16, u16); -prim_int_impl!(u32, i32, u32); -prim_int_impl!(u64, i64, u64); -prim_int_impl!(usize, isize, usize); -prim_int_impl!(i8, i8, u8); -prim_int_impl!(i16, i16, u16); -prim_int_impl!(i32, i32, u32); -prim_int_impl!(i64, i64, u64); -prim_int_impl!(isize, isize, usize); - -/// A generic trait for converting a value to a number. -pub trait ToPrimitive { - /// Converts the value of `self` to an `isize`. - #[inline] - fn to_isize(&self) -> Option { - self.to_i64().and_then(|x| x.to_isize()) - } - - /// Converts the value of `self` to an `i8`. - #[inline] - fn to_i8(&self) -> Option { - self.to_i64().and_then(|x| x.to_i8()) - } - - /// Converts the value of `self` to an `i16`. - #[inline] - fn to_i16(&self) -> Option { - self.to_i64().and_then(|x| x.to_i16()) - } - - /// Converts the value of `self` to an `i32`. - #[inline] - fn to_i32(&self) -> Option { - self.to_i64().and_then(|x| x.to_i32()) - } - - /// Converts the value of `self` to an `i64`. - fn to_i64(&self) -> Option; - - /// Converts the value of `self` to a `usize`. - #[inline] - fn to_usize(&self) -> Option { - self.to_u64().and_then(|x| x.to_usize()) - } - - /// Converts the value of `self` to an `u8`. - #[inline] - fn to_u8(&self) -> Option { - self.to_u64().and_then(|x| x.to_u8()) - } - - /// Converts the value of `self` to an `u16`. - #[inline] - fn to_u16(&self) -> Option { - self.to_u64().and_then(|x| x.to_u16()) - } - - /// Converts the value of `self` to an `u32`. - #[inline] - fn to_u32(&self) -> Option { - self.to_u64().and_then(|x| x.to_u32()) - } - - /// Converts the value of `self` to an `u64`. - #[inline] - fn to_u64(&self) -> Option; - - /// Converts the value of `self` to an `f32`. - #[inline] - fn to_f32(&self) -> Option { - self.to_f64().and_then(|x| x.to_f32()) - } - - /// Converts the value of `self` to an `f64`. - #[inline] - fn to_f64(&self) -> Option { - self.to_i64().and_then(|x| x.to_f64()) - } -} - -macro_rules! impl_to_primitive_int_to_int { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - let n = $slf as i64; - let min_value: $DstT = Bounded::min_value(); - let max_value: $DstT = Bounded::max_value(); - if min_value as i64 <= n && n <= max_value as i64 { - Some($slf as $DstT) - } else { - None - } - } - } - ) -} - -macro_rules! impl_to_primitive_int_to_uint { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - let zero: $SrcT = Zero::zero(); - let max_value: $DstT = Bounded::max_value(); - if zero <= $slf && $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_int { - ($T:ty) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { impl_to_primitive_int_to_int!($T, isize, *self) } - #[inline] - fn to_i8(&self) -> Option { impl_to_primitive_int_to_int!($T, i8, *self) } - #[inline] - fn to_i16(&self) -> Option { impl_to_primitive_int_to_int!($T, i16, *self) } - #[inline] - fn to_i32(&self) -> Option { impl_to_primitive_int_to_int!($T, i32, *self) } - #[inline] - fn to_i64(&self) -> Option { impl_to_primitive_int_to_int!($T, i64, *self) } - - #[inline] - fn to_usize(&self) -> Option { impl_to_primitive_int_to_uint!($T, usize, *self) } - #[inline] - fn to_u8(&self) -> Option { impl_to_primitive_int_to_uint!($T, u8, *self) } - #[inline] - fn to_u16(&self) -> Option { impl_to_primitive_int_to_uint!($T, u16, *self) } - #[inline] - fn to_u32(&self) -> Option { impl_to_primitive_int_to_uint!($T, u32, *self) } - #[inline] - fn to_u64(&self) -> Option { impl_to_primitive_int_to_uint!($T, u64, *self) } - - #[inline] - fn to_f32(&self) -> Option { Some(*self as f32) } - #[inline] - fn to_f64(&self) -> Option { Some(*self as f64) } - } - ) -} - -impl_to_primitive_int! { isize } -impl_to_primitive_int! { i8 } -impl_to_primitive_int! { i16 } -impl_to_primitive_int! { i32 } -impl_to_primitive_int! { i64 } - -macro_rules! impl_to_primitive_uint_to_int { - ($DstT:ty, $slf:expr) => ( - { - let max_value: $DstT = Bounded::max_value(); - if $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_uint_to_uint { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - let zero: $SrcT = Zero::zero(); - let max_value: $DstT = Bounded::max_value(); - if zero <= $slf && $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - } - ) -} - -macro_rules! impl_to_primitive_uint { - ($T:ty) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { impl_to_primitive_uint_to_int!(isize, *self) } - #[inline] - fn to_i8(&self) -> Option { impl_to_primitive_uint_to_int!(i8, *self) } - #[inline] - fn to_i16(&self) -> Option { impl_to_primitive_uint_to_int!(i16, *self) } - #[inline] - fn to_i32(&self) -> Option { impl_to_primitive_uint_to_int!(i32, *self) } - #[inline] - fn to_i64(&self) -> Option { impl_to_primitive_uint_to_int!(i64, *self) } - - #[inline] - fn to_usize(&self) -> Option { - impl_to_primitive_uint_to_uint!($T, usize, *self) - } - #[inline] - fn to_u8(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u8, *self) } - #[inline] - fn to_u16(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u16, *self) } - #[inline] - fn to_u32(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u32, *self) } - #[inline] - fn to_u64(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u64, *self) } - - #[inline] - fn to_f32(&self) -> Option { Some(*self as f32) } - #[inline] - fn to_f64(&self) -> Option { Some(*self as f64) } - } - ) -} - -impl_to_primitive_uint! { usize } -impl_to_primitive_uint! { u8 } -impl_to_primitive_uint! { u16 } -impl_to_primitive_uint! { u32 } -impl_to_primitive_uint! { u64 } - -macro_rules! impl_to_primitive_float_to_float { - ($SrcT:ident, $DstT:ident, $slf:expr) => ( - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - let n = $slf as f64; - let max_value: $SrcT = ::std::$SrcT::MAX; - if -max_value as f64 <= n && n <= max_value as f64 { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_float { - ($T:ident) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { Some(*self as isize) } - #[inline] - fn to_i8(&self) -> Option { Some(*self as i8) } - #[inline] - fn to_i16(&self) -> Option { Some(*self as i16) } - #[inline] - fn to_i32(&self) -> Option { Some(*self as i32) } - #[inline] - fn to_i64(&self) -> Option { Some(*self as i64) } - - #[inline] - fn to_usize(&self) -> Option { Some(*self as usize) } - #[inline] - fn to_u8(&self) -> Option { Some(*self as u8) } - #[inline] - fn to_u16(&self) -> Option { Some(*self as u16) } - #[inline] - fn to_u32(&self) -> Option { Some(*self as u32) } - #[inline] - fn to_u64(&self) -> Option { Some(*self as u64) } - - #[inline] - fn to_f32(&self) -> Option { impl_to_primitive_float_to_float!($T, f32, *self) } - #[inline] - fn to_f64(&self) -> Option { impl_to_primitive_float_to_float!($T, f64, *self) } - } - ) -} - -impl_to_primitive_float! { f32 } -impl_to_primitive_float! { f64 } - -/// A generic trait for converting a number to a value. -pub trait FromPrimitive: Sized { - /// Convert an `isize` to return an optional value of this type. If the - /// value cannot be represented by this value, the `None` is returned. - #[inline] - fn from_isize(n: isize) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i8` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i8(n: i8) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i16` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i16(n: i16) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i32(n: i32) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - fn from_i64(n: i64) -> Option; - - /// Convert a `usize` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_usize(n: usize) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u8` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u8(n: u8) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u16` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u16(n: u16) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u32(n: u32) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - fn from_u64(n: u64) -> Option; - - /// Convert a `f32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_f32(n: f32) -> Option { - FromPrimitive::from_f64(n as f64) - } - - /// Convert a `f64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_f64(n: f64) -> Option { - FromPrimitive::from_i64(n as i64) - } -} - -macro_rules! impl_from_primitive { - ($T:ty, $to_ty:ident) => ( - #[allow(deprecated)] - impl FromPrimitive for $T { - #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } - - #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } - - #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } - } - ) -} - -impl_from_primitive! { isize, to_isize } -impl_from_primitive! { i8, to_i8 } -impl_from_primitive! { i16, to_i16 } -impl_from_primitive! { i32, to_i32 } -impl_from_primitive! { i64, to_i64 } -impl_from_primitive! { usize, to_usize } -impl_from_primitive! { u8, to_u8 } -impl_from_primitive! { u16, to_u16 } -impl_from_primitive! { u32, to_u32 } -impl_from_primitive! { u64, to_u64 } -impl_from_primitive! { f32, to_f32 } -impl_from_primitive! { f64, to_f64 } - -/// Cast from one machine scalar to another. -/// -/// # Examples -/// -/// ``` -/// use num; -/// -/// let twenty: f32 = num::cast(0x14).unwrap(); -/// assert_eq!(twenty, 20f32); -/// ``` -/// -#[inline] -pub fn cast(n: T) -> Option { - NumCast::from(n) -} - -/// An interface for casting between machine scalars. -pub trait NumCast: Sized + ToPrimitive { - /// Creates a number from another value that can be converted into - /// a primitive via the `ToPrimitive` trait. - fn from(n: T) -> Option; -} - -macro_rules! impl_num_cast { - ($T:ty, $conv:ident) => ( - impl NumCast for $T { - #[inline] - #[allow(deprecated)] - fn from(n: N) -> Option<$T> { - // `$conv` could be generated using `concat_idents!`, but that - // macro seems to be broken at the moment - n.$conv() - } - } - ) -} - -impl_num_cast! { u8, to_u8 } -impl_num_cast! { u16, to_u16 } -impl_num_cast! { u32, to_u32 } -impl_num_cast! { u64, to_u64 } -impl_num_cast! { usize, to_usize } -impl_num_cast! { i8, to_i8 } -impl_num_cast! { i16, to_i16 } -impl_num_cast! { i32, to_i32 } -impl_num_cast! { i64, to_i64 } -impl_num_cast! { isize, to_isize } -impl_num_cast! { f32, to_f32 } -impl_num_cast! { f64, to_f64 } - -pub trait Float - : Num - + Copy - + NumCast - + PartialOrd - + Neg -{ - /// Returns the `NaN` value. - /// - /// ``` - /// use num::traits::Float; - /// - /// let nan: f32 = Float::nan(); - /// - /// assert!(nan.is_nan()); - /// ``` - fn nan() -> Self; - /// Returns the infinite value. - /// - /// ``` - /// use num::traits::Float; - /// use std::f32; - /// - /// let infinity: f32 = Float::infinity(); - /// - /// assert!(infinity.is_infinite()); - /// assert!(!infinity.is_finite()); - /// assert!(infinity > f32::MAX); - /// ``` - fn infinity() -> Self; - /// Returns the negative infinite value. - /// - /// ``` - /// use num::traits::Float; - /// use std::f32; - /// - /// let neg_infinity: f32 = Float::neg_infinity(); - /// - /// assert!(neg_infinity.is_infinite()); - /// assert!(!neg_infinity.is_finite()); - /// assert!(neg_infinity < f32::MIN); - /// ``` - fn neg_infinity() -> Self; - /// Returns `-0.0`. - /// - /// ``` - /// use num::traits::{Zero, Float}; - /// - /// let inf: f32 = Float::infinity(); - /// let zero: f32 = Zero::zero(); - /// let neg_zero: f32 = Float::neg_zero(); - /// - /// assert_eq!(zero, neg_zero); - /// assert_eq!(7.0f32/inf, zero); - /// assert_eq!(zero * 10.0, zero); - /// ``` - fn neg_zero() -> Self; - - /// Returns the smallest finite value that this type can represent. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::min_value(); - /// - /// assert_eq!(x, f64::MIN); - /// ``` - fn min_value() -> Self; - - /// Returns the smallest positive, normalized value that this type can represent. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::min_positive_value(); - /// - /// assert_eq!(x, f64::MIN_POSITIVE); - /// ``` - fn min_positive_value() -> Self; - - /// Returns the largest finite value that this type can represent. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::max_value(); - /// assert_eq!(x, f64::MAX); - /// ``` - fn max_value() -> Self; - - /// Returns `true` if this value is `NaN` and false otherwise. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let nan = f64::NAN; - /// let f = 7.0; - /// - /// assert!(nan.is_nan()); - /// assert!(!f.is_nan()); - /// ``` - fn is_nan(self) -> bool; - - /// Returns `true` if this value is positive infinity or negative infinity and - /// false otherwise. - /// - /// ``` - /// use num::traits::Float; - /// use std::f32; - /// - /// let f = 7.0f32; - /// let inf: f32 = Float::infinity(); - /// let neg_inf: f32 = Float::neg_infinity(); - /// let nan: f32 = f32::NAN; - /// - /// assert!(!f.is_infinite()); - /// assert!(!nan.is_infinite()); - /// - /// assert!(inf.is_infinite()); - /// assert!(neg_inf.is_infinite()); - /// ``` - fn is_infinite(self) -> bool; - - /// Returns `true` if this number is neither infinite nor `NaN`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f32; - /// - /// let f = 7.0f32; - /// let inf: f32 = Float::infinity(); - /// let neg_inf: f32 = Float::neg_infinity(); - /// let nan: f32 = f32::NAN; - /// - /// assert!(f.is_finite()); - /// - /// assert!(!nan.is_finite()); - /// assert!(!inf.is_finite()); - /// assert!(!neg_inf.is_finite()); - /// ``` - fn is_finite(self) -> bool; - - /// Returns `true` if the number is neither zero, infinite, - /// [subnormal][subnormal], or `NaN`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f32; - /// - /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 - /// let max = f32::MAX; - /// let lower_than_min = 1.0e-40_f32; - /// let zero = 0.0f32; - /// - /// assert!(min.is_normal()); - /// assert!(max.is_normal()); - /// - /// assert!(!zero.is_normal()); - /// assert!(!f32::NAN.is_normal()); - /// assert!(!f32::INFINITY.is_normal()); - /// // Values between `0` and `min` are Subnormal. - /// assert!(!lower_than_min.is_normal()); - /// ``` - /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number - fn is_normal(self) -> bool; - - /// Returns the floating point category of the number. If only one property - /// is going to be tested, it is generally faster to use the specific - /// predicate instead. - /// - /// ``` - /// use num::traits::Float; - /// use std::num::FpCategory; - /// use std::f32; - /// - /// let num = 12.4f32; - /// let inf = f32::INFINITY; - /// - /// assert_eq!(num.classify(), FpCategory::Normal); - /// assert_eq!(inf.classify(), FpCategory::Infinite); - /// ``` - fn classify(self) -> FpCategory; - - /// Returns the largest integer less than or equal to a number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 3.99; - /// let g = 3.0; - /// - /// assert_eq!(f.floor(), 3.0); - /// assert_eq!(g.floor(), 3.0); - /// ``` - fn floor(self) -> Self; - - /// Returns the smallest integer greater than or equal to a number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 3.01; - /// let g = 4.0; - /// - /// assert_eq!(f.ceil(), 4.0); - /// assert_eq!(g.ceil(), 4.0); - /// ``` - fn ceil(self) -> Self; - - /// Returns the nearest integer to a number. Round half-way cases away from - /// `0.0`. - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 3.3; - /// let g = -3.3; - /// - /// assert_eq!(f.round(), 3.0); - /// assert_eq!(g.round(), -3.0); - /// ``` - fn round(self) -> Self; - - /// Return the integer part of a number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 3.3; - /// let g = -3.7; - /// - /// assert_eq!(f.trunc(), 3.0); - /// assert_eq!(g.trunc(), -3.0); - /// ``` - fn trunc(self) -> Self; - - /// Returns the fractional part of a number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 3.5; - /// let y = -3.5; - /// let abs_difference_x = (x.fract() - 0.5).abs(); - /// let abs_difference_y = (y.fract() - (-0.5)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn fract(self) -> Self; - - /// Computes the absolute value of `self`. Returns `Float::nan()` if the - /// number is `Float::nan()`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = 3.5; - /// let y = -3.5; - /// - /// let abs_difference_x = (x.abs() - x).abs(); - /// let abs_difference_y = (y.abs() - (-y)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// - /// assert!(f64::NAN.abs().is_nan()); - /// ``` - fn abs(self) -> Self; - - /// Returns a number that represents the sign of `self`. - /// - /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` - /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` - /// - `Float::nan()` if the number is `Float::nan()` - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let f = 3.5; - /// - /// assert_eq!(f.signum(), 1.0); - /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); - /// - /// assert!(f64::NAN.signum().is_nan()); - /// ``` - fn signum(self) -> Self; - - /// Returns `true` if `self` is positive, including `+0.0` and - /// `Float::infinity()`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let nan: f64 = f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(f.is_sign_positive()); - /// assert!(!g.is_sign_positive()); - /// // Requires both tests to determine if is `NaN` - /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative()); - /// ``` - fn is_sign_positive(self) -> bool; - - /// Returns `true` if `self` is negative, including `-0.0` and - /// `Float::neg_infinity()`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let nan = f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(!f.is_sign_negative()); - /// assert!(g.is_sign_negative()); - /// // Requires both tests to determine if is `NaN`. - /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative()); - /// ``` - fn is_sign_negative(self) -> bool; - - /// Fused multiply-add. Computes `(self * a) + b` with only one rounding - /// error. This produces a more accurate result with better performance than - /// a separate multiplication operation followed by an add. - /// - /// ``` - /// use num::traits::Float; - /// - /// let m = 10.0; - /// let x = 4.0; - /// let b = 60.0; - /// - /// // 100.0 - /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn mul_add(self, a: Self, b: Self) -> Self; - /// Take the reciprocal (inverse) of a number, `1/x`. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.recip() - (1.0/x)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn recip(self) -> Self; - - /// Raise a number to an integer power. - /// - /// Using this function is generally faster than using `powf` - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.powi(2) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powi(self, n: i32) -> Self; - - /// Raise a number to a floating point power. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.powf(2.0) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powf(self, n: Self) -> Self; - - /// Take the square root of a number. - /// - /// Returns NaN if `self` is a negative number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let positive = 4.0; - /// let negative = -4.0; - /// - /// let abs_difference = (positive.sqrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// assert!(negative.sqrt().is_nan()); - /// ``` - fn sqrt(self) -> Self; - - /// Returns `e^(self)`, (the exponential function). - /// - /// ``` - /// use num::traits::Float; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp(self) -> Self; - - /// Returns `2^(self)`. - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 2.0; - /// - /// // 2^2 - 4 == 0 - /// let abs_difference = (f.exp2() - 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp2(self) -> Self; - - /// Returns the natural logarithm of the number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln(self) -> Self; - - /// Returns the logarithm of the number with respect to an arbitrary base. - /// - /// ``` - /// use num::traits::Float; - /// - /// let ten = 10.0; - /// let two = 2.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); - /// - /// // log2(2) - 1 == 0 - /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); - /// - /// assert!(abs_difference_10 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn log(self, base: Self) -> Self; - - /// Returns the base 2 logarithm of the number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let two = 2.0; - /// - /// // log2(2) - 1 == 0 - /// let abs_difference = (two.log2() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log2(self) -> Self; - - /// Returns the base 10 logarithm of the number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let ten = 10.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference = (ten.log10() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log10(self) -> Self; - - /// Returns the maximum of the two numbers. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.max(y), y); - /// ``` - fn max(self, other: Self) -> Self; - - /// Returns the minimum of the two numbers. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.min(y), x); - /// ``` - fn min(self, other: Self) -> Self; - - /// The positive difference of two numbers. - /// - /// * If `self <= other`: `0:0` - /// * Else: `self - other` - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 3.0; - /// let y = -3.0; - /// - /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); - /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn abs_sub(self, other: Self) -> Self; - - /// Take the cubic root of a number. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 8.0; - /// - /// // x^(1/3) - 2 == 0 - /// let abs_difference = (x.cbrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cbrt(self) -> Self; - - /// Calculate the length of the hypotenuse of a right-angle triangle given - /// legs of length `x` and `y`. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 2.0; - /// let y = 3.0; - /// - /// // sqrt(x^2 + y^2) - /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn hypot(self, other: Self) -> Self; - - /// Computes the sine of a number (in radians). - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/2.0; - /// - /// let abs_difference = (x.sin() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sin(self) -> Self; - - /// Computes the cosine of a number (in radians). - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = 2.0*f64::consts::PI; - /// - /// let abs_difference = (x.cos() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cos(self) -> Self; - - /// Computes the tangent of a number (in radians). - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let abs_difference = (x.tan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-14); - /// ``` - fn tan(self) -> Self; - - /// Computes the arcsine of a number. Return value is in radians in - /// the range [-pi/2, pi/2] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let f = f64::consts::PI / 2.0; - /// - /// // asin(sin(pi/2)) - /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn asin(self) -> Self; - - /// Computes the arccosine of a number. Return value is in radians in - /// the range [0, pi] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let f = f64::consts::PI / 4.0; - /// - /// // acos(cos(pi/4)) - /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn acos(self) -> Self; - - /// Computes the arctangent of a number. Return value is in radians in the - /// range [-pi/2, pi/2]; - /// - /// ``` - /// use num::traits::Float; - /// - /// let f = 1.0; - /// - /// // atan(tan(1)) - /// let abs_difference = (f.tan().atan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn atan(self) -> Self; - - /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). - /// - /// * `x = 0`, `y = 0`: `0` - /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` - /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` - /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let pi = f64::consts::PI; - /// // All angles from horizontal right (+x) - /// // 45 deg counter-clockwise - /// let x1 = 3.0; - /// let y1 = -3.0; - /// - /// // 135 deg clockwise - /// let x2 = -3.0; - /// let y2 = 3.0; - /// - /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); - /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); - /// - /// assert!(abs_difference_1 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn atan2(self, other: Self) -> Self; - - /// Simultaneously computes the sine and cosine of the number, `x`. Returns - /// `(sin(x), cos(x))`. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let f = x.sin_cos(); - /// - /// let abs_difference_0 = (f.0 - x.sin()).abs(); - /// let abs_difference_1 = (f.1 - x.cos()).abs(); - /// - /// assert!(abs_difference_0 < 1e-10); - /// assert!(abs_difference_0 < 1e-10); - /// ``` - fn sin_cos(self) -> (Self, Self); - - /// Returns `e^(self) - 1` in a way that is accurate even if the - /// number is close to zero. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 7.0; - /// - /// // e^(ln(7)) - 1 - /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp_m1(self) -> Self; - - /// Returns `ln(1+n)` (natural logarithm) more accurately than if - /// the operations were performed separately. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::E - 1.0; - /// - /// // ln(1 + (e - 1)) == ln(e) == 1 - /// let abs_difference = (x.ln_1p() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln_1p(self) -> Self; - - /// Hyperbolic sine function. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.sinh(); - /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` - /// let g = (e*e - 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sinh(self) -> Self; - - /// Hyperbolic cosine function. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// let f = x.cosh(); - /// // Solving cosh() at 1 gives this result - /// let g = (e*e + 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// // Same result - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn cosh(self) -> Self; - - /// Hyperbolic tangent function. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.tanh(); - /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` - /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn tanh(self) -> Self; - - /// Inverse hyperbolic sine function. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 1.0; - /// let f = x.sinh().asinh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn asinh(self) -> Self; - - /// Inverse hyperbolic cosine function. - /// - /// ``` - /// use num::traits::Float; - /// - /// let x = 1.0; - /// let f = x.cosh().acosh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn acosh(self) -> Self; - - /// Inverse hyperbolic tangent function. - /// - /// ``` - /// use num::traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let f = e.tanh().atanh(); - /// - /// let abs_difference = (f - e).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn atanh(self) -> Self; - - - /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. - /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. - /// The floating point encoding is documented in the [Reference][floating-point]. - /// - /// ``` - /// use num::traits::Float; - /// - /// let num = 2.0f32; - /// - /// // (8388608, -22, 1) - /// let (mantissa, exponent, sign) = Float::integer_decode(num); - /// let sign_f = sign as f32; - /// let mantissa_f = mantissa as f32; - /// let exponent_f = num.powf(exponent as f32); - /// - /// // 1 * 8388608 * 2^(-22) == 2 - /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - /// [floating-point]: ../../../../../reference.html#machine-types - fn integer_decode(self) -> (u64, i16, i8); -} - -macro_rules! float_impl { - ($T:ident $decode:ident) => ( - impl Float for $T { - fn nan() -> Self { - ::std::$T::NAN - } - - fn infinity() -> Self { - ::std::$T::INFINITY - } - - fn neg_infinity() -> Self { - ::std::$T::NEG_INFINITY - } - - fn neg_zero() -> Self { - -0.0 - } - - fn min_value() -> Self { - ::std::$T::MIN - } - - fn min_positive_value() -> Self { - ::std::$T::MIN_POSITIVE - } - - fn max_value() -> Self { - ::std::$T::MAX - } - - fn is_nan(self) -> bool { - <$T>::is_nan(self) - } - - fn is_infinite(self) -> bool { - <$T>::is_infinite(self) - } - - fn is_finite(self) -> bool { - <$T>::is_finite(self) - } - - fn is_normal(self) -> bool { - <$T>::is_normal(self) - } - - fn classify(self) -> FpCategory { - <$T>::classify(self) - } - - fn floor(self) -> Self { - <$T>::floor(self) - } - - fn ceil(self) -> Self { - <$T>::ceil(self) - } - - fn round(self) -> Self { - <$T>::round(self) - } - - fn trunc(self) -> Self { - <$T>::trunc(self) - } - - fn fract(self) -> Self { - <$T>::fract(self) - } - - fn abs(self) -> Self { - <$T>::abs(self) - } - - fn signum(self) -> Self { - <$T>::signum(self) - } - - fn is_sign_positive(self) -> bool { - <$T>::is_sign_positive(self) - } - - fn is_sign_negative(self) -> bool { - <$T>::is_sign_negative(self) - } - - fn mul_add(self, a: Self, b: Self) -> Self { - <$T>::mul_add(self, a, b) - } - - fn recip(self) -> Self { - <$T>::recip(self) - } - - fn powi(self, n: i32) -> Self { - <$T>::powi(self, n) - } - - fn powf(self, n: Self) -> Self { - <$T>::powf(self, n) - } - - fn sqrt(self) -> Self { - <$T>::sqrt(self) - } - - fn exp(self) -> Self { - <$T>::exp(self) - } - - fn exp2(self) -> Self { - <$T>::exp2(self) - } - - fn ln(self) -> Self { - <$T>::ln(self) - } - - fn log(self, base: Self) -> Self { - <$T>::log(self, base) - } - - fn log2(self) -> Self { - <$T>::log2(self) - } - - fn log10(self) -> Self { - <$T>::log10(self) - } - - fn max(self, other: Self) -> Self { - <$T>::max(self, other) - } - - fn min(self, other: Self) -> Self { - <$T>::min(self, other) - } - - fn abs_sub(self, other: Self) -> Self { - <$T>::abs_sub(self, other) - } - - fn cbrt(self) -> Self { - <$T>::cbrt(self) - } - - fn hypot(self, other: Self) -> Self { - <$T>::hypot(self, other) - } - - fn sin(self) -> Self { - <$T>::sin(self) - } - - fn cos(self) -> Self { - <$T>::cos(self) - } - - fn tan(self) -> Self { - <$T>::tan(self) - } - - fn asin(self) -> Self { - <$T>::asin(self) - } - - fn acos(self) -> Self { - <$T>::acos(self) - } - - fn atan(self) -> Self { - <$T>::atan(self) - } - - fn atan2(self, other: Self) -> Self { - <$T>::atan2(self, other) - } - - fn sin_cos(self) -> (Self, Self) { - <$T>::sin_cos(self) - } - - fn exp_m1(self) -> Self { - <$T>::exp_m1(self) - } - - fn ln_1p(self) -> Self { - <$T>::ln_1p(self) - } - - fn sinh(self) -> Self { - <$T>::sinh(self) - } - - fn cosh(self) -> Self { - <$T>::cosh(self) - } - - fn tanh(self) -> Self { - <$T>::tanh(self) - } - - fn asinh(self) -> Self { - <$T>::asinh(self) - } - - fn acosh(self) -> Self { - <$T>::acosh(self) - } - - fn atanh(self) -> Self { - <$T>::atanh(self) - } - - fn integer_decode(self) -> (u64, i16, i8) { - $decode(self) - } - } - ) -} - -fn integer_decode_f32(f: f32) -> (u64, i16, i8) { - let bits: u32 = unsafe { mem::transmute(f) }; - let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 }; - let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; - let mantissa = if exponent == 0 { - (bits & 0x7fffff) << 1 - } else { - (bits & 0x7fffff) | 0x800000 - }; - // Exponent bias + mantissa shift - exponent -= 127 + 23; - (mantissa as u64, exponent, sign) -} - -fn integer_decode_f64(f: f64) -> (u64, i16, i8) { - let bits: u64 = unsafe { mem::transmute(f) }; - let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; - let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; - let mantissa = if exponent == 0 { - (bits & 0xfffffffffffff) << 1 - } else { - (bits & 0xfffffffffffff) | 0x10000000000000 - }; - // Exponent bias + mantissa shift - exponent -= 1023 + 52; - (mantissa, exponent, sign) -} - -float_impl!(f32 integer_decode_f32); -float_impl!(f64 integer_decode_f64); - - -#[test] -fn from_str_radix_unwrap() { - // The Result error must impl Debug to allow unwrap() - - let i: i32 = Num::from_str_radix("0", 10).unwrap(); - assert_eq!(i, 0); - - let f: f32 = Num::from_str_radix("0.0", 10).unwrap(); - assert_eq!(f, 0.0); -} diff --git a/traits/Cargo.toml b/traits/Cargo.toml new file mode 100644 index 0000000..ee01da4 --- /dev/null +++ b/traits/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "num-traits" +version = "0.1.0" +authors = ["Łukasz Jan Niemier "] + +[dependencies] diff --git a/traits/src/bounds.rs b/traits/src/bounds.rs new file mode 100644 index 0000000..9f527d7 --- /dev/null +++ b/traits/src/bounds.rs @@ -0,0 +1,69 @@ +use std::{usize, u8, u16, u32, u64}; +use std::{isize, i8, i16, i32, i64}; +use std::{f32, f64}; + +/// Numbers which have upper and lower bounds +pub trait Bounded { + // FIXME (#5527): These should be associated constants + /// returns the smallest finite number this type can represent + fn min_value() -> Self; + /// returns the largest finite number this type can represent + fn max_value() -> Self; +} + +macro_rules! bounded_impl { + ($t:ty, $min:expr, $max:expr) => { + impl Bounded for $t { + #[inline] + fn min_value() -> $t { $min } + + #[inline] + fn max_value() -> $t { $max } + } + } +} + +bounded_impl!(usize, usize::MIN, usize::MAX); +bounded_impl!(u8, u8::MIN, u8::MAX); +bounded_impl!(u16, u16::MIN, u16::MAX); +bounded_impl!(u32, u32::MIN, u32::MAX); +bounded_impl!(u64, u64::MIN, u64::MAX); + +bounded_impl!(isize, isize::MIN, isize::MAX); +bounded_impl!(i8, i8::MIN, i8::MAX); +bounded_impl!(i16, i16::MIN, i16::MAX); +bounded_impl!(i32, i32::MIN, i32::MAX); +bounded_impl!(i64, i64::MIN, i64::MAX); + +bounded_impl!(f32, f32::MIN, f32::MAX); + +macro_rules! for_each_tuple_ { + ( $m:ident !! ) => ( + $m! { } + ); + ( $m:ident !! $h:ident, $($t:ident,)* ) => ( + $m! { $h $($t)* } + for_each_tuple_! { $m !! $($t,)* } + ); +} +macro_rules! for_each_tuple { + ( $m:ident ) => ( + for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, } + ); +} + +macro_rules! bounded_tuple { + ( $($name:ident)* ) => ( + impl<$($name: Bounded,)*> Bounded for ($($name,)*) { + fn min_value() -> Self { + ($($name::min_value(),)*) + } + fn max_value() -> Self { + ($($name::max_value(),)*) + } + } + ); +} + +for_each_tuple!(bounded_tuple); +bounded_impl!(f64, f64::MIN, f64::MAX); diff --git a/traits/src/cast.rs b/traits/src/cast.rs new file mode 100644 index 0000000..90b99ef --- /dev/null +++ b/traits/src/cast.rs @@ -0,0 +1,434 @@ +use std::mem::size_of; + +use identities::Zero; +use bounds::Bounded; + +/// A generic trait for converting a value to a number. +pub trait ToPrimitive { + /// Converts the value of `self` to an `isize`. + #[inline] + fn to_isize(&self) -> Option { + self.to_i64().and_then(|x| x.to_isize()) + } + + /// Converts the value of `self` to an `i8`. + #[inline] + fn to_i8(&self) -> Option { + self.to_i64().and_then(|x| x.to_i8()) + } + + /// Converts the value of `self` to an `i16`. + #[inline] + fn to_i16(&self) -> Option { + self.to_i64().and_then(|x| x.to_i16()) + } + + /// Converts the value of `self` to an `i32`. + #[inline] + fn to_i32(&self) -> Option { + self.to_i64().and_then(|x| x.to_i32()) + } + + /// Converts the value of `self` to an `i64`. + fn to_i64(&self) -> Option; + + /// Converts the value of `self` to a `usize`. + #[inline] + fn to_usize(&self) -> Option { + self.to_u64().and_then(|x| x.to_usize()) + } + + /// Converts the value of `self` to an `u8`. + #[inline] + fn to_u8(&self) -> Option { + self.to_u64().and_then(|x| x.to_u8()) + } + + /// Converts the value of `self` to an `u16`. + #[inline] + fn to_u16(&self) -> Option { + self.to_u64().and_then(|x| x.to_u16()) + } + + /// Converts the value of `self` to an `u32`. + #[inline] + fn to_u32(&self) -> Option { + self.to_u64().and_then(|x| x.to_u32()) + } + + /// Converts the value of `self` to an `u64`. + #[inline] + fn to_u64(&self) -> Option; + + /// Converts the value of `self` to an `f32`. + #[inline] + fn to_f32(&self) -> Option { + self.to_f64().and_then(|x| x.to_f32()) + } + + /// Converts the value of `self` to an `f64`. + #[inline] + fn to_f64(&self) -> Option { + self.to_i64().and_then(|x| x.to_f64()) + } +} + +macro_rules! impl_to_primitive_int_to_int { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let n = $slf as i64; + let min_value: $DstT = Bounded::min_value(); + let max_value: $DstT = Bounded::max_value(); + if min_value as i64 <= n && n <= max_value as i64 { + Some($slf as $DstT) + } else { + None + } + } + } + ) +} + +macro_rules! impl_to_primitive_int_to_uint { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + let zero: $SrcT = Zero::zero(); + let max_value: $DstT = Bounded::max_value(); + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_int { + ($T:ty) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option { impl_to_primitive_int_to_int!($T, isize, *self) } + #[inline] + fn to_i8(&self) -> Option { impl_to_primitive_int_to_int!($T, i8, *self) } + #[inline] + fn to_i16(&self) -> Option { impl_to_primitive_int_to_int!($T, i16, *self) } + #[inline] + fn to_i32(&self) -> Option { impl_to_primitive_int_to_int!($T, i32, *self) } + #[inline] + fn to_i64(&self) -> Option { impl_to_primitive_int_to_int!($T, i64, *self) } + + #[inline] + fn to_usize(&self) -> Option { impl_to_primitive_int_to_uint!($T, usize, *self) } + #[inline] + fn to_u8(&self) -> Option { impl_to_primitive_int_to_uint!($T, u8, *self) } + #[inline] + fn to_u16(&self) -> Option { impl_to_primitive_int_to_uint!($T, u16, *self) } + #[inline] + fn to_u32(&self) -> Option { impl_to_primitive_int_to_uint!($T, u32, *self) } + #[inline] + fn to_u64(&self) -> Option { impl_to_primitive_int_to_uint!($T, u64, *self) } + + #[inline] + fn to_f32(&self) -> Option { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option { Some(*self as f64) } + } + ) +} + +impl_to_primitive_int!(isize); +impl_to_primitive_int!(i8); +impl_to_primitive_int!(i16); +impl_to_primitive_int!(i32); +impl_to_primitive_int!(i64); + +macro_rules! impl_to_primitive_uint_to_int { + ($DstT:ty, $slf:expr) => ( + { + let max_value: $DstT = Bounded::max_value(); + if $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_uint_to_uint { + ($SrcT:ty, $DstT:ty, $slf:expr) => ( + { + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let zero: $SrcT = Zero::zero(); + let max_value: $DstT = Bounded::max_value(); + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) + } else { + None + } + } + } + ) +} + +macro_rules! impl_to_primitive_uint { + ($T:ty) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option { impl_to_primitive_uint_to_int!(isize, *self) } + #[inline] + fn to_i8(&self) -> Option { impl_to_primitive_uint_to_int!(i8, *self) } + #[inline] + fn to_i16(&self) -> Option { impl_to_primitive_uint_to_int!(i16, *self) } + #[inline] + fn to_i32(&self) -> Option { impl_to_primitive_uint_to_int!(i32, *self) } + #[inline] + fn to_i64(&self) -> Option { impl_to_primitive_uint_to_int!(i64, *self) } + + #[inline] + fn to_usize(&self) -> Option { + impl_to_primitive_uint_to_uint!($T, usize, *self) + } + #[inline] + fn to_u8(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u8, *self) } + #[inline] + fn to_u16(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u16, *self) } + #[inline] + fn to_u32(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u32, *self) } + #[inline] + fn to_u64(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u64, *self) } + + #[inline] + fn to_f32(&self) -> Option { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option { Some(*self as f64) } + } + ) +} + +impl_to_primitive_uint!(usize); +impl_to_primitive_uint!(u8); +impl_to_primitive_uint!(u16); +impl_to_primitive_uint!(u32); +impl_to_primitive_uint!(u64); + +macro_rules! impl_to_primitive_float_to_float { + ($SrcT:ident, $DstT:ident, $slf:expr) => ( + if size_of::<$SrcT>() <= size_of::<$DstT>() { + Some($slf as $DstT) + } else { + let n = $slf as f64; + let max_value: $SrcT = ::std::$SrcT::MAX; + if -max_value as f64 <= n && n <= max_value as f64 { + Some($slf as $DstT) + } else { + None + } + } + ) +} + +macro_rules! impl_to_primitive_float { + ($T:ident) => ( + impl ToPrimitive for $T { + #[inline] + fn to_isize(&self) -> Option { Some(*self as isize) } + #[inline] + fn to_i8(&self) -> Option { Some(*self as i8) } + #[inline] + fn to_i16(&self) -> Option { Some(*self as i16) } + #[inline] + fn to_i32(&self) -> Option { Some(*self as i32) } + #[inline] + fn to_i64(&self) -> Option { Some(*self as i64) } + + #[inline] + fn to_usize(&self) -> Option { Some(*self as usize) } + #[inline] + fn to_u8(&self) -> Option { Some(*self as u8) } + #[inline] + fn to_u16(&self) -> Option { Some(*self as u16) } + #[inline] + fn to_u32(&self) -> Option { Some(*self as u32) } + #[inline] + fn to_u64(&self) -> Option { Some(*self as u64) } + + #[inline] + fn to_f32(&self) -> Option { impl_to_primitive_float_to_float!($T, f32, *self) } + #[inline] + fn to_f64(&self) -> Option { impl_to_primitive_float_to_float!($T, f64, *self) } + } + ) +} + +impl_to_primitive_float!(f32); +impl_to_primitive_float!(f64); + +/// A generic trait for converting a number to a value. +pub trait FromPrimitive: Sized { + /// Convert an `isize` to return an optional value of this type. If the + /// value cannot be represented by this value, the `None` is returned. + #[inline] + fn from_isize(n: isize) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i8` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i8(n: i8) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i16` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i16(n: i16) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i32(n: i32) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + fn from_i64(n: i64) -> Option; + + /// Convert a `usize` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_usize(n: usize) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u8` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u8(n: u8) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u16` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u16(n: u16) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u32(n: u32) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + fn from_u64(n: u64) -> Option; + + /// Convert a `f32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_f32(n: f32) -> Option { + FromPrimitive::from_f64(n as f64) + } + + /// Convert a `f64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_f64(n: f64) -> Option { + FromPrimitive::from_i64(n as i64) + } +} + +macro_rules! impl_from_primitive { + ($T:ty, $to_ty:ident) => ( + #[allow(deprecated)] + impl FromPrimitive for $T { + #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } + } + ) +} + +impl_from_primitive!(isize, to_isize); +impl_from_primitive!(i8, to_i8); +impl_from_primitive!(i16, to_i16); +impl_from_primitive!(i32, to_i32); +impl_from_primitive!(i64, to_i64); +impl_from_primitive!(usize, to_usize); +impl_from_primitive!(u8, to_u8); +impl_from_primitive!(u16, to_u16); +impl_from_primitive!(u32, to_u32); +impl_from_primitive!(u64, to_u64); +impl_from_primitive!(f32, to_f32); +impl_from_primitive!(f64, to_f64); + +/// Cast from one machine scalar to another. +/// +/// # Examples +/// +/// ``` +/// use num; +/// +/// let twenty: f32 = num::cast(0x14).unwrap(); +/// assert_eq!(twenty, 20f32); +/// ``` +/// +#[inline] +pub fn cast(n: T) -> Option { + NumCast::from(n) +} + +/// An interface for casting between machine scalars. +pub trait NumCast: Sized + ToPrimitive { + /// Creates a number from another value that can be converted into + /// a primitive via the `ToPrimitive` trait. + fn from(n: T) -> Option; +} + +macro_rules! impl_num_cast { + ($T:ty, $conv:ident) => ( + impl NumCast for $T { + #[inline] + #[allow(deprecated)] + fn from(n: N) -> Option<$T> { + // `$conv` could be generated using `concat_idents!`, but that + // macro seems to be broken at the moment + n.$conv() + } + } + ) +} + +impl_num_cast!(u8, to_u8); +impl_num_cast!(u16, to_u16); +impl_num_cast!(u32, to_u32); +impl_num_cast!(u64, to_u64); +impl_num_cast!(usize, to_usize); +impl_num_cast!(i8, to_i8); +impl_num_cast!(i16, to_i16); +impl_num_cast!(i32, to_i32); +impl_num_cast!(i64, to_i64); +impl_num_cast!(isize, to_isize); +impl_num_cast!(f32, to_f32); +impl_num_cast!(f64, to_f64); diff --git a/traits/src/float.rs b/traits/src/float.rs new file mode 100644 index 0000000..5d1f0e0 --- /dev/null +++ b/traits/src/float.rs @@ -0,0 +1,1126 @@ +use std::mem; +use std::ops::Neg; +use std::num::FpCategory; + +use {Num, NumCast}; + +pub trait Float + : Num + + Copy + + NumCast + + PartialOrd + + Neg +{ + /// Returns the `NaN` value. + /// + /// ``` + /// use num::traits::Float; + /// + /// let nan: f32 = Float::nan(); + /// + /// assert!(nan.is_nan()); + /// ``` + fn nan() -> Self; + /// Returns the infinite value. + /// + /// ``` + /// use num::traits::Float; + /// use std::f32; + /// + /// let infinity: f32 = Float::infinity(); + /// + /// assert!(infinity.is_infinite()); + /// assert!(!infinity.is_finite()); + /// assert!(infinity > f32::MAX); + /// ``` + fn infinity() -> Self; + /// Returns the negative infinite value. + /// + /// ``` + /// use num::traits::Float; + /// use std::f32; + /// + /// let neg_infinity: f32 = Float::neg_infinity(); + /// + /// assert!(neg_infinity.is_infinite()); + /// assert!(!neg_infinity.is_finite()); + /// assert!(neg_infinity < f32::MIN); + /// ``` + fn neg_infinity() -> Self; + /// Returns `-0.0`. + /// + /// ``` + /// use num::traits::{Zero, Float}; + /// + /// let inf: f32 = Float::infinity(); + /// let zero: f32 = Zero::zero(); + /// let neg_zero: f32 = Float::neg_zero(); + /// + /// assert_eq!(zero, neg_zero); + /// assert_eq!(7.0f32/inf, zero); + /// assert_eq!(zero * 10.0, zero); + /// ``` + fn neg_zero() -> Self; + + /// Returns the smallest finite value that this type can represent. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_value(); + /// + /// assert_eq!(x, f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_positive_value(); + /// + /// assert_eq!(x, f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns the largest finite value that this type can represent. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::max_value(); + /// assert_eq!(x, f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns `true` if this value is `NaN` and false otherwise. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let nan = f64::NAN; + /// let f = 7.0; + /// + /// assert!(nan.is_nan()); + /// assert!(!f.is_nan()); + /// ``` + fn is_nan(self) -> bool; + + /// Returns `true` if this value is positive infinity or negative infinity and + /// false otherwise. + /// + /// ``` + /// use num::traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(!f.is_infinite()); + /// assert!(!nan.is_infinite()); + /// + /// assert!(inf.is_infinite()); + /// assert!(neg_inf.is_infinite()); + /// ``` + fn is_infinite(self) -> bool; + + /// Returns `true` if this number is neither infinite nor `NaN`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(f.is_finite()); + /// + /// assert!(!nan.is_finite()); + /// assert!(!inf.is_finite()); + /// assert!(!neg_inf.is_finite()); + /// ``` + fn is_finite(self) -> bool; + + /// Returns `true` if the number is neither zero, infinite, + /// [subnormal][subnormal], or `NaN`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f32; + /// + /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 + /// let max = f32::MAX; + /// let lower_than_min = 1.0e-40_f32; + /// let zero = 0.0f32; + /// + /// assert!(min.is_normal()); + /// assert!(max.is_normal()); + /// + /// assert!(!zero.is_normal()); + /// assert!(!f32::NAN.is_normal()); + /// assert!(!f32::INFINITY.is_normal()); + /// // Values between `0` and `min` are Subnormal. + /// assert!(!lower_than_min.is_normal()); + /// ``` + /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number + fn is_normal(self) -> bool; + + /// Returns the floating point category of the number. If only one property + /// is going to be tested, it is generally faster to use the specific + /// predicate instead. + /// + /// ``` + /// use num::traits::Float; + /// use std::num::FpCategory; + /// use std::f32; + /// + /// let num = 12.4f32; + /// let inf = f32::INFINITY; + /// + /// assert_eq!(num.classify(), FpCategory::Normal); + /// assert_eq!(inf.classify(), FpCategory::Infinite); + /// ``` + fn classify(self) -> FpCategory; + + /// Returns the largest integer less than or equal to a number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 3.99; + /// let g = 3.0; + /// + /// assert_eq!(f.floor(), 3.0); + /// assert_eq!(g.floor(), 3.0); + /// ``` + fn floor(self) -> Self; + + /// Returns the smallest integer greater than or equal to a number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 3.01; + /// let g = 4.0; + /// + /// assert_eq!(f.ceil(), 4.0); + /// assert_eq!(g.ceil(), 4.0); + /// ``` + fn ceil(self) -> Self; + + /// Returns the nearest integer to a number. Round half-way cases away from + /// `0.0`. + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 3.3; + /// let g = -3.3; + /// + /// assert_eq!(f.round(), 3.0); + /// assert_eq!(g.round(), -3.0); + /// ``` + fn round(self) -> Self; + + /// Return the integer part of a number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 3.3; + /// let g = -3.7; + /// + /// assert_eq!(f.trunc(), 3.0); + /// assert_eq!(g.trunc(), -3.0); + /// ``` + fn trunc(self) -> Self; + + /// Returns the fractional part of a number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 3.5; + /// let y = -3.5; + /// let abs_difference_x = (x.fract() - 0.5).abs(); + /// let abs_difference_y = (y.fract() - (-0.5)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn fract(self) -> Self; + + /// Computes the absolute value of `self`. Returns `Float::nan()` if the + /// number is `Float::nan()`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = 3.5; + /// let y = -3.5; + /// + /// let abs_difference_x = (x.abs() - x).abs(); + /// let abs_difference_y = (y.abs() - (-y)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// + /// assert!(f64::NAN.abs().is_nan()); + /// ``` + fn abs(self) -> Self; + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` + /// - `Float::nan()` if the number is `Float::nan()` + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let f = 3.5; + /// + /// assert_eq!(f.signum(), 1.0); + /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); + /// + /// assert!(f64::NAN.signum().is_nan()); + /// ``` + fn signum(self) -> Self; + + /// Returns `true` if `self` is positive, including `+0.0` and + /// `Float::infinity()`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let nan: f64 = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(f.is_sign_positive()); + /// assert!(!g.is_sign_positive()); + /// // Requires both tests to determine if is `NaN` + /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative()); + /// ``` + fn is_sign_positive(self) -> bool; + + /// Returns `true` if `self` is negative, including `-0.0` and + /// `Float::neg_infinity()`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let nan = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(!f.is_sign_negative()); + /// assert!(g.is_sign_negative()); + /// // Requires both tests to determine if is `NaN`. + /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative()); + /// ``` + fn is_sign_negative(self) -> bool; + + /// Fused multiply-add. Computes `(self * a) + b` with only one rounding + /// error. This produces a more accurate result with better performance than + /// a separate multiplication operation followed by an add. + /// + /// ``` + /// use num::traits::Float; + /// + /// let m = 10.0; + /// let x = 4.0; + /// let b = 60.0; + /// + /// // 100.0 + /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn mul_add(self, a: Self, b: Self) -> Self; + /// Take the reciprocal (inverse) of a number, `1/x`. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.recip() - (1.0/x)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn recip(self) -> Self; + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powi(2) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powi(self, n: i32) -> Self; + + /// Raise a number to a floating point power. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powf(2.0) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powf(self, n: Self) -> Self; + + /// Take the square root of a number. + /// + /// Returns NaN if `self` is a negative number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let positive = 4.0; + /// let negative = -4.0; + /// + /// let abs_difference = (positive.sqrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// assert!(negative.sqrt().is_nan()); + /// ``` + fn sqrt(self) -> Self; + + /// Returns `e^(self)`, (the exponential function). + /// + /// ``` + /// use num::traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp(self) -> Self; + + /// Returns `2^(self)`. + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 2.0; + /// + /// // 2^2 - 4 == 0 + /// let abs_difference = (f.exp2() - 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp2(self) -> Self; + + /// Returns the natural logarithm of the number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln(self) -> Self; + + /// Returns the logarithm of the number with respect to an arbitrary base. + /// + /// ``` + /// use num::traits::Float; + /// + /// let ten = 10.0; + /// let two = 2.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); + /// + /// // log2(2) - 1 == 0 + /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); + /// + /// assert!(abs_difference_10 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn log(self, base: Self) -> Self; + + /// Returns the base 2 logarithm of the number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let two = 2.0; + /// + /// // log2(2) - 1 == 0 + /// let abs_difference = (two.log2() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log2(self) -> Self; + + /// Returns the base 10 logarithm of the number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let ten = 10.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference = (ten.log10() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log10(self) -> Self; + + /// Returns the maximum of the two numbers. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.max(y), y); + /// ``` + fn max(self, other: Self) -> Self; + + /// Returns the minimum of the two numbers. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.min(y), x); + /// ``` + fn min(self, other: Self) -> Self; + + /// The positive difference of two numbers. + /// + /// * If `self <= other`: `0:0` + /// * Else: `self - other` + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 3.0; + /// let y = -3.0; + /// + /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); + /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn abs_sub(self, other: Self) -> Self; + + /// Take the cubic root of a number. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 8.0; + /// + /// // x^(1/3) - 2 == 0 + /// let abs_difference = (x.cbrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cbrt(self) -> Self; + + /// Calculate the length of the hypotenuse of a right-angle triangle given + /// legs of length `x` and `y`. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 2.0; + /// let y = 3.0; + /// + /// // sqrt(x^2 + y^2) + /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn hypot(self, other: Self) -> Self; + + /// Computes the sine of a number (in radians). + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/2.0; + /// + /// let abs_difference = (x.sin() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sin(self) -> Self; + + /// Computes the cosine of a number (in radians). + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = 2.0*f64::consts::PI; + /// + /// let abs_difference = (x.cos() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cos(self) -> Self; + + /// Computes the tangent of a number (in radians). + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let abs_difference = (x.tan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-14); + /// ``` + fn tan(self) -> Self; + + /// Computes the arcsine of a number. Return value is in radians in + /// the range [-pi/2, pi/2] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 2.0; + /// + /// // asin(sin(pi/2)) + /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn asin(self) -> Self; + + /// Computes the arccosine of a number. Return value is in radians in + /// the range [0, pi] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 4.0; + /// + /// // acos(cos(pi/4)) + /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn acos(self) -> Self; + + /// Computes the arctangent of a number. Return value is in radians in the + /// range [-pi/2, pi/2]; + /// + /// ``` + /// use num::traits::Float; + /// + /// let f = 1.0; + /// + /// // atan(tan(1)) + /// let abs_difference = (f.tan().atan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn atan(self) -> Self; + + /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). + /// + /// * `x = 0`, `y = 0`: `0` + /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` + /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` + /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let pi = f64::consts::PI; + /// // All angles from horizontal right (+x) + /// // 45 deg counter-clockwise + /// let x1 = 3.0; + /// let y1 = -3.0; + /// + /// // 135 deg clockwise + /// let x2 = -3.0; + /// let y2 = 3.0; + /// + /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); + /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); + /// + /// assert!(abs_difference_1 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn atan2(self, other: Self) -> Self; + + /// Simultaneously computes the sine and cosine of the number, `x`. Returns + /// `(sin(x), cos(x))`. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let f = x.sin_cos(); + /// + /// let abs_difference_0 = (f.0 - x.sin()).abs(); + /// let abs_difference_1 = (f.1 - x.cos()).abs(); + /// + /// assert!(abs_difference_0 < 1e-10); + /// assert!(abs_difference_0 < 1e-10); + /// ``` + fn sin_cos(self) -> (Self, Self); + + /// Returns `e^(self) - 1` in a way that is accurate even if the + /// number is close to zero. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 7.0; + /// + /// // e^(ln(7)) - 1 + /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp_m1(self) -> Self; + + /// Returns `ln(1+n)` (natural logarithm) more accurately than if + /// the operations were performed separately. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::E - 1.0; + /// + /// // ln(1 + (e - 1)) == ln(e) == 1 + /// let abs_difference = (x.ln_1p() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln_1p(self) -> Self; + + /// Hyperbolic sine function. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.sinh(); + /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` + /// let g = (e*e - 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sinh(self) -> Self; + + /// Hyperbolic cosine function. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// let f = x.cosh(); + /// // Solving cosh() at 1 gives this result + /// let g = (e*e + 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// // Same result + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn cosh(self) -> Self; + + /// Hyperbolic tangent function. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.tanh(); + /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` + /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn tanh(self) -> Self; + + /// Inverse hyperbolic sine function. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 1.0; + /// let f = x.sinh().asinh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn asinh(self) -> Self; + + /// Inverse hyperbolic cosine function. + /// + /// ``` + /// use num::traits::Float; + /// + /// let x = 1.0; + /// let f = x.cosh().acosh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn acosh(self) -> Self; + + /// Inverse hyperbolic tangent function. + /// + /// ``` + /// use num::traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let f = e.tanh().atanh(); + /// + /// let abs_difference = (f - e).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn atanh(self) -> Self; + + + /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. + /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. + /// The floating point encoding is documented in the [Reference][floating-point]. + /// + /// ``` + /// use num::traits::Float; + /// + /// let num = 2.0f32; + /// + /// // (8388608, -22, 1) + /// let (mantissa, exponent, sign) = Float::integer_decode(num); + /// let sign_f = sign as f32; + /// let mantissa_f = mantissa as f32; + /// let exponent_f = num.powf(exponent as f32); + /// + /// // 1 * 8388608 * 2^(-22) == 2 + /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + /// [floating-point]: ../../../../../reference.html#machine-types + fn integer_decode(self) -> (u64, i16, i8); +} + +macro_rules! float_impl { + ($T:ident $decode:ident) => ( + impl Float for $T { + fn nan() -> Self { + ::std::$T::NAN + } + + fn infinity() -> Self { + ::std::$T::INFINITY + } + + fn neg_infinity() -> Self { + ::std::$T::NEG_INFINITY + } + + fn neg_zero() -> Self { + -0.0 + } + + fn min_value() -> Self { + ::std::$T::MIN + } + + fn min_positive_value() -> Self { + ::std::$T::MIN_POSITIVE + } + + fn max_value() -> Self { + ::std::$T::MAX + } + + fn is_nan(self) -> bool { + <$T>::is_nan(self) + } + + fn is_infinite(self) -> bool { + <$T>::is_infinite(self) + } + + fn is_finite(self) -> bool { + <$T>::is_finite(self) + } + + fn is_normal(self) -> bool { + <$T>::is_normal(self) + } + + fn classify(self) -> FpCategory { + <$T>::classify(self) + } + + fn floor(self) -> Self { + <$T>::floor(self) + } + + fn ceil(self) -> Self { + <$T>::ceil(self) + } + + fn round(self) -> Self { + <$T>::round(self) + } + + fn trunc(self) -> Self { + <$T>::trunc(self) + } + + fn fract(self) -> Self { + <$T>::fract(self) + } + + fn abs(self) -> Self { + <$T>::abs(self) + } + + fn signum(self) -> Self { + <$T>::signum(self) + } + + fn is_sign_positive(self) -> bool { + <$T>::is_sign_positive(self) + } + + fn is_sign_negative(self) -> bool { + <$T>::is_sign_negative(self) + } + + fn mul_add(self, a: Self, b: Self) -> Self { + <$T>::mul_add(self, a, b) + } + + fn recip(self) -> Self { + <$T>::recip(self) + } + + fn powi(self, n: i32) -> Self { + <$T>::powi(self, n) + } + + fn powf(self, n: Self) -> Self { + <$T>::powf(self, n) + } + + fn sqrt(self) -> Self { + <$T>::sqrt(self) + } + + fn exp(self) -> Self { + <$T>::exp(self) + } + + fn exp2(self) -> Self { + <$T>::exp2(self) + } + + fn ln(self) -> Self { + <$T>::ln(self) + } + + fn log(self, base: Self) -> Self { + <$T>::log(self, base) + } + + fn log2(self) -> Self { + <$T>::log2(self) + } + + fn log10(self) -> Self { + <$T>::log10(self) + } + + fn max(self, other: Self) -> Self { + <$T>::max(self, other) + } + + fn min(self, other: Self) -> Self { + <$T>::min(self, other) + } + + fn abs_sub(self, other: Self) -> Self { + <$T>::abs_sub(self, other) + } + + fn cbrt(self) -> Self { + <$T>::cbrt(self) + } + + fn hypot(self, other: Self) -> Self { + <$T>::hypot(self, other) + } + + fn sin(self) -> Self { + <$T>::sin(self) + } + + fn cos(self) -> Self { + <$T>::cos(self) + } + + fn tan(self) -> Self { + <$T>::tan(self) + } + + fn asin(self) -> Self { + <$T>::asin(self) + } + + fn acos(self) -> Self { + <$T>::acos(self) + } + + fn atan(self) -> Self { + <$T>::atan(self) + } + + fn atan2(self, other: Self) -> Self { + <$T>::atan2(self, other) + } + + fn sin_cos(self) -> (Self, Self) { + <$T>::sin_cos(self) + } + + fn exp_m1(self) -> Self { + <$T>::exp_m1(self) + } + + fn ln_1p(self) -> Self { + <$T>::ln_1p(self) + } + + fn sinh(self) -> Self { + <$T>::sinh(self) + } + + fn cosh(self) -> Self { + <$T>::cosh(self) + } + + fn tanh(self) -> Self { + <$T>::tanh(self) + } + + fn asinh(self) -> Self { + <$T>::asinh(self) + } + + fn acosh(self) -> Self { + <$T>::acosh(self) + } + + fn atanh(self) -> Self { + <$T>::atanh(self) + } + + fn integer_decode(self) -> (u64, i16, i8) { + $decode(self) + } + } + ) +} + +fn integer_decode_f32(f: f32) -> (u64, i16, i8) { + let bits: u32 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 31 == 0 { + 1 + } else { + -1 + }; + let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; + let mantissa = if exponent == 0 { + (bits & 0x7fffff) << 1 + } else { + (bits & 0x7fffff) | 0x800000 + }; + // Exponent bias + mantissa shift + exponent -= 127 + 23; + (mantissa as u64, exponent, sign) +} + +fn integer_decode_f64(f: f64) -> (u64, i16, i8) { + let bits: u64 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 63 == 0 { + 1 + } else { + -1 + }; + let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; + let mantissa = if exponent == 0 { + (bits & 0xfffffffffffff) << 1 + } else { + (bits & 0xfffffffffffff) | 0x10000000000000 + }; + // Exponent bias + mantissa shift + exponent -= 1023 + 52; + (mantissa, exponent, sign) +} + +float_impl!(f32 integer_decode_f32); +float_impl!(f64 integer_decode_f64); diff --git a/traits/src/identities.rs b/traits/src/identities.rs new file mode 100644 index 0000000..0fee84a --- /dev/null +++ b/traits/src/identities.rs @@ -0,0 +1,95 @@ +use std::ops::{Add, Mul}; + +/// Defines an additive identity element for `Self`. +pub trait Zero: Sized + Add { + /// Returns the additive identity element of `Self`, `0`. + /// + /// # Laws + /// + /// ```{.text} + /// a + 0 = a ∀ a ∈ Self + /// 0 + a = a ∀ a ∈ Self + /// ``` + /// + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // FIXME (#5527): This should be an associated constant + fn zero() -> Self; + + /// Returns `true` if `self` is equal to the additive identity. + #[inline] + fn is_zero(&self) -> bool; +} + +macro_rules! zero_impl { + ($t:ty, $v:expr) => { + impl Zero for $t { + #[inline] + fn zero() -> $t { $v } + #[inline] + fn is_zero(&self) -> bool { *self == $v } + } + } +} + +zero_impl!(usize, 0usize); +zero_impl!(u8, 0u8); +zero_impl!(u16, 0u16); +zero_impl!(u32, 0u32); +zero_impl!(u64, 0u64); + +zero_impl!(isize, 0isize); +zero_impl!(i8, 0i8); +zero_impl!(i16, 0i16); +zero_impl!(i32, 0i32); +zero_impl!(i64, 0i64); + +zero_impl!(f32, 0.0f32); +zero_impl!(f64, 0.0f64); + +/// Defines a multiplicative identity element for `Self`. +pub trait One: Sized + Mul { + /// Returns the multiplicative identity element of `Self`, `1`. + /// + /// # Laws + /// + /// ```{.text} + /// a * 1 = a ∀ a ∈ Self + /// 1 * a = a ∀ a ∈ Self + /// ``` + /// + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // FIXME (#5527): This should be an associated constant + fn one() -> Self; +} + +macro_rules! one_impl { + ($t:ty, $v:expr) => { + impl One for $t { + #[inline] + fn one() -> $t { $v } + } + } +} + +one_impl!(usize, 1usize); +one_impl!(u8, 1u8); +one_impl!(u16, 1u16); +one_impl!(u32, 1u32); +one_impl!(u64, 1u64); + +one_impl!(isize, 1isize); +one_impl!(i8, 1i8); +one_impl!(i16, 1i16); +one_impl!(i32, 1i32); +one_impl!(i64, 1i64); + +one_impl!(f32, 1.0f32); +one_impl!(f64, 1.0f64); diff --git a/traits/src/int.rs b/traits/src/int.rs new file mode 100644 index 0000000..071df7f --- /dev/null +++ b/traits/src/int.rs @@ -0,0 +1,360 @@ +use std::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; + +use {Num, NumCast}; +use bounds::Bounded; +use ops::checked::*; +use ops::saturating::Saturating; + +pub trait PrimInt + : Sized + + Copy + + Num + NumCast + + Bounded + + PartialOrd + Ord + Eq + + Not + + BitAnd + + BitOr + + BitXor + + Shl + + Shr + + CheckedAdd + + CheckedSub + + CheckedMul + + CheckedDiv + + Saturating +{ + /// Returns the number of ones in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_ones(), 3); + /// ``` + fn count_ones(self) -> u32; + + /// Returns the number of zeros in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_zeros(), 5); + /// ``` + fn count_zeros(self) -> u32; + + /// Returns the number of leading zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.leading_zeros(), 10); + /// ``` + fn leading_zeros(self) -> u32; + + /// Returns the number of trailing zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.trailing_zeros(), 3); + /// ``` + fn trailing_zeros(self) -> u32; + + /// Shifts the bits to the left by a specified amount amount, `n`, wrapping + /// the truncated bits to the end of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF012u64; + /// + /// assert_eq!(n.rotate_left(12), m); + /// ``` + fn rotate_left(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, wrapping + /// the truncated bits to the beginning of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xDEF0123456789ABCu64; + /// + /// assert_eq!(n.rotate_right(12), m); + /// ``` + fn rotate_right(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to signed `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF000u64; + /// + /// assert_eq!(n.signed_shl(12), m); + /// ``` + fn signed_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, copying + /// the "sign bit" in the most significant bits even for unsigned types. + /// + /// This is bitwise equivalent to signed `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0xFEDCBA9876543210u64; + /// let m = 0xFFFFEDCBA9876543u64; + /// + /// assert_eq!(n.signed_shr(12), m); + /// ``` + fn signed_shr(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to unsigned `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFi64; + /// let m = 0x3456789ABCDEF000i64; + /// + /// assert_eq!(n.unsigned_shl(12), m); + /// ``` + fn unsigned_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, filling + /// zeros in the most significant bits. + /// + /// This is bitwise equivalent to unsigned `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0xFEDCBA9876543210i64; + /// let m = 0x000FEDCBA9876543i64; + /// + /// assert_eq!(n.unsigned_shr(12), m); + /// ``` + fn unsigned_shr(self, n: u32) -> Self; + + /// Reverses the byte order of the integer. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xEFCDAB8967452301u64; + /// + /// assert_eq!(n.swap_bytes(), m); + /// ``` + fn swap_bytes(self) -> Self; + + /// Convert an integer from big endian to the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(u64::from_be(n), n) + /// } else { + /// assert_eq!(u64::from_be(n), n.swap_bytes()) + /// } + /// ``` + fn from_be(x: Self) -> Self; + + /// Convert an integer from little endian to the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(u64::from_le(n), n) + /// } else { + /// assert_eq!(u64::from_le(n), n.swap_bytes()) + /// } + /// ``` + fn from_le(x: Self) -> Self; + + /// Convert `self` to big endian from the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(n.to_be(), n) + /// } else { + /// assert_eq!(n.to_be(), n.swap_bytes()) + /// } + /// ``` + fn to_be(self) -> Self; + + /// Convert `self` to little endian from the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(n.to_le(), n) + /// } else { + /// assert_eq!(n.to_le(), n.swap_bytes()) + /// } + /// ``` + fn to_le(self) -> Self; + + /// Raises self to the power of `exp`, using exponentiation by squaring. + /// + /// # Examples + /// + /// ``` + /// use num::traits::PrimInt; + /// + /// assert_eq!(2i32.pow(4), 16); + /// ``` + fn pow(self, mut exp: u32) -> Self; +} + +macro_rules! prim_int_impl { + ($T:ty, $S:ty, $U:ty) => ( + impl PrimInt for $T { + fn count_ones(self) -> u32 { + <$T>::count_ones(self) + } + + fn count_zeros(self) -> u32 { + <$T>::count_zeros(self) + } + + fn leading_zeros(self) -> u32 { + <$T>::leading_zeros(self) + } + + fn trailing_zeros(self) -> u32 { + <$T>::trailing_zeros(self) + } + + fn rotate_left(self, n: u32) -> Self { + <$T>::rotate_left(self, n) + } + + fn rotate_right(self, n: u32) -> Self { + <$T>::rotate_right(self, n) + } + + fn signed_shl(self, n: u32) -> Self { + ((self as $S) << n) as $T + } + + fn signed_shr(self, n: u32) -> Self { + ((self as $S) >> n) as $T + } + + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + + fn swap_bytes(self) -> Self { + <$T>::swap_bytes(self) + } + + fn from_be(x: Self) -> Self { + <$T>::from_be(x) + } + + fn from_le(x: Self) -> Self { + <$T>::from_le(x) + } + + fn to_be(self) -> Self { + <$T>::to_be(self) + } + + fn to_le(self) -> Self { + <$T>::to_le(self) + } + + fn pow(self, exp: u32) -> Self { + <$T>::pow(self, exp) + } + } + ) +} + +// prim_int_impl!(type, signed, unsigned); +prim_int_impl!(u8, i8, u8); +prim_int_impl!(u16, i16, u16); +prim_int_impl!(u32, i32, u32); +prim_int_impl!(u64, i64, u64); +prim_int_impl!(usize, isize, usize); +prim_int_impl!(i8, i8, u8); +prim_int_impl!(i16, i16, u16); +prim_int_impl!(i32, i32, u32); +prim_int_impl!(i64, i64, u64); +prim_int_impl!(isize, isize, usize); diff --git a/traits/src/lib.rs b/traits/src/lib.rs new file mode 100644 index 0000000..9665094 --- /dev/null +++ b/traits/src/lib.rs @@ -0,0 +1,215 @@ +// Copyright 2013-2014 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. + +//! Numeric traits for generic mathematics + +use std::ops::{Add, Sub, Mul, Div, Rem}; + +pub use bounds::Bounded; +pub use float::Float; +pub use identities::{Zero, One}; +pub use ops::checked::*; +pub use ops::saturating::Saturating; +pub use sign::{Signed, Unsigned}; +pub use int::PrimInt; +pub use cast::*; + +mod identities; +mod sign; +mod ops; +mod bounds; +mod float; +mod int; +mod cast; + +/// The base trait for numeric types +pub trait Num: PartialEq + Zero + One + + Add + Sub + + Mul + Div + Rem +{ + type Error; + + /// Convert from a string and radix <= 36. + fn from_str_radix(str: &str, radix: u32) -> Result; +} + +macro_rules! int_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t { + type Error = ::std::num::ParseIntError; + fn from_str_radix(s: &str, radix: u32) + -> Result + { + <$t>::from_str_radix(s, radix) + } + } + )*) +} +int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); + +pub enum FloatErrorKind { + Empty, + Invalid, +} +pub struct ParseFloatError { + pub kind: FloatErrorKind, +} + +macro_rules! float_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t { + type Error = ParseFloatError; + + fn from_str_radix(src: &str, radix: u32) + -> Result + { + use self::FloatErrorKind::*; + use self::ParseFloatError as PFE; + + // Special values + match src { + "inf" => return Ok(Float::infinity()), + "-inf" => return Ok(Float::neg_infinity()), + "NaN" => return Ok(Float::nan()), + _ => {}, + } + + fn slice_shift_char(src: &str) -> Option<(char, &str)> { + src.chars().nth(0).map(|ch| (ch, &src[1..])) + } + + let (is_positive, src) = match slice_shift_char(src) { + None => return Err(PFE { kind: Empty }), + Some(('-', "")) => return Err(PFE { kind: Empty }), + Some(('-', src)) => (false, src), + Some((_, _)) => (true, src), + }; + + // The significand to accumulate + let mut sig = if is_positive { 0.0 } else { -0.0 }; + // Necessary to detect overflow + let mut prev_sig = sig; + let mut cs = src.chars().enumerate(); + // Exponent prefix and exponent index offset + let mut exp_info = None::<(char, usize)>; + + // Parse the integer part of the significand + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // shift significand one digit left + sig = sig * (radix as $t); + + // add/subtract current digit depending on sign + if is_positive { + sig = sig + ((digit as isize) as $t); + } else { + sig = sig - ((digit as isize) as $t); + } + + // Detect overflow by comparing to last value, except + // if we've not seen any non-zero digits. + if prev_sig != 0.0 { + if is_positive && sig <= prev_sig + { return Ok(Float::infinity()); } + if !is_positive && sig >= prev_sig + { return Ok(Float::neg_infinity()); } + + // Detect overflow by reversing the shift-and-add process + if is_positive && (prev_sig != (sig - digit as $t) / radix as $t) + { return Ok(Float::infinity()); } + if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t) + { return Ok(Float::neg_infinity()); } + } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + '.' => { + break; // start of fractional part + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + + // If we are not yet at the exponent parse the fractional + // part of the significand + if exp_info.is_none() { + let mut power = 1.0; + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // Decrease power one order of magnitude + power = power / (radix as $t); + // add/subtract current digit depending on sign + sig = if is_positive { + sig + (digit as $t) * power + } else { + sig - (digit as $t) * power + }; + // Detect overflow by comparing to last value + if is_positive && sig < prev_sig + { return Ok(Float::infinity()); } + if !is_positive && sig > prev_sig + { return Ok(Float::neg_infinity()); } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + } + + // Parse and calculate the exponent + let exp = match exp_info { + Some((c, offset)) => { + let base = match c { + 'E' | 'e' if radix == 10 => 10.0, + 'P' | 'p' if radix == 16 => 2.0, + _ => return Err(PFE { kind: Invalid }), + }; + + // Parse the exponent as decimal integer + let src = &src[offset..]; + let (is_positive, exp) = match slice_shift_char(src) { + Some(('-', src)) => (false, src.parse::()), + Some(('+', src)) => (true, src.parse::()), + Some((_, _)) => (true, src.parse::()), + None => return Err(PFE { kind: Invalid }), + }; + + match (is_positive, exp) { + (true, Ok(exp)) => base.powi(exp as i32), + (false, Ok(exp)) => 1.0 / base.powi(exp as i32), + (_, Err(_)) => return Err(PFE { kind: Invalid }), + } + }, + None => 1.0, // no exponent + }; + + Ok(sig * exp) + } + } + )*) +} +float_trait_impl!(Num for f32 f64); diff --git a/traits/src/ops/checked.rs b/traits/src/ops/checked.rs new file mode 100644 index 0000000..b6bf0d6 --- /dev/null +++ b/traits/src/ops/checked.rs @@ -0,0 +1,91 @@ +use std::ops::{Add, Sub, Mul, Div}; + +/// Performs addition that returns `None` instead of wrapping around on +/// overflow. +pub trait CheckedAdd: Sized + Add { + /// Adds two numbers, checking for overflow. If overflow happens, `None` is + /// returned. + fn checked_add(&self, v: &Self) -> Option; +} + +macro_rules! checked_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &$t) -> Option<$t> { + <$t>::$method(*self, *v) + } + } + } +} + +checked_impl!(CheckedAdd, checked_add, u8); +checked_impl!(CheckedAdd, checked_add, u16); +checked_impl!(CheckedAdd, checked_add, u32); +checked_impl!(CheckedAdd, checked_add, u64); +checked_impl!(CheckedAdd, checked_add, usize); + +checked_impl!(CheckedAdd, checked_add, i8); +checked_impl!(CheckedAdd, checked_add, i16); +checked_impl!(CheckedAdd, checked_add, i32); +checked_impl!(CheckedAdd, checked_add, i64); +checked_impl!(CheckedAdd, checked_add, isize); + +/// Performs subtraction that returns `None` instead of wrapping around on underflow. +pub trait CheckedSub: Sized + Sub { + /// Subtracts two numbers, checking for underflow. If underflow happens, + /// `None` is returned. + fn checked_sub(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedSub, checked_sub, u8); +checked_impl!(CheckedSub, checked_sub, u16); +checked_impl!(CheckedSub, checked_sub, u32); +checked_impl!(CheckedSub, checked_sub, u64); +checked_impl!(CheckedSub, checked_sub, usize); + +checked_impl!(CheckedSub, checked_sub, i8); +checked_impl!(CheckedSub, checked_sub, i16); +checked_impl!(CheckedSub, checked_sub, i32); +checked_impl!(CheckedSub, checked_sub, i64); +checked_impl!(CheckedSub, checked_sub, isize); + +/// Performs multiplication that returns `None` instead of wrapping around on underflow or +/// overflow. +pub trait CheckedMul: Sized + Mul { + /// Multiplies two numbers, checking for underflow or overflow. If underflow + /// or overflow happens, `None` is returned. + fn checked_mul(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedMul, checked_mul, u8); +checked_impl!(CheckedMul, checked_mul, u16); +checked_impl!(CheckedMul, checked_mul, u32); +checked_impl!(CheckedMul, checked_mul, u64); +checked_impl!(CheckedMul, checked_mul, usize); + +checked_impl!(CheckedMul, checked_mul, i8); +checked_impl!(CheckedMul, checked_mul, i16); +checked_impl!(CheckedMul, checked_mul, i32); +checked_impl!(CheckedMul, checked_mul, i64); +checked_impl!(CheckedMul, checked_mul, isize); + +/// Performs division that returns `None` instead of panicking on division by zero and instead of +/// wrapping around on underflow and overflow. +pub trait CheckedDiv: Sized + Div { + /// Divides two numbers, checking for underflow, overflow and division by + /// zero. If any of that happens, `None` is returned. + fn checked_div(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedDiv, checked_div, u8); +checked_impl!(CheckedDiv, checked_div, u16); +checked_impl!(CheckedDiv, checked_div, u32); +checked_impl!(CheckedDiv, checked_div, u64); +checked_impl!(CheckedDiv, checked_div, usize); + +checked_impl!(CheckedDiv, checked_div, i8); +checked_impl!(CheckedDiv, checked_div, i16); +checked_impl!(CheckedDiv, checked_div, i32); +checked_impl!(CheckedDiv, checked_div, i64); +checked_impl!(CheckedDiv, checked_div, isize); diff --git a/traits/src/ops/mod.rs b/traits/src/ops/mod.rs new file mode 100644 index 0000000..2632a0f --- /dev/null +++ b/traits/src/ops/mod.rs @@ -0,0 +1,2 @@ +pub mod saturating; +pub mod checked; diff --git a/traits/src/ops/saturating.rs b/traits/src/ops/saturating.rs new file mode 100644 index 0000000..15f06b7 --- /dev/null +++ b/traits/src/ops/saturating.rs @@ -0,0 +1,26 @@ +/// Saturating math operations +pub trait Saturating { + /// Saturating addition operator. + /// Returns a+b, saturating at the numeric bounds instead of overflowing. + fn saturating_add(self, v: Self) -> Self; + + /// Saturating subtraction operator. + /// Returns a-b, saturating at the numeric bounds instead of overflowing. + fn saturating_sub(self, v: Self) -> Self; +} + +macro_rules! saturating_impl { + ($trait_name:ident for $($t:ty)*) => {$( + impl $trait_name for $t { + fn saturating_add(self, v: Self) -> Self { + Self::saturating_add(self, v) + } + + fn saturating_sub(self, v: Self) -> Self { + Self::saturating_sub(self, v) + } + } + )*} +} + +saturating_impl!(Saturating for isize usize i8 u8 i16 u16 i32 u32 i64 u64); diff --git a/traits/src/sign.rs b/traits/src/sign.rs new file mode 100644 index 0000000..ae1d38c --- /dev/null +++ b/traits/src/sign.rs @@ -0,0 +1,126 @@ +use std::ops::Neg; +use std::{f32, f64}; + +use Num; + +/// Useful functions for signed numbers (i.e. numbers that can be negative). +pub trait Signed: Sized + Num + Neg { + /// Computes the absolute value. + /// + /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`. + /// + /// For signed integers, `::MIN` will be returned if the number is `::MIN`. + fn abs(&self) -> Self; + + /// The positive difference of two numbers. + /// + /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference + /// between `self` and `other` is returned. + fn abs_sub(&self, other: &Self) -> Self; + + /// Returns the sign of the number. + /// + /// For `f32` and `f64`: + /// + /// * `1.0` if the number is positive, `+0.0` or `INFINITY` + /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// * `NaN` if the number is `NaN` + /// + /// For signed integers: + /// + /// * `0` if the number is zero + /// * `1` if the number is positive + /// * `-1` if the number is negative + fn signum(&self) -> Self; + + /// Returns true if the number is positive and false if the number is zero or negative. + fn is_positive(&self) -> bool; + + /// Returns true if the number is negative and false if the number is zero or positive. + fn is_negative(&self) -> bool; +} + +macro_rules! signed_impl { + ($($t:ty)*) => ($( + impl Signed for $t { + #[inline] + fn abs(&self) -> $t { + if self.is_negative() { -*self } else { *self } + } + + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + if *self <= *other { 0 } else { *self - *other } + } + + #[inline] + fn signum(&self) -> $t { + match *self { + n if n > 0 => 1, + 0 => 0, + _ => -1, + } + } + + #[inline] + fn is_positive(&self) -> bool { *self > 0 } + + #[inline] + fn is_negative(&self) -> bool { *self < 0 } + } + )*) +} + +signed_impl!(isize i8 i16 i32 i64); + +macro_rules! signed_float_impl { + ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr) => { + impl Signed for $t { + /// Computes the absolute value. Returns `NAN` if the number is `NAN`. + #[inline] + fn abs(&self) -> $t { + <$t>::abs(*self) + } + + /// The positive difference of two numbers. Returns `0.0` if the number is + /// less than or equal to `other`, otherwise the difference between`self` + /// and `other` is returned. + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + <$t>::abs_sub(*self, *other) + } + + /// # Returns + /// + /// - `1.0` if the number is positive, `+0.0` or `INFINITY` + /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// - `NAN` if the number is NaN + #[inline] + fn signum(&self) -> $t { + <$t>::signum(*self) + } + + /// Returns `true` if the number is positive, including `+0.0` and `INFINITY` + #[inline] + fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf } + + /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY` + #[inline] + fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf } + } + } +} + +signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY); +signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY); + +/// A trait for values which cannot be negative +pub trait Unsigned: Num {} + +macro_rules! empty_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t {} + )*) +} + +empty_trait_impl!(Unsigned for usize u8 u16 u32 u64); From 4361521f5a5942510ac7096fcc9aeeccbb739f56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Tue, 16 Feb 2016 00:21:13 +0100 Subject: [PATCH 02/31] Move num-macros to macros to fit new naming system --- {num-macros => macros}/Cargo.toml | 0 {num-macros => macros}/src/lib.rs | 0 {num-macros => macros}/tests/test_macro.rs | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {num-macros => macros}/Cargo.toml (100%) rename {num-macros => macros}/src/lib.rs (100%) rename {num-macros => macros}/tests/test_macro.rs (100%) diff --git a/num-macros/Cargo.toml b/macros/Cargo.toml similarity index 100% rename from num-macros/Cargo.toml rename to macros/Cargo.toml diff --git a/num-macros/src/lib.rs b/macros/src/lib.rs similarity index 100% rename from num-macros/src/lib.rs rename to macros/src/lib.rs diff --git a/num-macros/tests/test_macro.rs b/macros/tests/test_macro.rs similarity index 100% rename from num-macros/tests/test_macro.rs rename to macros/tests/test_macro.rs From f1a80857ee03db3662cb15fc03039b7c09830929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Wed, 17 Feb 2016 18:51:28 +0100 Subject: [PATCH 03/31] Extract integer module --- Cargo.toml | 3 + integer/Cargo.toml | 5 +- integer/src/lib.rs | 58 ++-- src/integer.rs | 656 --------------------------------------------- src/lib.rs | 3 +- 5 files changed, 46 insertions(+), 679 deletions(-) delete mode 100644 src/integer.rs diff --git a/Cargo.toml b/Cargo.toml index 7eb975f..37edb98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,9 @@ serde = { version = "^0.7.0", optional = true } [dependencies.num-traits] path = "./traits" +[dependencies.num-integer] +path = "./integer" + [dev-dependencies] # Some tests of non-rand functionality still use rand because the tests # themselves are randomized. diff --git a/integer/Cargo.toml b/integer/Cargo.toml index 651a69d..29991b3 100644 --- a/integer/Cargo.toml +++ b/integer/Cargo.toml @@ -1,6 +1,7 @@ [package] -name = "integer" +name = "num-integer" version = "0.1.0" authors = ["Łukasz Jan Niemier "] -[dependencies] +[dependencies.num-traits] +path = "../traits" diff --git a/integer/src/lib.rs b/integer/src/lib.rs index eca274f..94d5f82 100644 --- a/integer/src/lib.rs +++ b/integer/src/lib.rs @@ -10,7 +10,9 @@ //! Integer trait and functions. -use {Num, Signed}; +extern crate num_traits as traits; + +use traits::{Num, Signed}; pub trait Integer : Sized @@ -179,7 +181,7 @@ macro_rules! impl_integer_for_isize { impl Integer for $T { /// Floored integer division #[inline] - fn div_floor(&self, other: &$T) -> $T { + fn div_floor(&self, other: &Self) -> Self { // 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) { @@ -191,7 +193,7 @@ macro_rules! impl_integer_for_isize { /// Floored integer modulo #[inline] - fn mod_floor(&self, other: &$T) -> $T { + fn mod_floor(&self, other: &Self) -> Self { // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) match *self % *other { @@ -203,7 +205,7 @@ macro_rules! impl_integer_for_isize { /// Calculates `div_floor` and `mod_floor` simultaneously #[inline] - fn div_mod_floor(&self, other: &$T) -> ($T,$T) { + fn div_mod_floor(&self, other: &Self) -> (Self, Self) { // 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) { @@ -216,7 +218,7 @@ macro_rules! impl_integer_for_isize { /// Calculates the Greatest Common Divisor (GCD) of the number and /// `other`. The result is always positive. #[inline] - fn gcd(&self, other: &$T) -> $T { + fn gcd(&self, other: &Self) -> Self { // Use Stein's algorithm let mut m = *self; let mut n = *other; @@ -233,7 +235,7 @@ macro_rules! impl_integer_for_isize { // Assuming two's complement, the number created by the shift // is positive for all numbers except gcd = abs(min value) // The call to .abs() causes a panic in debug mode - if m == <$T>::min_value() || n == <$T>::min_value() { + if m == Self::min_value() || n == Self::min_value() { return (1 << shift).abs() } @@ -257,18 +259,22 @@ macro_rules! impl_integer_for_isize { /// Calculates the Lowest Common Multiple (LCM) of the number and /// `other`. #[inline] - fn lcm(&self, other: &$T) -> $T { + fn lcm(&self, other: &Self) -> Self { // should not have to recalculate abs ((*self * *other) / self.gcd(other)).abs() } /// Deprecated, use `is_multiple_of` instead. #[inline] - fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } + fn divides(&self, other: &Self) -> bool { + self.is_multiple_of(other) + } /// Returns `true` if the number is a multiple of `other`. #[inline] - fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + fn is_multiple_of(&self, other: &Self) -> bool { + *self % *other == 0 + } /// Returns `true` if the number is divisible by `2` #[inline] @@ -280,7 +286,7 @@ macro_rules! impl_integer_for_isize { /// Simultaneous truncated integer division and modulus. #[inline] - fn div_rem(&self, other: &$T) -> ($T, $T) { + fn div_rem(&self, other: &Self) -> (Self, Self) { (*self / *other, *self % *other) } } @@ -295,7 +301,7 @@ macro_rules! impl_integer_for_isize { /// - `d`: denominator (divisor) /// - `qr`: quotient and remainder #[cfg(test)] - fn test_division_rule((n,d): ($T,$T), (q,r): ($T,$T)) { + fn test_division_rule((n,d): ($T, $T), (q,r): ($T, $T)) { assert_eq!(d * q + r, n); } @@ -475,15 +481,19 @@ macro_rules! impl_integer_for_usize { impl Integer for $T { /// Unsigned integer division. Returns the same result as `div` (`/`). #[inline] - fn div_floor(&self, other: &$T) -> $T { *self / *other } + fn div_floor(&self, other: &Self) -> Self { + *self / *other + } /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). #[inline] - fn mod_floor(&self, other: &$T) -> $T { *self % *other } + fn mod_floor(&self, other: &Self) -> Self { + *self % *other + } /// Calculates the Greatest Common Divisor (GCD) of the number and `other` #[inline] - fn gcd(&self, other: &$T) -> $T { + fn gcd(&self, other: &Self) -> Self { // Use Stein's algorithm let mut m = *self; let mut n = *other; @@ -507,29 +517,37 @@ macro_rules! impl_integer_for_usize { /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] - fn lcm(&self, other: &$T) -> $T { + fn lcm(&self, other: &Self) -> Self { (*self * *other) / self.gcd(other) } /// Deprecated, use `is_multiple_of` instead. #[inline] - fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } + fn divides(&self, other: &Self) -> bool { + self.is_multiple_of(other) + } /// Returns `true` if the number is a multiple of `other`. #[inline] - fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } + fn is_multiple_of(&self, other: &Self) -> bool { + *self % *other == 0 + } /// Returns `true` if the number is divisible by `2`. #[inline] - fn is_even(&self) -> bool { (*self) & 1 == 0 } + fn is_even(&self) -> bool { + *self % 2 == 0 + } /// Returns `true` if the number is not divisible by `2`. #[inline] - fn is_odd(&self) -> bool { !(*self).is_even() } + fn is_odd(&self) -> bool { + !self.is_even() + } /// Simultaneous truncated integer division and modulus. #[inline] - fn div_rem(&self, other: &$T) -> ($T, $T) { + fn div_rem(&self, other: &Self) -> (Self, Self) { (*self / *other, *self % *other) } } diff --git a/src/integer.rs b/src/integer.rs deleted file mode 100644 index 883c01c..0000000 --- a/src/integer.rs +++ /dev/null @@ -1,656 +0,0 @@ -// Copyright 2013-2014 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. - -//! Integer trait and functions. - -use {Num, Signed}; - -pub trait Integer - : Sized + Num + Ord -{ - /// Floored integer division. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// 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); - /// ~~~ - fn div_floor(&self, other: &Self) -> Self; - - /// Floored integer modulo, satisfying: - /// - /// ~~~ - /// # use num::Integer; - /// # let n = 1; let d = 1; - /// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n) - /// ~~~ - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// 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); - /// ~~~ - fn mod_floor(&self, other: &Self) -> Self; - - /// Greatest Common Divisor (GCD). - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(6.gcd(&8), 2); - /// assert_eq!(7.gcd(&3), 1); - /// ~~~ - fn gcd(&self, other: &Self) -> Self; - - /// Lowest Common Multiple (LCM). - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(7.lcm(&3), 21); - /// assert_eq!(2.lcm(&4), 4); - /// ~~~ - fn lcm(&self, other: &Self) -> Self; - - /// Deprecated, use `is_multiple_of` instead. - fn divides(&self, other: &Self) -> bool; - - /// Returns `true` if `other` is a multiple of `self`. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(9.is_multiple_of(&3), true); - /// assert_eq!(3.is_multiple_of(&9), false); - /// ~~~ - fn is_multiple_of(&self, other: &Self) -> bool; - - /// Returns `true` if the number is even. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(3.is_even(), false); - /// assert_eq!(4.is_even(), true); - /// ~~~ - fn is_even(&self) -> bool; - - /// Returns `true` if the number is odd. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(3.is_odd(), true); - /// assert_eq!(4.is_odd(), false); - /// ~~~ - fn is_odd(&self) -> bool; - - /// Simultaneous truncated integer division and modulus. - /// Returns `(quotient, remainder)`. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(( 8).div_rem( &3), ( 2, 2)); - /// assert_eq!(( 8).div_rem(&-3), (-2, 2)); - /// assert_eq!((-8).div_rem( &3), (-2, -2)); - /// assert_eq!((-8).div_rem(&-3), ( 2, -2)); - /// - /// assert_eq!(( 1).div_rem( &2), ( 0, 1)); - /// assert_eq!(( 1).div_rem(&-2), ( 0, 1)); - /// assert_eq!((-1).div_rem( &2), ( 0, -1)); - /// assert_eq!((-1).div_rem(&-2), ( 0, -1)); - /// ~~~ - #[inline] - fn div_rem(&self, other: &Self) -> (Self, Self); - - /// Simultaneous floored integer division and modulus. - /// Returns `(quotient, remainder)`. - /// - /// # Examples - /// - /// ~~~ - /// # use num::Integer; - /// assert_eq!(( 8).div_mod_floor( &3), ( 2, 2)); - /// assert_eq!(( 8).div_mod_floor(&-3), (-3, -1)); - /// assert_eq!((-8).div_mod_floor( &3), (-3, 1)); - /// assert_eq!((-8).div_mod_floor(&-3), ( 2, -2)); - /// - /// assert_eq!(( 1).div_mod_floor( &2), ( 0, 1)); - /// assert_eq!(( 1).div_mod_floor(&-2), (-1, -1)); - /// assert_eq!((-1).div_mod_floor( &2), (-1, 1)); - /// assert_eq!((-1).div_mod_floor(&-2), ( 0, -1)); - /// ~~~ - fn div_mod_floor(&self, other: &Self) -> (Self, Self) { - (self.div_floor(other), self.mod_floor(other)) - } -} - -/// Simultaneous integer division and modulus -#[inline] pub fn div_rem(x: T, y: T) -> (T, T) { x.div_rem(&y) } -/// Floored integer division -#[inline] pub fn div_floor(x: T, y: T) -> T { x.div_floor(&y) } -/// Floored integer modulus -#[inline] pub fn mod_floor(x: T, y: T) -> T { x.mod_floor(&y) } -/// Simultaneous floored integer division and modulus -#[inline] pub fn div_mod_floor(x: T, y: T) -> (T, T) { x.div_mod_floor(&y) } - -/// Calculates the Greatest Common Divisor (GCD) of the number and `other`. The -/// result is always positive. -#[inline(always)] pub fn gcd(x: T, y: T) -> T { x.gcd(&y) } -/// Calculates the Lowest Common Multiple (LCM) of the number and `other`. -#[inline(always)] pub fn lcm(x: T, y: T) -> T { x.lcm(&y) } - -macro_rules! impl_integer_for_isize { - ($T:ty, $test_mod:ident) => ( - impl Integer for $T { - /// Floored integer division - #[inline] - 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, - } - } - - /// Floored integer modulo - #[inline] - 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] - 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 the Greatest Common Divisor (GCD) of the number and - /// `other`. The result is always positive. - #[inline] - fn gcd(&self, other: &$T) -> $T { - // Use Stein's algorithm - let mut m = *self; - let mut n = *other; - if m == 0 || n == 0 { return (m | n).abs() } - - // find common factors of 2 - let shift = (m | n).trailing_zeros(); - - // The algorithm needs positive numbers, but the minimum value - // can't be represented as a positive one. - // It's also a power of two, so the gcd can be - // calculated by bitshifting in that case - - // Assuming two's complement, the number created by the shift - // is positive for all numbers except gcd = abs(min value) - // The call to .abs() causes a panic in debug mode - if m == <$T>::min_value() || n == <$T>::min_value() { - return (1 << shift).abs() - } - - // guaranteed to be positive now, rest like unsigned algorithm - m = m.abs(); - n = n.abs(); - - // divide n and m by 2 until odd - // m inside loop - n >>= n.trailing_zeros(); - - while m != 0 { - m >>= m.trailing_zeros(); - if n > m { ::std::mem::swap(&mut n, &mut m) } - m -= n; - } - - n << shift - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and - /// `other`. - #[inline] - fn lcm(&self, other: &$T) -> $T { - // should not have to recalculate abs - (*self * (*other / self.gcd(other))).abs() - } - - /// Deprecated, use `is_multiple_of` instead. - #[inline] - fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } - - /// Returns `true` if the number is divisible by `2` - #[inline] - fn is_even(&self) -> bool { (*self) & 1 == 0 } - - /// Returns `true` if the number is not divisible by `2` - #[inline] - fn is_odd(&self) -> bool { !self.is_even() } - - /// Simultaneous truncated integer division and modulus. - #[inline] - fn div_rem(&self, other: &$T) -> ($T, $T) { - (*self / *other, *self % *other) - } - } - - #[cfg(test)] - mod $test_mod { - use Integer; - - /// 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_gcd_cmp_with_euclidean() { - fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { - while m != 0 { - ::std::mem::swap(&mut m, &mut n); - m %= n; - } - - n.abs() - } - - // gcd(-128, b) = 128 is not representable as positive value - // for i8 - for i in -127..127 { - for j in -127..127 { - assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); - } - } - - // last value - // FIXME: Use inclusive ranges for above loop when implemented - let i = 127; - for j in -127..127 { - assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); - } - assert_eq!(127.gcd(&127), 127); - } - - #[test] - fn test_gcd_min_val() { - let min = <$T>::min_value(); - let max = <$T>::max_value(); - let max_pow2 = max / 2 + 1; - assert_eq!(min.gcd(&max), 1 as $T); - assert_eq!(max.gcd(&min), 1 as $T); - assert_eq!(min.gcd(&max_pow2), max_pow2); - assert_eq!(max_pow2.gcd(&min), max_pow2); - assert_eq!(min.gcd(&42), 2 as $T); - assert_eq!((42 as $T).gcd(&min), 2 as $T); - } - - #[test] - #[should_panic] - fn test_gcd_min_val_min_val() { - let min = <$T>::min_value(); - assert!(min.gcd(&min) >= 0); - } - - #[test] - #[should_panic] - fn test_gcd_min_val_0() { - let min = <$T>::min_value(); - assert!(min.gcd(&0) >= 0); - } - - #[test] - #[should_panic] - fn test_gcd_0_min_val() { - let min = <$T>::min_value(); - assert!((0 as $T).gcd(&min) >= 0); - } - - #[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_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); - } - } - ) -} - -impl_integer_for_isize!(i8, test_integer_i8); -impl_integer_for_isize!(i16, test_integer_i16); -impl_integer_for_isize!(i32, test_integer_i32); -impl_integer_for_isize!(i64, test_integer_i64); -impl_integer_for_isize!(isize, test_integer_isize); - -macro_rules! impl_integer_for_usize { - ($T:ty, $test_mod:ident) => ( - impl Integer for $T { - /// Unsigned integer division. Returns the same result as `div` (`/`). - #[inline] - fn div_floor(&self, other: &$T) -> $T { *self / *other } - - /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). - #[inline] - fn mod_floor(&self, other: &$T) -> $T { *self % *other } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other` - #[inline] - fn gcd(&self, other: &$T) -> $T { - // Use Stein's algorithm - let mut m = *self; - let mut n = *other; - if m == 0 || n == 0 { return m | n } - - // find common factors of 2 - let shift = (m | n).trailing_zeros(); - - // divide n and m by 2 until odd - // m inside loop - n >>= n.trailing_zeros(); - - while m != 0 { - m >>= m.trailing_zeros(); - if n > m { ::std::mem::swap(&mut n, &mut m) } - m -= n; - } - - n << shift - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. - #[inline] - fn lcm(&self, other: &$T) -> $T { - *self * (*other / self.gcd(other)) - } - - /// Deprecated, use `is_multiple_of` instead. - #[inline] - fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } - - /// Returns `true` if the number is divisible by `2`. - #[inline] - fn is_even(&self) -> bool { (*self) & 1 == 0 } - - /// Returns `true` if the number is not divisible by `2`. - #[inline] - fn is_odd(&self) -> bool { !(*self).is_even() } - - /// Simultaneous truncated integer division and modulus. - #[inline] - fn div_rem(&self, other: &$T) -> ($T, $T) { - (*self / *other, *self % *other) - } - } - - #[cfg(test)] - mod $test_mod { - use Integer; - - #[test] - fn test_div_mod_floor() { - assert_eq!((10 as $T).div_floor(&(3 as $T)), 3 as $T); - assert_eq!((10 as $T).mod_floor(&(3 as $T)), 1 as $T); - assert_eq!((10 as $T).div_mod_floor(&(3 as $T)), (3 as $T, 1 as $T)); - assert_eq!((5 as $T).div_floor(&(5 as $T)), 1 as $T); - assert_eq!((5 as $T).mod_floor(&(5 as $T)), 0 as $T); - assert_eq!((5 as $T).div_mod_floor(&(5 as $T)), (1 as $T, 0 as $T)); - assert_eq!((3 as $T).div_floor(&(7 as $T)), 0 as $T); - assert_eq!((3 as $T).mod_floor(&(7 as $T)), 3 as $T); - assert_eq!((3 as $T).div_mod_floor(&(7 as $T)), (0 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_gcd_cmp_with_euclidean() { - fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { - while m != 0 { - ::std::mem::swap(&mut m, &mut n); - m %= n; - } - n - } - - for i in 0..255 { - for j in 0..255 { - assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); - } - } - - // last value - // FIXME: Use inclusive ranges for above loop when implemented - let i = 255; - for j in 0..255 { - assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); - } - assert_eq!(255.gcd(&255), 255); - } - - #[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!((15 as $T).lcm(&17), 255 as $T); - } - - #[test] - fn test_is_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); - } - } - ) -} - -impl_integer_for_usize!(u8, test_integer_u8); -impl_integer_for_usize!(u16, test_integer_u16); -impl_integer_for_usize!(u32, test_integer_u32); -impl_integer_for_usize!(u64, test_integer_u64); -impl_integer_for_usize!(usize, test_integer_usize); - -#[test] -fn test_lcm_overflow() { - macro_rules! check { - ($t:ty, $x:expr, $y:expr, $r:expr) => { { - let x: $t = $x; - let y: $t = $y; - let o = x.checked_mul(y); - assert!(o.is_none(), - "sanity checking that {} input {} * {} overflows", - stringify!($t), x, y); - assert_eq!(x.lcm(&y), $r); - assert_eq!(y.lcm(&x), $r); - } } - } - - // Original bug (Issue #166) - check!(i64, 46656000000000000, 600, 46656000000000000); - - check!(i8, 0x40, 0x04, 0x40); - check!(u8, 0x80, 0x02, 0x80); - check!(i16, 0x40_00, 0x04, 0x40_00); - check!(u16, 0x80_00, 0x02, 0x80_00); - check!(i32, 0x4000_0000, 0x04, 0x4000_0000); - check!(u32, 0x8000_0000, 0x02, 0x8000_0000); - check!(i64, 0x4000_0000_0000_0000, 0x04, 0x4000_0000_0000_0000); - check!(u64, 0x8000_0000_0000_0000, 0x02, 0x8000_0000_0000_0000); -} diff --git a/src/lib.rs b/src/lib.rs index 48ef305..46e0adb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,6 +58,7 @@ html_playground_url = "http://play.rust-lang.org/")] extern crate num_traits; +extern crate num_integer; #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; @@ -92,7 +93,7 @@ use std::ops::{Mul}; #[cfg(feature = "bigint")] pub mod bigint; pub mod complex; -pub mod integer; +pub mod integer { pub use num_integer::*; } pub mod iter; pub mod traits { pub use num_traits::*; } #[cfg(feature = "rational")] From 2176b7048c7ee1a8a274e6541dc6428768f87d8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Tue, 1 Mar 2016 11:47:10 +0100 Subject: [PATCH 04/31] Extract bigint --- Cargo.toml | 76 +- bigint/Cargo.toml | 22 + bigint/src/lib.rs | 5129 ++++++++++++++++++++++++++++++++++++++++++++ integer/src/lib.rs | 54 +- src/lib.rs | 3 +- traits/src/lib.rs | 10 +- 6 files changed, 5234 insertions(+), 60 deletions(-) create mode 100644 bigint/Cargo.toml create mode 100644 bigint/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 37edb98..378484a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,44 +1,52 @@ [package] - -name = "num" -version = "0.1.31" authors = ["The Rust Project Developers"] -license = "MIT/Apache-2.0" -homepage = "https://github.com/rust-num/num" -repository = "https://github.com/rust-num/num" +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] -description = """ -A collection of numeric types and traits for Rust, including bigint, -complex, rational, range iterators, generic integers, and more! -""" - -[dependencies] -rand = { version = "0.3.8", optional = true } -rustc-serialize = { version = "0.3.13", optional = true } -serde = { version = "^0.7.0", optional = true } - -[dependencies.num-traits] -path = "./traits" - -[dependencies.num-integer] -path = "./integer" - -[dev-dependencies] -# Some tests of non-rand functionality still use rand because the tests -# themselves are randomized. -rand = { version = "0.3.8" } - -[features] - -complex = [] -rational = [] -bigint = [] -default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] +license = "MIT/Apache-2.0" +name = "num" +repository = "https://github.com/rust-num/num" +version = "0.1.31" [[bench]] name = "bigint" [[bench]] -name = "shootout-pidigits" harness = false +name = "shootout-pidigits" + +[dependencies] + +[dependencies.num-bigint] +optional = false +path = "bigint" + +[dependencies.num-integer] +path = "./integer" + +[dependencies.num-traits] +path = "./traits" + +[dependencies.rand] +optional = true +version = "0.3.8" + +[dependencies.rustc-serialize] +optional = true +version = "0.3.13" + +[dependencies.serde] +optional = true +version = "^0.7.0" + +[dev-dependencies] + +[dev-dependencies.rand] +version = "0.3.8" + +[features] +bigint = [] +complex = [] +default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] +rational = [] diff --git a/bigint/Cargo.toml b/bigint/Cargo.toml new file mode 100644 index 0000000..729e5cc --- /dev/null +++ b/bigint/Cargo.toml @@ -0,0 +1,22 @@ +[package] +authors = ["Łukasz Jan Niemier "] +name = "num-bigint" +version = "0.1.0" + +[dependencies] + +[dependencies.num-integer] +optional = false +path = "../integer" + +[dependencies.num-traits] +optional = false +path = "../traits" + +[dependencies.rand] +optional = true +version = "0.3.14" + +[dependencies.serde] +optional = true +version = "0.7.0" diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs new file mode 100644 index 0000000..7bb3cc5 --- /dev/null +++ b/bigint/src/lib.rs @@ -0,0 +1,5129 @@ +// Copyright 2013-2014 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. + +//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`). +//! +//! A `BigUint` is represented as a vector of `BigDigit`s. +//! A `BigInt` is a combination of `BigUint` and `Sign`. +//! +//! Common numerical operations are overloaded, so we can treat them +//! the same way we treat other numbers. +//! +//! ## Example +//! +//! ```rust +//! use num::{BigUint, Zero, One}; +//! use std::mem::replace; +//! +//! // Calculate large fibonacci numbers. +//! fn fib(n: usize) -> BigUint { +//! let mut f0: BigUint = Zero::zero(); +//! let mut f1: BigUint = One::one(); +//! for _ in 0..n { +//! let f2 = f0 + &f1; +//! // This is a low cost way of swapping f0 with f1 and f1 with f2. +//! f0 = replace(&mut f1, f2); +//! } +//! f0 +//! } +//! +//! // This is a very large number. +//! println!("fib(1000) = {}", fib(1000)); +//! ``` +//! +//! It's easy to generate large random numbers: +//! +//! ```rust +//! extern crate rand; +//! extern crate num; +//! +//! # #[cfg(feature = "rand")] +//! # fn main() { +//! use num::bigint::{ToBigInt, RandBigInt}; +//! +//! let mut rng = rand::thread_rng(); +//! let a = rng.gen_bigint(1000); +//! +//! let low = -10000.to_bigint().unwrap(); +//! let high = 10000.to_bigint().unwrap(); +//! let b = rng.gen_bigint_range(&low, &high); +//! +//! // Probably an even larger number. +//! println!("{}", a * b); +//! # } +//! +//! # #[cfg(not(feature = "rand"))] +//! # fn main() { +//! # } +//! ``` + +extern crate num_integer as integer; +extern crate num_traits as traits; + +use std::borrow::Cow; +use std::default::Default; +use std::error::Error; +use std::iter::repeat; +use std::num::ParseIntError; +use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub}; +use std::str::{self, FromStr}; +use std::fmt; +use std::cmp::Ordering::{self, Less, Greater, Equal}; +use std::{f32, f64}; +use std::{u8, i64, u64}; +use std::ascii::AsciiExt; + +#[cfg(feature = "serde")] +use serde; + +// Some of the tests of non-RNG-based functionality are randomized using the +// RNG-based functionality, so the RNG-based functionality needs to be enabled +// for tests. +#[cfg(any(feature = "rand", test))] +use rand::Rng; + +use integer::Integer; +use traits::{ToPrimitive, FromPrimitive, Float, Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul, + CheckedDiv, Signed, Zero, One}; + +use self::Sign::{Minus, NoSign, Plus}; + +/// A `BigDigit` is a `BigUint`'s composing element. +pub type BigDigit = u32; + +/// A `DoubleBigDigit` is the internal type used to do the computations. Its +/// size is the double of the size of `BigDigit`. +pub type DoubleBigDigit = u64; + +pub const ZERO_BIG_DIGIT: BigDigit = 0; + +#[allow(non_snake_case)] +pub mod big_digit { + use super::BigDigit; + use super::DoubleBigDigit; + + // `DoubleBigDigit` size dependent + pub const BITS: usize = 32; + + pub const BASE: DoubleBigDigit = 1 << BITS; + const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS; + + #[inline] + fn get_hi(n: DoubleBigDigit) -> BigDigit { + (n >> BITS) as BigDigit + } + #[inline] + fn get_lo(n: DoubleBigDigit) -> BigDigit { + (n & LO_MASK) as BigDigit + } + + /// Split one `DoubleBigDigit` into two `BigDigit`s. + #[inline] + pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { + (get_hi(n), get_lo(n)) + } + + /// Join two `BigDigit`s into one `DoubleBigDigit` + #[inline] + pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit { + (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS) + } +} + +// Generic functions for add/subtract/multiply with carry/borrow: +// + +// Add with carry: +#[inline] +fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit { + let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) + (b as DoubleBigDigit) + + (*carry as DoubleBigDigit)); + + *carry = hi; + lo +} + +// Subtract with borrow: +#[inline] +fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit { + let (hi, lo) = big_digit::from_doublebigdigit(big_digit::BASE + (a as DoubleBigDigit) - + (b as DoubleBigDigit) - + (*borrow as DoubleBigDigit)); + // hi * (base) + lo == 1*(base) + ai - bi - borrow + // => ai - bi - borrow < 0 <=> hi == 0 + // + *borrow = if hi == 0 { + 1 + } else { + 0 + }; + lo +} + +#[inline] +fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit { + let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) + + (b as DoubleBigDigit) * (c as DoubleBigDigit) + + (*carry as DoubleBigDigit)); + *carry = hi; + lo +} + +/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder: +/// +/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit. +/// This is _not_ true for an arbitrary numerator/denominator. +/// +/// (This function also matches what the x86 divide instruction does). +#[inline] +fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) { + debug_assert!(hi < divisor); + + let lhs = big_digit::to_doublebigdigit(hi, lo); + let rhs = divisor as DoubleBigDigit; + ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit) +} + +/// A big unsigned integer type. +/// +/// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number +/// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`. +#[derive(Clone, Debug, Hash)] +#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] +pub struct BigUint { + data: Vec, +} + +impl PartialEq for BigUint { + #[inline] + fn eq(&self, other: &BigUint) -> bool { + match self.cmp(other) { + Equal => true, + _ => false, + } + } +} +impl Eq for BigUint {} + +impl PartialOrd for BigUint { + #[inline] + fn partial_cmp(&self, other: &BigUint) -> Option { + Some(self.cmp(other)) + } +} + +fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering { + debug_assert!(a.last() != Some(&0)); + debug_assert!(b.last() != Some(&0)); + + let (a_len, b_len) = (a.len(), b.len()); + if a_len < b_len { + return Less; + } + if a_len > b_len { + return Greater; + } + + for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) { + if ai < bi { + return Less; + } + if ai > bi { + return Greater; + } + } + return Equal; +} + +impl Ord for BigUint { + #[inline] + fn cmp(&self, other: &BigUint) -> Ordering { + cmp_slice(&self.data[..], &other.data[..]) + } +} + +impl Default for BigUint { + #[inline] + fn default() -> BigUint { + Zero::zero() + } +} + +impl fmt::Display for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "", &self.to_str_radix(10)) + } +} + +impl fmt::LowerHex for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0x", &self.to_str_radix(16)) + } +} + +impl fmt::UpperHex for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0x", &self.to_str_radix(16).to_ascii_uppercase()) + } +} + +impl fmt::Binary for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0b", &self.to_str_radix(2)) + } +} + +impl fmt::Octal for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(true, "0o", &self.to_str_radix(8)) + } +} + +impl FromStr for BigUint { + type Err = ParseBigIntError; + + #[inline] + fn from_str(s: &str) -> Result { + BigUint::from_str_radix(s, 10) + } +} + +// Read bitwise digits that evenly divide BigDigit +fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { + debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0); + debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); + + let digits_per_big_digit = big_digit::BITS / bits; + + let data = v.chunks(digits_per_big_digit) + .map(|chunk| { + chunk.iter().rev().fold(0u32, |acc, &c| (acc << bits) | c as BigDigit) + }) + .collect(); + + BigUint::new(data) +} + +// Read bitwise digits that don't evenly divide BigDigit +fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { + debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0); + debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); + + let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS; + let mut data = Vec::with_capacity(big_digits); + + let mut d = 0; + let mut dbits = 0; + for &c in v { + d |= (c as DoubleBigDigit) << dbits; + dbits += bits; + if dbits >= big_digit::BITS { + let (hi, lo) = big_digit::from_doublebigdigit(d); + data.push(lo); + d = hi as DoubleBigDigit; + dbits -= big_digit::BITS; + } + } + + if dbits > 0 { + debug_assert!(dbits < big_digit::BITS); + data.push(d as BigDigit); + } + + BigUint::new(data) +} + +// Read little-endian radix digits +fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint { + debug_assert!(!v.is_empty() && !radix.is_power_of_two()); + debug_assert!(v.iter().all(|&c| (c as u32) < radix)); + + // Estimate how big the result will be, so we can pre-allocate it. + let bits = (radix as f64).log2() * v.len() as f64; + let big_digits = (bits / big_digit::BITS as f64).ceil(); + let mut data = Vec::with_capacity(big_digits as usize); + + let (base, power) = get_radix_base(radix); + debug_assert!(base < (1 << 32)); + let base = base as BigDigit; + + let r = v.len() % power; + let i = if r == 0 { + power + } else { + r + }; + let (head, tail) = v.split_at(i); + + let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); + data.push(first); + + debug_assert!(tail.len() % power == 0); + for chunk in tail.chunks(power) { + if data.last() != Some(&0) { + data.push(0); + } + + let mut carry = 0; + for d in data.iter_mut() { + *d = mac_with_carry(0, *d, base, &mut carry); + } + debug_assert!(carry == 0); + + let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); + add2(&mut data, &[n]); + } + + BigUint::new(data) +} + +impl Num for BigUint { + type FromStrRadixErr = ParseBigIntError; + + /// Creates and initializes a `BigUint`. + fn from_str_radix(s: &str, radix: u32) -> Result { + assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); + let mut s = s; + if s.starts_with('+') { + let tail = &s[1..]; + if !tail.starts_with('+') { + s = tail + } + } + + if s.is_empty() { + // create ParseIntError::Empty + let e = u64::from_str_radix(s, radix).unwrap_err(); + return Err(e.into()); + } + + // First normalize all characters to plain digit values + let mut v = Vec::with_capacity(s.len()); + for b in s.bytes() { + let d = match b { + b'0'...b'9' => b - b'0', + b'a'...b'z' => b - b'a' + 10, + b'A'...b'Z' => b - b'A' + 10, + _ => u8::MAX, + }; + if d < radix as u8 { + v.push(d); + } else { + // create ParseIntError::InvalidDigit + let e = u64::from_str_radix(&s[v.len()..], radix).unwrap_err(); + return Err(e.into()); + } + } + + let res = if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of multiplication + let bits = radix.trailing_zeros() as usize; + v.reverse(); + if big_digit::BITS % bits == 0 { + from_bitwise_digits_le(&v, bits) + } else { + from_inexact_bitwise_digits_le(&v, bits) + } + } else { + from_radix_digits_be(&v, radix) + }; + Ok(res) + } +} + +macro_rules! forward_val_val_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl $imp<$res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to val-ref + $imp::$method(self, &other) + } + } + } +} + +macro_rules! forward_val_val_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl $imp<$res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to val-ref, with the larger capacity as val + if self.data.capacity() >= other.data.capacity() { + $imp::$method(self, &other) + } else { + $imp::$method(other, &self) + } + } + } + } +} + +macro_rules! forward_ref_val_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<$res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // forward to ref-ref + $imp::$method(self, &other) + } + } + } +} + +macro_rules! forward_ref_val_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<$res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: $res) -> $res { + // reverse, forward to val-ref + $imp::$method(other, self) + } + } + } +} + +macro_rules! forward_val_ref_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a> $imp<&'a $res> for $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to ref-ref + $imp::$method(&self, other) + } + } + } +} + +macro_rules! forward_ref_ref_binop { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to val-ref + $imp::$method(self.clone(), other) + } + } + } +} + +macro_rules! forward_ref_ref_binop_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + impl<'a, 'b> $imp<&'b $res> for &'a $res { + type Output = $res; + + #[inline] + fn $method(self, other: &$res) -> $res { + // forward to val-ref, choosing the larger to clone + if self.data.len() >= other.data.len() { + $imp::$method(self.clone(), other) + } else { + $imp::$method(other.clone(), self) + } + } + } + } +} + +// Forward everything to ref-ref, when reusing storage is not helpful +macro_rules! forward_all_binop_to_ref_ref { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop!(impl $imp for $res, $method); + forward_val_ref_binop!(impl $imp for $res, $method); + forward_ref_val_binop!(impl $imp for $res, $method); + }; +} + +// Forward everything to val-ref, so LHS storage can be reused +macro_rules! forward_all_binop_to_val_ref { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop!(impl $imp for $res, $method); + forward_ref_val_binop!(impl $imp for $res, $method); + forward_ref_ref_binop!(impl $imp for $res, $method); + }; +} + +// Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused +macro_rules! forward_all_binop_to_val_ref_commutative { + (impl $imp:ident for $res:ty, $method:ident) => { + forward_val_val_binop_commutative!(impl $imp for $res, $method); + forward_ref_val_binop_commutative!(impl $imp for $res, $method); + forward_ref_ref_binop_commutative!(impl $imp for $res, $method); + }; +} + +forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand); + +impl<'a> BitAnd<&'a BigUint> for BigUint { + type Output = BigUint; + + #[inline] + fn bitand(self, other: &BigUint) -> BigUint { + let mut data = self.data; + for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { + *ai &= bi; + } + data.truncate(other.data.len()); + BigUint::new(data) + } +} + +forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor); + +impl<'a> BitOr<&'a BigUint> for BigUint { + type Output = BigUint; + + fn bitor(self, other: &BigUint) -> BigUint { + let mut data = self.data; + for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { + *ai |= bi; + } + if other.data.len() > data.len() { + let extra = &other.data[data.len()..]; + data.extend(extra.iter().cloned()); + } + BigUint::new(data) + } +} + +forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor); + +impl<'a> BitXor<&'a BigUint> for BigUint { + type Output = BigUint; + + fn bitxor(self, other: &BigUint) -> BigUint { + let mut data = self.data; + for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { + *ai ^= bi; + } + if other.data.len() > data.len() { + let extra = &other.data[data.len()..]; + data.extend(extra.iter().cloned()); + } + BigUint::new(data) + } +} + +#[inline] +fn biguint_shl(n: Cow, bits: usize) -> BigUint { + let n_unit = bits / big_digit::BITS; + let mut data = match n_unit { + 0 => n.into_owned().data, + _ => { + let len = n_unit + n.data.len() + 1; + let mut data = Vec::with_capacity(len); + data.extend(repeat(0).take(n_unit)); + data.extend(n.data.iter().cloned()); + data + } + }; + + let n_bits = bits % big_digit::BITS; + if n_bits > 0 { + let mut carry = 0; + for elem in data[n_unit..].iter_mut() { + let new_carry = *elem >> (big_digit::BITS - n_bits); + *elem = (*elem << n_bits) | carry; + carry = new_carry; + } + if carry != 0 { + data.push(carry); + } + } + + BigUint::new(data) +} + +impl Shl for BigUint { + type Output = BigUint; + + #[inline] + fn shl(self, rhs: usize) -> BigUint { + biguint_shl(Cow::Owned(self), rhs) + } +} + +impl<'a> Shl for &'a BigUint { + type Output = BigUint; + + #[inline] + fn shl(self, rhs: usize) -> BigUint { + biguint_shl(Cow::Borrowed(self), rhs) + } +} + +#[inline] +fn biguint_shr(n: Cow, bits: usize) -> BigUint { + let n_unit = bits / big_digit::BITS; + if n_unit >= n.data.len() { + return Zero::zero(); + } + let mut data = match n_unit { + 0 => n.into_owned().data, + _ => n.data[n_unit..].to_vec(), + }; + + let n_bits = bits % big_digit::BITS; + if n_bits > 0 { + let mut borrow = 0; + for elem in data.iter_mut().rev() { + let new_borrow = *elem << (big_digit::BITS - n_bits); + *elem = (*elem >> n_bits) | borrow; + borrow = new_borrow; + } + } + + BigUint::new(data) +} + +impl Shr for BigUint { + type Output = BigUint; + + #[inline] + fn shr(self, rhs: usize) -> BigUint { + biguint_shr(Cow::Owned(self), rhs) + } +} + +impl<'a> Shr for &'a BigUint { + type Output = BigUint; + + #[inline] + fn shr(self, rhs: usize) -> BigUint { + biguint_shr(Cow::Borrowed(self), rhs) + } +} + +impl Zero for BigUint { + #[inline] + fn zero() -> BigUint { + BigUint::new(Vec::new()) + } + + #[inline] + fn is_zero(&self) -> bool { + self.data.is_empty() + } +} + +impl One for BigUint { + #[inline] + fn one() -> BigUint { + BigUint::new(vec![1]) + } +} + +impl Unsigned for BigUint {} + +forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add); + +// Only for the Add impl: +#[must_use] +#[inline] +fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit { + let mut b_iter = b.iter(); + let mut carry = 0; + + for ai in a.iter_mut() { + if let Some(bi) = b_iter.next() { + *ai = adc(*ai, *bi, &mut carry); + } else if carry != 0 { + *ai = adc(*ai, 0, &mut carry); + } else { + break; + } + } + + debug_assert!(b_iter.next() == None); + carry +} + +/// /Two argument addition of raw slices: +/// a += b +/// +/// The caller _must_ ensure that a is big enough to store the result - typically this means +/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry. +fn add2(a: &mut [BigDigit], b: &[BigDigit]) { + let carry = __add2(a, b); + + debug_assert!(carry == 0); +} + +// We'd really prefer to avoid using add2/sub2 directly as much as possible - since they make the +// caller entirely responsible for ensuring a's vector is big enough, and that the result is +// normalized, they're rather error prone and verbose: +// +// We could implement the Add and Sub traits for BigUint + BigDigit slices, like below - this works +// great, except that then it becomes the module's public interface, which we probably don't want: +// +// I'm keeping the code commented out, because I think this is worth revisiting: +// +// impl<'a> Add<&'a [BigDigit]> for BigUint { +// type Output = BigUint; +// +// fn add(mut self, other: &[BigDigit]) -> BigUint { +// if self.data.len() < other.len() { +// let extra = other.len() - self.data.len(); +// self.data.extend(repeat(0).take(extra)); +// } +// +// let carry = __add2(&mut self.data[..], other); +// if carry != 0 { +// self.data.push(carry); +// } +// +// self +// } +// } +// + +impl<'a> Add<&'a BigUint> for BigUint { + type Output = BigUint; + + fn add(mut self, other: &BigUint) -> BigUint { + if self.data.len() < other.data.len() { + let extra = other.data.len() - self.data.len(); + self.data.extend(repeat(0).take(extra)); + } + + let carry = __add2(&mut self.data[..], &other.data[..]); + if carry != 0 { + self.data.push(carry); + } + + self + } +} + +forward_all_binop_to_val_ref!(impl Sub for BigUint, sub); + +fn sub2(a: &mut [BigDigit], b: &[BigDigit]) { + let mut b_iter = b.iter(); + let mut borrow = 0; + + for ai in a.iter_mut() { + if let Some(bi) = b_iter.next() { + *ai = sbb(*ai, *bi, &mut borrow); + } else if borrow != 0 { + *ai = sbb(*ai, 0, &mut borrow); + } else { + break; + } + } + + // note: we're _required_ to fail on underflow + assert!(borrow == 0 && b_iter.all(|x| *x == 0), + "Cannot subtract b from a because b is larger than a."); +} + +impl<'a> Sub<&'a BigUint> for BigUint { + type Output = BigUint; + + fn sub(mut self, other: &BigUint) -> BigUint { + sub2(&mut self.data[..], &other.data[..]); + self.normalize() + } +} + +fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> BigInt { + // Normalize: + let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; + let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; + + match cmp_slice(a, b) { + Greater => { + let mut ret = BigUint::from_slice(a); + sub2(&mut ret.data[..], b); + BigInt::from_biguint(Plus, ret.normalize()) + } + Less => { + let mut ret = BigUint::from_slice(b); + sub2(&mut ret.data[..], a); + BigInt::from_biguint(Minus, ret.normalize()) + } + _ => Zero::zero(), + } +} + +forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul); + +/// Three argument multiply accumulate: +/// acc += b * c +fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) { + if c == 0 { + return; + } + + let mut b_iter = b.iter(); + let mut carry = 0; + + for ai in acc.iter_mut() { + if let Some(bi) = b_iter.next() { + *ai = mac_with_carry(*ai, *bi, c, &mut carry); + } else if carry != 0 { + *ai = mac_with_carry(*ai, 0, c, &mut carry); + } else { + break; + } + } + + assert!(carry == 0); +} + +/// Three argument multiply accumulate: +/// acc += b * c +fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) { + let (x, y) = if b.len() < c.len() { + (b, c) + } else { + (c, b) + }; + + // Karatsuba multiplication is slower than long multiplication for small x and y: + // + if x.len() <= 4 { + for (i, xi) in x.iter().enumerate() { + mac_digit(&mut acc[i..], y, *xi); + } + } else { + /* + * Karatsuba multiplication: + * + * The idea is that we break x and y up into two smaller numbers that each have about half + * as many digits, like so (note that multiplying by b is just a shift): + * + * x = x0 + x1 * b + * y = y0 + y1 * b + * + * With some algebra, we can compute x * y with three smaller products, where the inputs to + * each of the smaller products have only about half as many digits as x and y: + * + * x * y = (x0 + x1 * b) * (y0 + y1 * b) + * + * x * y = x0 * y0 + * + x0 * y1 * b + * + x1 * y0 * b + * + x1 * y1 * b^2 + * + * Let p0 = x0 * y0 and p2 = x1 * y1: + * + * x * y = p0 + * + (x0 * y1 + x1 * p0) * b + * + p2 * b^2 + * + * The real trick is that middle term: + * + * x0 * y1 + x1 * y0 + * + * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2 + * + * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2 + * + * Now we complete the square: + * + * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2 + * + * = -((x1 - x0) * (y1 - y0)) + p0 + p2 + * + * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula: + * + * x * y = p0 + * + (p0 + p2 - p1) * b + * + p2 * b^2 + * + * Where the three intermediate products are: + * + * p0 = x0 * y0 + * p1 = (x1 - x0) * (y1 - y0) + * p2 = x1 * y1 + * + * In doing the computation, we take great care to avoid unnecessary temporary variables + * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a + * bit so we can use the same temporary variable for all the intermediate products: + * + * x * y = p2 * b^2 + p2 * b + * + p0 * b + p0 + * - p1 * b + * + * The other trick we use is instead of doing explicit shifts, we slice acc at the + * appropriate offset when doing the add. + */ + + /* + * When x is smaller than y, it's significantly faster to pick b such that x is split in + * half, not y: + */ + let b = x.len() / 2; + let (x0, x1) = x.split_at(b); + let (y0, y1) = y.split_at(b); + + /* We reuse the same BigUint for all the intermediate multiplies: */ + + let len = y.len() + 1; + let mut p = BigUint { data: vec![0; len] }; + + // p2 = x1 * y1 + mac3(&mut p.data[..], x1, y1); + + // Not required, but the adds go faster if we drop any unneeded 0s from the end: + p = p.normalize(); + + add2(&mut acc[b..], &p.data[..]); + add2(&mut acc[b * 2..], &p.data[..]); + + // Zero out p before the next multiply: + p.data.truncate(0); + p.data.extend(repeat(0).take(len)); + + // p0 = x0 * y0 + mac3(&mut p.data[..], x0, y0); + p = p.normalize(); + + add2(&mut acc[..], &p.data[..]); + add2(&mut acc[b..], &p.data[..]); + + // p1 = (x1 - x0) * (y1 - y0) + // We do this one last, since it may be negative and acc can't ever be negative: + let j0 = sub_sign(x1, x0); + let j1 = sub_sign(y1, y0); + + match j0.sign * j1.sign { + Plus => { + p.data.truncate(0); + p.data.extend(repeat(0).take(len)); + + mac3(&mut p.data[..], &j0.data.data[..], &j1.data.data[..]); + p = p.normalize(); + + sub2(&mut acc[b..], &p.data[..]); + }, + Minus => { + mac3(&mut acc[b..], &j0.data.data[..], &j1.data.data[..]); + }, + NoSign => (), + } + } +} + +fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint { + let len = x.len() + y.len() + 1; + let mut prod = BigUint { data: vec![0; len] }; + + mac3(&mut prod.data[..], x, y); + prod.normalize() +} + +impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn mul(self, other: &BigUint) -> BigUint { + mul3(&self.data[..], &other.data[..]) + } +} + +fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) { + let mut rem = 0; + + for d in a.data.iter_mut().rev() { + let (q, r) = div_wide(rem, *d, b); + *d = q; + rem = r; + } + + (a.normalize(), rem) +} + +forward_all_binop_to_ref_ref!(impl Div for BigUint, div); + +impl<'a, 'b> Div<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn div(self, other: &BigUint) -> BigUint { + let (q, _) = self.div_rem(other); + return q; + } +} + +forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem); + +impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint { + type Output = BigUint; + + #[inline] + fn rem(self, other: &BigUint) -> BigUint { + let (_, r) = self.div_rem(other); + return r; + } +} + +impl Neg for BigUint { + type Output = BigUint; + + #[inline] + fn neg(self) -> BigUint { + panic!() + } +} + +impl<'a> Neg for &'a BigUint { + type Output = BigUint; + + #[inline] + fn neg(self) -> BigUint { + panic!() + } +} + +impl CheckedAdd for BigUint { + #[inline] + fn checked_add(&self, v: &BigUint) -> Option { + return Some(self.add(v)); + } +} + +impl CheckedSub for BigUint { + #[inline] + fn checked_sub(&self, v: &BigUint) -> Option { + match self.cmp(v) { + Less => None, + Equal => Some(Zero::zero()), + Greater => Some(self.sub(v)), + } + } +} + +impl CheckedMul for BigUint { + #[inline] + fn checked_mul(&self, v: &BigUint) -> Option { + return Some(self.mul(v)); + } +} + +impl CheckedDiv for BigUint { + #[inline] + fn checked_div(&self, v: &BigUint) -> Option { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } +} + +impl Integer for BigUint { + #[inline] + fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { + self.div_mod_floor(other) + } + + #[inline] + fn div_floor(&self, other: &BigUint) -> BigUint { + let (d, _) = self.div_mod_floor(other); + return d; + } + + #[inline] + fn mod_floor(&self, other: &BigUint) -> BigUint { + let (_, m) = self.div_mod_floor(other); + return m; + } + + fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { + if other.is_zero() { + panic!() + } + if self.is_zero() { + return (Zero::zero(), Zero::zero()); + } + if *other == One::one() { + return (self.clone(), Zero::zero()); + } + + // Required or the q_len calculation below can underflow: + match self.cmp(other) { + Less => return (Zero::zero(), self.clone()), + Equal => return (One::one(), Zero::zero()), + Greater => {} // Do nothing + } + + // This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D: + // + // First, normalize the arguments so the highest bit in the highest digit of the divisor is + // set: the main loop uses the highest digit of the divisor for generating guesses, so we + // want it to be the largest number we can efficiently divide by. + // + let shift = other.data.last().unwrap().leading_zeros() as usize; + let mut a = self << shift; + let b = other << shift; + + // The algorithm works by incrementally calculating "guesses", q0, for part of the + // remainder. Once we have any number q0 such that q0 * b <= a, we can set + // + // q += q0 + // a -= q0 * b + // + // and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder. + // + // q0, our guess, is calculated by dividing the last few digits of a by the last digit of b + // - this should give us a guess that is "close" to the actual quotient, but is possibly + // greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction + // until we have a guess such that q0 & b <= a. + // + + let bn = *b.data.last().unwrap(); + let q_len = a.data.len() - b.data.len() + 1; + let mut q = BigUint { data: vec![0; q_len] }; + + // We reuse the same temporary to avoid hitting the allocator in our inner loop - this is + // sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0 + // can be bigger). + // + let mut tmp = BigUint { data: Vec::with_capacity(2) }; + + for j in (0..q_len).rev() { + /* + * When calculating our next guess q0, we don't need to consider the digits below j + * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from + * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those + * two numbers will be zero in all digits up to (j + b.data.len() - 1). + */ + let offset = j + b.data.len() - 1; + if offset >= a.data.len() { + continue; + } + + /* just avoiding a heap allocation: */ + let mut a0 = tmp; + a0.data.truncate(0); + a0.data.extend(a.data[offset..].iter().cloned()); + + /* + * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts + * implicitly at the end, when adding and subtracting to a and q. Not only do we + * save the cost of the shifts, the rest of the arithmetic gets to work with + * smaller numbers. + */ + let (mut q0, _) = div_rem_digit(a0, bn); + let mut prod = &b * &q0; + + while cmp_slice(&prod.data[..], &a.data[j..]) == Greater { + let one: BigUint = One::one(); + q0 = q0 - one; + prod = prod - &b; + } + + add2(&mut q.data[j..], &q0.data[..]); + sub2(&mut a.data[j..], &prod.data[..]); + a = a.normalize(); + + tmp = q0; + } + + debug_assert!(a < b); + + (q.normalize(), a >> shift) + } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. + /// + /// The result is always positive. + #[inline] + fn gcd(&self, other: &BigUint) -> BigUint { + // Use Euclid's algorithm + let mut m = (*self).clone(); + let mut n = (*other).clone(); + while !m.is_zero() { + let temp = m; + m = n % &temp; + n = temp; + } + return n; + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. + #[inline] + fn lcm(&self, other: &BigUint) -> BigUint { + ((self * other) / self.gcd(other)) + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &BigUint) -> bool { + self.is_multiple_of(other) + } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &BigUint) -> bool { + (self % other).is_zero() + } + + /// Returns `true` if the number is divisible by `2`. + #[inline] + fn is_even(&self) -> bool { + // Considering only the last digit. + match self.data.first() { + Some(x) => x.is_even(), + None => true, + } + } + + /// Returns `true` if the number is not divisible by `2`. + #[inline] + fn is_odd(&self) -> bool { + !self.is_even() + } +} + +impl ToPrimitive for BigUint { + #[inline] + fn to_i64(&self) -> Option { + self.to_u64().and_then(|n| { + // If top bit of u64 is set, it's too large to convert to i64. + if n >> 63 == 0 { + Some(n as i64) + } else { + None + } + }) + } + + // `DoubleBigDigit` size dependent + #[inline] + fn to_u64(&self) -> Option { + match self.data.len() { + 0 => Some(0), + 1 => Some(self.data[0] as u64), + 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) as u64), + _ => None, + } + } + + // `DoubleBigDigit` size dependent + #[inline] + fn to_f32(&self) -> Option { + match self.data.len() { + 0 => Some(f32::zero()), + 1 => Some(self.data[0] as f32), + len => { + // this will prevent any overflow of exponent + if len > (f32::MAX_EXP as usize) / big_digit::BITS { + None + } else { + let exponent = (len - 2) * big_digit::BITS; + // we need 25 significant digits, 24 to be stored and 1 for rounding + // this gives at least 33 significant digits + let mantissa = big_digit::to_doublebigdigit(self.data[len - 1], + self.data[len - 2]); + // this cast handles rounding + let ret = (mantissa as f32) * 2.0.powi(exponent as i32); + if ret.is_infinite() { + None + } else { + Some(ret) + } + } + } + } + } + + // `DoubleBigDigit` size dependent + #[inline] + fn to_f64(&self) -> Option { + match self.data.len() { + 0 => Some(f64::zero()), + 1 => Some(self.data[0] as f64), + 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) as f64), + len => { + // this will prevent any overflow of exponent + if len > (f64::MAX_EXP as usize) / big_digit::BITS { + None + } else { + let mut exponent = (len - 2) * big_digit::BITS; + let mut mantissa = big_digit::to_doublebigdigit(self.data[len - 1], + self.data[len - 2]); + // we need at least 54 significant bit digits, 53 to be stored and 1 for rounding + // so we take enough from the next BigDigit to make it up to 64 + let shift = mantissa.leading_zeros() as usize; + if shift > 0 { + mantissa <<= shift; + mantissa |= self.data[len - 3] as u64 >> (big_digit::BITS - shift); + exponent -= shift; + } + // this cast handles rounding + let ret = (mantissa as f64) * 2.0.powi(exponent as i32); + if ret.is_infinite() { + None + } else { + Some(ret) + } + } + } + } + } +} + +impl FromPrimitive for BigUint { + #[inline] + fn from_i64(n: i64) -> Option { + if n >= 0 { + Some(BigUint::from(n as u64)) + } else { + None + } + } + + #[inline] + fn from_u64(n: u64) -> Option { + Some(BigUint::from(n)) + } + + #[inline] + fn from_f64(mut n: f64) -> Option { + // handle NAN, INFINITY, NEG_INFINITY + if !n.is_finite() { + return None; + } + + // match the rounding of casting from float to int + n = n.trunc(); + + // handle 0.x, -0.x + if n.is_zero() { + return Some(BigUint::zero()); + } + + let (mantissa, exponent, sign) = Float::integer_decode(n); + + if sign == -1 { + return None; + } + + let mut ret = BigUint::from(mantissa); + if exponent > 0 { + ret = ret << exponent as usize; + } else if exponent < 0 { + ret = ret >> (-exponent) as usize; + } + Some(ret) + } +} + +impl From for BigUint { + // `DoubleBigDigit` size dependent + #[inline] + fn from(n: u64) -> Self { + match big_digit::from_doublebigdigit(n) { + (0, 0) => BigUint::zero(), + (0, n0) => BigUint { data: vec![n0] }, + (n1, n0) => BigUint { data: vec![n0, n1] }, + } + } +} + +macro_rules! impl_biguint_from_uint { + ($T:ty) => { + impl From<$T> for BigUint { + #[inline] + fn from(n: $T) -> Self { + BigUint::from(n as u64) + } + } + } +} + +impl_biguint_from_uint!(u8); +impl_biguint_from_uint!(u16); +impl_biguint_from_uint!(u32); +impl_biguint_from_uint!(usize); + +/// A generic trait for converting a value to a `BigUint`. +pub trait ToBigUint { + /// Converts the value of `self` to a `BigUint`. + fn to_biguint(&self) -> Option; +} + +impl ToBigUint for BigInt { + #[inline] + fn to_biguint(&self) -> Option { + if self.sign == Plus { + Some(self.data.clone()) + } else if self.sign == NoSign { + Some(Zero::zero()) + } else { + None + } + } +} + +impl ToBigUint for BigUint { + #[inline] + fn to_biguint(&self) -> Option { + Some(self.clone()) + } +} + +macro_rules! impl_to_biguint { + ($T:ty, $from_ty:path) => { + impl ToBigUint for $T { + #[inline] + fn to_biguint(&self) -> Option { + $from_ty(*self) + } + } + } +} + +impl_to_biguint!(isize, FromPrimitive::from_isize); +impl_to_biguint!(i8, FromPrimitive::from_i8); +impl_to_biguint!(i16, FromPrimitive::from_i16); +impl_to_biguint!(i32, FromPrimitive::from_i32); +impl_to_biguint!(i64, FromPrimitive::from_i64); +impl_to_biguint!(usize, FromPrimitive::from_usize); +impl_to_biguint!(u8, FromPrimitive::from_u8); +impl_to_biguint!(u16, FromPrimitive::from_u16); +impl_to_biguint!(u32, FromPrimitive::from_u32); +impl_to_biguint!(u64, FromPrimitive::from_u64); +impl_to_biguint!(f32, FromPrimitive::from_f32); +impl_to_biguint!(f64, FromPrimitive::from_f64); + +// Extract bitwise digits that evenly divide BigDigit +fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { + debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0); + + let last_i = u.data.len() - 1; + let mask: BigDigit = (1 << bits) - 1; + let digits_per_big_digit = big_digit::BITS / bits; + let digits = (u.bits() + bits - 1) / bits; + let mut res = Vec::with_capacity(digits); + + for mut r in u.data[..last_i].iter().cloned() { + for _ in 0..digits_per_big_digit { + res.push((r & mask) as u8); + r >>= bits; + } + } + + let mut r = u.data[last_i]; + while r != 0 { + res.push((r & mask) as u8); + r >>= bits; + } + + res +} + +// Extract bitwise digits that don't evenly divide BigDigit +fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { + debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0); + + let last_i = u.data.len() - 1; + let mask: DoubleBigDigit = (1 << bits) - 1; + let digits = (u.bits() + bits - 1) / bits; + let mut res = Vec::with_capacity(digits); + + let mut r = 0; + let mut rbits = 0; + for hi in u.data[..last_i].iter().cloned() { + r |= (hi as DoubleBigDigit) << rbits; + rbits += big_digit::BITS; + + while rbits >= bits { + res.push((r & mask) as u8); + r >>= bits; + rbits -= bits; + } + } + + r |= (u.data[last_i] as DoubleBigDigit) << rbits; + while r != 0 { + res.push((r & mask) as u8); + r >>= bits; + } + + res +} + +// Extract little-endian radix digits +#[inline(always)] // forced inline to get const-prop for radix=10 +fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec { + debug_assert!(!u.is_zero() && !radix.is_power_of_two()); + + // Estimate how big the result will be, so we can pre-allocate it. + let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil(); + let mut res = Vec::with_capacity(radix_digits as usize); + let mut digits = u.clone(); + + let (base, power) = get_radix_base(radix); + debug_assert!(base < (1 << 32)); + let base = base as BigDigit; + + while digits.data.len() > 1 { + let (q, mut r) = div_rem_digit(digits, base); + for _ in 0..power { + res.push((r % radix) as u8); + r /= radix; + } + digits = q; + } + + let mut r = digits.data[0]; + while r != 0 { + res.push((r % radix) as u8); + r /= radix; + } + + res +} + +fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec { + assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); + + if u.is_zero() { + return vec![b'0']; + } + + let mut res = if radix.is_power_of_two() { + // Powers of two can use bitwise masks and shifting instead of division + let bits = radix.trailing_zeros() as usize; + if big_digit::BITS % bits == 0 { + to_bitwise_digits_le(u, bits) + } else { + to_inexact_bitwise_digits_le(u, bits) + } + } else if radix == 10 { + // 10 is so common that it's worth separating out for const-propagation. + // Optimizers can often turn constant division into a faster multiplication. + to_radix_digits_le(u, 10) + } else { + to_radix_digits_le(u, radix) + }; + + // Now convert everything to ASCII digits. + for r in &mut res { + debug_assert!((*r as u32) < radix); + if *r < 10 { + *r += b'0'; + } else { + *r += b'a' - 10; + } + } + res +} + +impl BigUint { + /// Creates and initializes a `BigUint`. + /// + /// The digits are in little-endian base 2^32. + #[inline] + pub fn new(digits: Vec) -> BigUint { + BigUint { data: digits }.normalize() + } + + /// Creates and initializes a `BigUint`. + /// + /// The digits are in little-endian base 2^32. + #[inline] + pub fn from_slice(slice: &[BigDigit]) -> BigUint { + BigUint::new(slice.to_vec()) + } + + /// Creates and initializes a `BigUint`. + /// + /// The bytes are in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::BigUint; + /// + /// assert_eq!(BigUint::from_bytes_be(b"A"), + /// BigUint::parse_bytes(b"65", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"AA"), + /// BigUint::parse_bytes(b"16705", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"AB"), + /// BigUint::parse_bytes(b"16706", 10).unwrap()); + /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"), + /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); + /// ``` + #[inline] + pub fn from_bytes_be(bytes: &[u8]) -> BigUint { + if bytes.is_empty() { + Zero::zero() + } else { + let mut v = bytes.to_vec(); + v.reverse(); + BigUint::from_bytes_le(&*v) + } + } + + /// Creates and initializes a `BigUint`. + /// + /// The bytes are in little-endian byte order. + #[inline] + pub fn from_bytes_le(bytes: &[u8]) -> BigUint { + if bytes.is_empty() { + Zero::zero() + } else { + from_bitwise_digits_le(bytes, 8) + } + } + + /// Returns the byte representation of the `BigUint` in little-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); + /// assert_eq!(i.to_bytes_le(), vec![101, 4]); + /// ``` + #[inline] + pub fn to_bytes_le(&self) -> Vec { + if self.is_zero() { + vec![0] + } else { + to_bitwise_digits_le(self, 8) + } + } + + /// Returns the byte representation of the `BigUint` in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); + /// assert_eq!(i.to_bytes_be(), vec![4, 101]); + /// ``` + #[inline] + pub fn to_bytes_be(&self) -> Vec { + let mut v = self.to_bytes_le(); + v.reverse(); + v + } + + /// Returns the integer formatted as a string in the given radix. + /// `radix` must be in the range `[2, 36]`. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::BigUint; + /// + /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); + /// assert_eq!(i.to_str_radix(16), "ff"); + /// ``` + #[inline] + pub fn to_str_radix(&self, radix: u32) -> String { + let mut v = to_str_radix_reversed(self, radix); + v.reverse(); + unsafe { String::from_utf8_unchecked(v) } + } + + /// Creates and initializes a `BigUint`. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{BigUint, ToBigUint}; + /// + /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234)); + /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); + /// assert_eq!(BigUint::parse_bytes(b"G", 16), None); + /// ``` + #[inline] + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { + str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok()) + } + + /// Determines the fewest bits necessary to express the `BigUint`. + pub fn bits(&self) -> usize { + if self.is_zero() { + return 0; + } + let zeros = self.data.last().unwrap().leading_zeros(); + return self.data.len() * big_digit::BITS - zeros as usize; + } + + /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to + /// be nonzero. + #[inline] + fn normalize(mut self) -> BigUint { + while let Some(&0) = self.data.last() { + self.data.pop(); + } + self + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for BigUint { + fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> + where S: serde::Serializer + { + self.data.serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl serde::Deserialize for BigUint { + fn deserialize(deserializer: &mut D) -> Result + where D: serde::Deserializer + { + let data = try!(Vec::deserialize(deserializer)); + Ok(BigUint { data: data }) + } +} + +// `DoubleBigDigit` size dependent +/// Returns the greatest power of the radix <= big_digit::BASE +#[inline] +fn get_radix_base(radix: u32) -> (DoubleBigDigit, usize) { + // To generate this table: + // let target = std::u32::max as u64 + 1; + // for radix in 2u64..37 { + // let power = (target as f64).log(radix as f64) as u32; + // let base = radix.pow(power); + // println!("({:10}, {:2}), // {:2}", base, power, radix); + // } + const BASES: [(DoubleBigDigit, usize); 37] = [(0, 0), + (0, 0), + (4294967296, 32), // 2 + (3486784401, 20), // 3 + (4294967296, 16), // 4 + (1220703125, 13), // 5 + (2176782336, 12), // 6 + (1977326743, 11), // 7 + (1073741824, 10), // 8 + (3486784401, 10), // 9 + (1000000000, 9), // 10 + (2357947691, 9), // 11 + (429981696, 8), // 12 + (815730721, 8), // 13 + (1475789056, 8), // 14 + (2562890625, 8), // 15 + (4294967296, 8), // 16 + (410338673, 7), // 17 + (612220032, 7), // 18 + (893871739, 7), // 19 + (1280000000, 7), // 20 + (1801088541, 7), // 21 + (2494357888, 7), // 22 + (3404825447, 7), // 23 + (191102976, 6), // 24 + (244140625, 6), // 25 + (308915776, 6), // 26 + (387420489, 6), // 27 + (481890304, 6), // 28 + (594823321, 6), // 29 + (729000000, 6), // 30 + (887503681, 6), // 31 + (1073741824, 6), // 32 + (1291467969, 6), // 33 + (1544804416, 6), // 34 + (1838265625, 6), // 35 + (2176782336, 6) /* 36 */]; + + assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); + BASES[radix as usize] +} + +/// A Sign is a `BigInt`'s composing element. +#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)] +#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] +pub enum Sign { + Minus, + NoSign, + Plus, +} + +impl Neg for Sign { + type Output = Sign; + + /// Negate Sign value. + #[inline] + fn neg(self) -> Sign { + match self { + Minus => Plus, + NoSign => NoSign, + Plus => Minus, + } + } +} + +impl Mul for Sign { + type Output = Sign; + + #[inline] + fn mul(self, other: Sign) -> Sign { + match (self, other) { + (NoSign, _) | (_, NoSign) => NoSign, + (Plus, Plus) | (Minus, Minus) => Plus, + (Plus, Minus) | (Minus, Plus) => Minus, + } + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for Sign { + fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> + where S: serde::Serializer + { + match *self { + Sign::Minus => (-1i8).serialize(serializer), + Sign::NoSign => 0i8.serialize(serializer), + Sign::Plus => 1i8.serialize(serializer), + } + } +} + +#[cfg(feature = "serde")] +impl serde::Deserialize for Sign { + fn deserialize(deserializer: &mut D) -> Result + where D: serde::Deserializer + { + use serde::de::Error; + + let sign: i8 = try!(serde::Deserialize::deserialize(deserializer)); + match sign { + -1 => Ok(Sign::Minus), + 0 => Ok(Sign::NoSign), + 1 => Ok(Sign::Plus), + _ => Err(D::Error::invalid_value("sign must be -1, 0, or 1")), + } + } +} + +/// A big signed integer type. +#[derive(Clone, Debug, Hash)] +#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] +pub struct BigInt { + sign: Sign, + data: BigUint, +} + +impl PartialEq for BigInt { + #[inline] + fn eq(&self, other: &BigInt) -> bool { + self.cmp(other) == Equal + } +} + +impl Eq for BigInt {} + +impl PartialOrd for BigInt { + #[inline] + fn partial_cmp(&self, other: &BigInt) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for BigInt { + #[inline] + fn cmp(&self, other: &BigInt) -> Ordering { + let scmp = self.sign.cmp(&other.sign); + if scmp != Equal { + return scmp; + } + + match self.sign { + NoSign => Equal, + Plus => self.data.cmp(&other.data), + Minus => other.data.cmp(&self.data), + } + } +} + +impl Default for BigInt { + #[inline] + fn default() -> BigInt { + Zero::zero() + } +} + +impl fmt::Display for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10)) + } +} + +impl fmt::Binary for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2)) + } +} + +impl fmt::Octal for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8)) + } +} + +impl fmt::LowerHex for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16)) + } +} + +impl fmt::UpperHex for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad_integral(!self.is_negative(), + "0x", + &self.data.to_str_radix(16).to_ascii_uppercase()) + } +} + +impl FromStr for BigInt { + type Err = ParseBigIntError; + + #[inline] + fn from_str(s: &str) -> Result { + BigInt::from_str_radix(s, 10) + } +} + +impl Num for BigInt { + type FromStrRadixErr = ParseBigIntError; + + /// Creates and initializes a BigInt. + #[inline] + fn from_str_radix(mut s: &str, radix: u32) -> Result { + let sign = if s.starts_with('-') { + let tail = &s[1..]; + if !tail.starts_with('+') { + s = tail + } + Minus + } else { + Plus + }; + let bu = try!(BigUint::from_str_radix(s, radix)); + Ok(BigInt::from_biguint(sign, bu)) + } +} + +impl Shl for BigInt { + type Output = BigInt; + + #[inline] + fn shl(self, rhs: usize) -> BigInt { + (&self) << rhs + } +} + +impl<'a> Shl for &'a BigInt { + type Output = BigInt; + + #[inline] + fn shl(self, rhs: usize) -> BigInt { + BigInt::from_biguint(self.sign, &self.data << rhs) + } +} + +impl Shr for BigInt { + type Output = BigInt; + + #[inline] + fn shr(self, rhs: usize) -> BigInt { + BigInt::from_biguint(self.sign, self.data >> rhs) + } +} + +impl<'a> Shr for &'a BigInt { + type Output = BigInt; + + #[inline] + fn shr(self, rhs: usize) -> BigInt { + BigInt::from_biguint(self.sign, &self.data >> rhs) + } +} + +impl Zero for BigInt { + #[inline] + fn zero() -> BigInt { + BigInt::from_biguint(NoSign, Zero::zero()) + } + + #[inline] + fn is_zero(&self) -> bool { + self.sign == NoSign + } +} + +impl One for BigInt { + #[inline] + fn one() -> BigInt { + BigInt::from_biguint(Plus, One::one()) + } +} + +impl Signed for BigInt { + #[inline] + fn abs(&self) -> BigInt { + match self.sign { + Plus | NoSign => self.clone(), + Minus => BigInt::from_biguint(Plus, self.data.clone()), + } + } + + #[inline] + fn abs_sub(&self, other: &BigInt) -> BigInt { + if *self <= *other { + Zero::zero() + } else { + self - other + } + } + + #[inline] + fn signum(&self) -> BigInt { + match self.sign { + Plus => BigInt::from_biguint(Plus, One::one()), + Minus => BigInt::from_biguint(Minus, One::one()), + NoSign => Zero::zero(), + } + } + + #[inline] + fn is_positive(&self) -> bool { + self.sign == Plus + } + + #[inline] + fn is_negative(&self) -> bool { + self.sign == Minus + } +} + +// We want to forward to BigUint::add, but it's not clear how that will go until +// we compare both sign and magnitude. So we duplicate this body for every +// val/ref combination, deferring that decision to BigUint's own forwarding. +macro_rules! bigint_add { + ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { + match ($a.sign, $b.sign) { + (_, NoSign) => $a_owned, + (NoSign, _) => $b_owned, + // same sign => keep the sign with the sum of magnitudes + (Plus, Plus) | (Minus, Minus) => + BigInt::from_biguint($a.sign, $a_data + $b_data), + // opposite signs => keep the sign of the larger with the difference of magnitudes + (Plus, Minus) | (Minus, Plus) => + match $a.data.cmp(&$b.data) { + Less => BigInt::from_biguint($b.sign, $b_data - $a_data), + Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), + Equal => Zero::zero(), + }, + } + }; +} + +impl<'a, 'b> Add<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: &BigInt) -> BigInt { + bigint_add!(self, + self.clone(), + &self.data, + other, + other.clone(), + &other.data) + } +} + +impl<'a> Add for &'a BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: BigInt) -> BigInt { + bigint_add!(self, self.clone(), &self.data, other, other, other.data) + } +} + +impl<'a> Add<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: &BigInt) -> BigInt { + bigint_add!(self, self, self.data, other, other.clone(), &other.data) + } +} + +impl Add for BigInt { + type Output = BigInt; + + #[inline] + fn add(self, other: BigInt) -> BigInt { + bigint_add!(self, self, self.data, other, other, other.data) + } +} + +// We want to forward to BigUint::sub, but it's not clear how that will go until +// we compare both sign and magnitude. So we duplicate this body for every +// val/ref combination, deferring that decision to BigUint's own forwarding. +macro_rules! bigint_sub { + ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { + match ($a.sign, $b.sign) { + (_, NoSign) => $a_owned, + (NoSign, _) => -$b_owned, + // opposite signs => keep the sign of the left with the sum of magnitudes + (Plus, Minus) | (Minus, Plus) => + BigInt::from_biguint($a.sign, $a_data + $b_data), + // same sign => keep or toggle the sign of the left with the difference of magnitudes + (Plus, Plus) | (Minus, Minus) => + match $a.data.cmp(&$b.data) { + Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data), + Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), + Equal => Zero::zero(), + }, + } + }; +} + +impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: &BigInt) -> BigInt { + bigint_sub!(self, + self.clone(), + &self.data, + other, + other.clone(), + &other.data) + } +} + +impl<'a> Sub for &'a BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + bigint_sub!(self, self.clone(), &self.data, other, other, other.data) + } +} + +impl<'a> Sub<&'a BigInt> for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: &BigInt) -> BigInt { + bigint_sub!(self, self, self.data, other, other.clone(), &other.data) + } +} + +impl Sub for BigInt { + type Output = BigInt; + + #[inline] + fn sub(self, other: BigInt) -> BigInt { + bigint_sub!(self, self, self.data, other, other, other.data) + } +} + +forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul); + +impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn mul(self, other: &BigInt) -> BigInt { + BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data) + } +} + +forward_all_binop_to_ref_ref!(impl Div for BigInt, div); + +impl<'a, 'b> Div<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn div(self, other: &BigInt) -> BigInt { + let (q, _) = self.div_rem(other); + q + } +} + +forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem); + +impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt { + type Output = BigInt; + + #[inline] + fn rem(self, other: &BigInt) -> BigInt { + let (_, r) = self.div_rem(other); + r + } +} + +impl Neg for BigInt { + type Output = BigInt; + + #[inline] + fn neg(mut self) -> BigInt { + self.sign = -self.sign; + self + } +} + +impl<'a> Neg for &'a BigInt { + type Output = BigInt; + + #[inline] + fn neg(self) -> BigInt { + -self.clone() + } +} + +impl CheckedAdd for BigInt { + #[inline] + fn checked_add(&self, v: &BigInt) -> Option { + return Some(self.add(v)); + } +} + +impl CheckedSub for BigInt { + #[inline] + fn checked_sub(&self, v: &BigInt) -> Option { + return Some(self.sub(v)); + } +} + +impl CheckedMul for BigInt { + #[inline] + fn checked_mul(&self, v: &BigInt) -> Option { + return Some(self.mul(v)); + } +} + +impl CheckedDiv for BigInt { + #[inline] + fn checked_div(&self, v: &BigInt) -> Option { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } +} + +impl Integer for BigInt { + #[inline] + fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { + // r.sign == self.sign + let (d_ui, r_ui) = self.data.div_mod_floor(&other.data); + let d = BigInt::from_biguint(self.sign, d_ui); + let r = BigInt::from_biguint(self.sign, r_ui); + if other.is_negative() { + (-d, r) + } else { + (d, r) + } + } + + #[inline] + fn div_floor(&self, other: &BigInt) -> BigInt { + let (d, _) = self.div_mod_floor(other); + d + } + + #[inline] + fn mod_floor(&self, other: &BigInt) -> BigInt { + let (_, m) = self.div_mod_floor(other); + m + } + + fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { + // m.sign == other.sign + let (d_ui, m_ui) = self.data.div_rem(&other.data); + let d = BigInt::from_biguint(Plus, d_ui); + let m = BigInt::from_biguint(Plus, m_ui); + let one: BigInt = One::one(); + match (self.sign, other.sign) { + (_, NoSign) => panic!(), + (Plus, Plus) | (NoSign, Plus) => (d, m), + (Plus, Minus) | (NoSign, Minus) => { + if m.is_zero() { + (-d, Zero::zero()) + } else { + (-d - one, m + other) + } + } + (Minus, Plus) => { + if m.is_zero() { + (-d, Zero::zero()) + } else { + (-d - one, other - m) + } + } + (Minus, Minus) => (d, -m), + } + } + + /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. + /// + /// The result is always positive. + #[inline] + fn gcd(&self, other: &BigInt) -> BigInt { + BigInt::from_biguint(Plus, self.data.gcd(&other.data)) + } + + /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. + #[inline] + fn lcm(&self, other: &BigInt) -> BigInt { + BigInt::from_biguint(Plus, self.data.lcm(&other.data)) + } + + /// Deprecated, use `is_multiple_of` instead. + #[inline] + fn divides(&self, other: &BigInt) -> bool { + return self.is_multiple_of(other); + } + + /// Returns `true` if the number is a multiple of `other`. + #[inline] + fn is_multiple_of(&self, other: &BigInt) -> bool { + self.data.is_multiple_of(&other.data) + } + + /// Returns `true` if the number is divisible by `2`. + #[inline] + fn is_even(&self) -> bool { + self.data.is_even() + } + + /// Returns `true` if the number is not divisible by `2`. + #[inline] + fn is_odd(&self) -> bool { + self.data.is_odd() + } +} + +impl ToPrimitive for BigInt { + #[inline] + fn to_i64(&self) -> Option { + match self.sign { + Plus => self.data.to_i64(), + NoSign => Some(0), + Minus => { + self.data.to_u64().and_then(|n| { + let m: u64 = 1 << 63; + if n < m { + Some(-(n as i64)) + } else if n == m { + Some(i64::MIN) + } else { + None + } + }) + } + } + } + + #[inline] + fn to_u64(&self) -> Option { + match self.sign { + Plus => self.data.to_u64(), + NoSign => Some(0), + Minus => None, + } + } + + #[inline] + fn to_f32(&self) -> Option { + self.data.to_f32().map(|n| { + if self.sign == Minus { + -n + } else { + n + } + }) + } + + #[inline] + fn to_f64(&self) -> Option { + self.data.to_f64().map(|n| { + if self.sign == Minus { + -n + } else { + n + } + }) + } +} + +impl FromPrimitive for BigInt { + #[inline] + fn from_i64(n: i64) -> Option { + Some(BigInt::from(n)) + } + + #[inline] + fn from_u64(n: u64) -> Option { + Some(BigInt::from(n)) + } + + #[inline] + fn from_f64(n: f64) -> Option { + if n >= 0.0 { + BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x)) + } else { + BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x)) + } + } +} + +impl From for BigInt { + #[inline] + fn from(n: i64) -> Self { + if n >= 0 { + BigInt::from(n as u64) + } else { + let u = u64::MAX - (n as u64) + 1; + BigInt { + sign: Minus, + data: BigUint::from(u), + } + } + } +} + +macro_rules! impl_bigint_from_int { + ($T:ty) => { + impl From<$T> for BigInt { + #[inline] + fn from(n: $T) -> Self { + BigInt::from(n as i64) + } + } + } +} + +impl_bigint_from_int!(i8); +impl_bigint_from_int!(i16); +impl_bigint_from_int!(i32); +impl_bigint_from_int!(isize); + +impl From for BigInt { + #[inline] + fn from(n: u64) -> Self { + if n > 0 { + BigInt { + sign: Plus, + data: BigUint::from(n), + } + } else { + BigInt::zero() + } + } +} + +macro_rules! impl_bigint_from_uint { + ($T:ty) => { + impl From<$T> for BigInt { + #[inline] + fn from(n: $T) -> Self { + BigInt::from(n as u64) + } + } + } +} + +impl_bigint_from_uint!(u8); +impl_bigint_from_uint!(u16); +impl_bigint_from_uint!(u32); +impl_bigint_from_uint!(usize); + +impl From for BigInt { + #[inline] + fn from(n: BigUint) -> Self { + if n.is_zero() { + BigInt::zero() + } else { + BigInt { + sign: Plus, + data: n, + } + } + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for BigInt { + fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> + where S: serde::Serializer + { + (self.sign, &self.data).serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl serde::Deserialize for BigInt { + fn deserialize(deserializer: &mut D) -> Result + where D: serde::Deserializer + { + let (sign, data) = try!(serde::Deserialize::deserialize(deserializer)); + Ok(BigInt { + sign: sign, + data: data, + }) + } +} + +/// A generic trait for converting a value to a `BigInt`. +pub trait ToBigInt { + /// Converts the value of `self` to a `BigInt`. + fn to_bigint(&self) -> Option; +} + +impl ToBigInt for BigInt { + #[inline] + fn to_bigint(&self) -> Option { + Some(self.clone()) + } +} + +impl ToBigInt for BigUint { + #[inline] + fn to_bigint(&self) -> Option { + if self.is_zero() { + Some(Zero::zero()) + } else { + Some(BigInt { + sign: Plus, + data: self.clone(), + }) + } + } +} + +macro_rules! impl_to_bigint { + ($T:ty, $from_ty:path) => { + impl ToBigInt for $T { + #[inline] + fn to_bigint(&self) -> Option { + $from_ty(*self) + } + } + } +} + +impl_to_bigint!(isize, FromPrimitive::from_isize); +impl_to_bigint!(i8, FromPrimitive::from_i8); +impl_to_bigint!(i16, FromPrimitive::from_i16); +impl_to_bigint!(i32, FromPrimitive::from_i32); +impl_to_bigint!(i64, FromPrimitive::from_i64); +impl_to_bigint!(usize, FromPrimitive::from_usize); +impl_to_bigint!(u8, FromPrimitive::from_u8); +impl_to_bigint!(u16, FromPrimitive::from_u16); +impl_to_bigint!(u32, FromPrimitive::from_u32); +impl_to_bigint!(u64, FromPrimitive::from_u64); +impl_to_bigint!(f32, FromPrimitive::from_f32); +impl_to_bigint!(f64, FromPrimitive::from_f64); + +pub trait RandBigInt { + /// Generate a random `BigUint` of the given bit size. + fn gen_biguint(&mut self, bit_size: usize) -> BigUint; + + /// Generate a random BigInt of the given bit size. + fn gen_bigint(&mut self, bit_size: usize) -> BigInt; + + /// Generate a random `BigUint` less than the given bound. Fails + /// when the bound is zero. + fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; + + /// Generate a random `BigUint` within the given range. The lower + /// bound is inclusive; the upper bound is exclusive. Fails when + /// the upper bound is not greater than the lower bound. + fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; + + /// Generate a random `BigInt` within the given range. The lower + /// bound is inclusive; the upper bound is exclusive. Fails when + /// the upper bound is not greater than the lower bound. + fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; +} + +#[cfg(any(feature = "rand", test))] +impl RandBigInt for R { + fn gen_biguint(&mut self, bit_size: usize) -> BigUint { + let (digits, rem) = bit_size.div_rem(&big_digit::BITS); + let mut data = Vec::with_capacity(digits + 1); + for _ in 0..digits { + data.push(self.gen()); + } + if rem > 0 { + let final_digit: BigDigit = self.gen(); + data.push(final_digit >> (big_digit::BITS - rem)); + } + BigUint::new(data) + } + + fn gen_bigint(&mut self, bit_size: usize) -> BigInt { + // Generate a random BigUint... + let biguint = self.gen_biguint(bit_size); + // ...and then randomly assign it a Sign... + let sign = if biguint.is_zero() { + // ...except that if the BigUint is zero, we need to try + // again with probability 0.5. This is because otherwise, + // the probability of generating a zero BigInt would be + // double that of any other number. + if self.gen() { + return self.gen_bigint(bit_size); + } else { + NoSign + } + } else if self.gen() { + Plus + } else { + Minus + }; + BigInt::from_biguint(sign, biguint) + } + + fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { + assert!(!bound.is_zero()); + let bits = bound.bits(); + loop { + let n = self.gen_biguint(bits); + if n < *bound { + return n; + } + } + } + + fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint { + assert!(*lbound < *ubound); + return lbound + self.gen_biguint_below(&(ubound - lbound)); + } + + fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt { + assert!(*lbound < *ubound); + let delta = (ubound - lbound).to_biguint().unwrap(); + return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap(); + } +} + +impl BigInt { + /// Creates and initializes a BigInt. + /// + /// The digits are in little-endian base 2^32. + #[inline] + pub fn new(sign: Sign, digits: Vec) -> BigInt { + BigInt::from_biguint(sign, BigUint::new(digits)) + } + + /// Creates and initializes a `BigInt`. + /// + /// The digits are in little-endian base 2^32. + #[inline] + pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt { + if sign == NoSign || data.is_zero() { + return BigInt { + sign: NoSign, + data: Zero::zero(), + }; + } + BigInt { + sign: sign, + data: data, + } + } + + /// Creates and initializes a `BigInt`. + #[inline] + pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_slice(slice)) + } + + /// Creates and initializes a `BigInt`. + /// + /// The bytes are in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{BigInt, Sign}; + /// + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"), + /// BigInt::parse_bytes(b"65", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"), + /// BigInt::parse_bytes(b"16705", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"), + /// BigInt::parse_bytes(b"16706", 10).unwrap()); + /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"), + /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); + /// ``` + #[inline] + pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes)) + } + + /// Creates and initializes a `BigInt`. + /// + /// The bytes are in little-endian byte order. + #[inline] + pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt { + BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes)) + } + + /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{ToBigInt, Sign}; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); + /// ``` + #[inline] + pub fn to_bytes_le(&self) -> (Sign, Vec) { + (self.sign, self.data.to_bytes_le()) + } + + /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{ToBigInt, Sign}; + /// + /// let i = -1125.to_bigint().unwrap(); + /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); + /// ``` + #[inline] + pub fn to_bytes_be(&self) -> (Sign, Vec) { + (self.sign, self.data.to_bytes_be()) + } + + /// Returns the integer formatted as a string in the given radix. + /// `radix` must be in the range `[2, 36]`. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::BigInt; + /// + /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); + /// assert_eq!(i.to_str_radix(16), "ff"); + /// ``` + #[inline] + pub fn to_str_radix(&self, radix: u32) -> String { + let mut v = to_str_radix_reversed(&self.data, radix); + + if self.is_negative() { + v.push(b'-'); + } + + v.reverse(); + unsafe { String::from_utf8_unchecked(v) } + } + + /// Returns the sign of the `BigInt` as a `Sign`. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{ToBigInt, Sign}; + /// + /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus); + /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus); + /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign); + /// ``` + #[inline] + pub fn sign(&self) -> Sign { + self.sign + } + + /// Creates and initializes a `BigInt`. + /// + /// # Examples + /// + /// ``` + /// use num::bigint::{BigInt, ToBigInt}; + /// + /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234)); + /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); + /// assert_eq!(BigInt::parse_bytes(b"G", 16), None); + /// ``` + #[inline] + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { + str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok()) + } + + + /// Converts this `BigInt` into a `BigUint`, if it's not negative. + #[inline] + pub fn to_biguint(&self) -> Option { + match self.sign { + Plus => Some(self.data.clone()), + NoSign => Some(Zero::zero()), + Minus => None, + } + } + + #[inline] + pub fn checked_add(&self, v: &BigInt) -> Option { + return Some(self.add(v)); + } + + #[inline] + pub fn checked_sub(&self, v: &BigInt) -> Option { + return Some(self.sub(v)); + } + + #[inline] + pub fn checked_mul(&self, v: &BigInt) -> Option { + return Some(self.mul(v)); + } + + #[inline] + pub fn checked_div(&self, v: &BigInt) -> Option { + if v.is_zero() { + return None; + } + return Some(self.div(v)); + } +} + +#[derive(Debug, PartialEq)] +pub enum ParseBigIntError { + ParseInt(ParseIntError), + Other, +} + +impl fmt::Display for ParseBigIntError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + &ParseBigIntError::ParseInt(ref e) => e.fmt(f), + &ParseBigIntError::Other => "failed to parse provided string".fmt(f), + } + } +} + +impl Error for ParseBigIntError { + fn description(&self) -> &str { + "failed to parse bigint/biguint" + } +} + +impl From for ParseBigIntError { + fn from(err: ParseIntError) -> ParseBigIntError { + ParseBigIntError::ParseInt(err) + } +} + +#[cfg(test)] +mod biguint_tests { + use Integer; + use super::{BigDigit, BigUint, ToBigUint, big_digit}; + use super::{BigInt, RandBigInt, ToBigInt}; + use super::Sign::Plus; + + use std::cmp::Ordering::{Less, Equal, Greater}; + use std::{f32, f64}; + use std::i64; + use std::iter::repeat; + use std::str::FromStr; + use std::{u8, u16, u32, u64, usize}; + + use rand::thread_rng; + use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv}; + use {ToPrimitive, FromPrimitive}; + use Float; + + /// Assert that an op works for all val/ref combinations + macro_rules! assert_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_eq!((&$left) $op (&$right), $expected); + assert_eq!((&$left) $op $right.clone(), $expected); + assert_eq!($left.clone() $op (&$right), $expected); + assert_eq!($left.clone() $op $right.clone(), $expected); + }; + } + + #[test] + fn test_from_slice() { + fn check(slice: &[BigDigit], data: &[BigDigit]) { + assert!(BigUint::from_slice(slice).data == data); + } + check(&[1], &[1]); + check(&[0, 0, 0], &[]); + check(&[1, 2, 0, 0], &[1, 2]); + check(&[0, 0, 1, 2], &[0, 0, 1, 2]); + check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); + check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); + } + + #[test] + fn test_from_bytes_be() { + fn check(s: &str, result: &str) { + assert_eq!(BigUint::from_bytes_be(s.as_bytes()), + BigUint::parse_bytes(result.as_bytes(), 10).unwrap()); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero()); + } + + #[test] + fn test_to_bytes_be() { + fn check(s: &str, result: &str) { + let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); + assert_eq!(b.to_bytes_be(), s.as_bytes()); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + let b: BigUint = Zero::zero(); + assert_eq!(b.to_bytes_be(), [0]); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]); + } + + #[test] + fn test_from_bytes_le() { + fn check(s: &str, result: &str) { + assert_eq!(BigUint::from_bytes_le(s.as_bytes()), + BigUint::parse_bytes(result.as_bytes(), 10).unwrap()); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero()); + } + + #[test] + fn test_to_bytes_le() { + fn check(s: &str, result: &str) { + let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); + assert_eq!(b.to_bytes_le(), s.as_bytes()); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + let b: BigUint = Zero::zero(); + assert_eq!(b.to_bytes_le(), [0]); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]); + } + + #[test] + fn test_cmp() { + let data: [&[_]; 7] = [&[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1]]; + let data: Vec = data.iter().map(|v| BigUint::from_slice(*v)).collect(); + for (i, ni) in data.iter().enumerate() { + for (j0, nj) in data[i..].iter().enumerate() { + let j = j0 + i; + if i == j { + assert_eq!(ni.cmp(nj), Equal); + assert_eq!(nj.cmp(ni), Equal); + assert_eq!(ni, nj); + assert!(!(ni != nj)); + assert!(ni <= nj); + assert!(ni >= nj); + assert!(!(ni < nj)); + assert!(!(ni > nj)); + } else { + assert_eq!(ni.cmp(nj), Less); + assert_eq!(nj.cmp(ni), Greater); + + assert!(!(ni == nj)); + assert!(ni != nj); + + assert!(ni <= nj); + assert!(!(ni >= nj)); + assert!(ni < nj); + assert!(!(ni > nj)); + + assert!(!(nj <= ni)); + assert!(nj >= ni); + assert!(!(nj < ni)); + assert!(nj > ni); + } + } + } + } + + #[test] + fn test_hash() { + let a = BigUint::new(vec![]); + let b = BigUint::new(vec![0]); + let c = BigUint::new(vec![1]); + let d = BigUint::new(vec![1, 0, 0, 0, 0, 0]); + let e = BigUint::new(vec![0, 0, 0, 0, 0, 1]); + assert!(::hash(&a) == ::hash(&b)); + assert!(::hash(&b) != ::hash(&c)); + assert!(::hash(&c) == ::hash(&d)); + assert!(::hash(&d) != ::hash(&e)); + } + + const BIT_TESTS: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[// LEFT RIGHT AND OR XOR + (&[], &[], &[], &[], &[]), + (&[268, 482, 17], + &[964, 54], + &[260, 34], + &[972, 502, 17], + &[712, 468, 17])]; + + #[test] + fn test_bitand() { + for elm in BIT_TESTS { + let (a_vec, b_vec, c_vec, _, _) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a & b == c); + assert_op!(b & a == c); + } + } + + #[test] + fn test_bitor() { + for elm in BIT_TESTS { + let (a_vec, b_vec, _, c_vec, _) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a | b == c); + assert_op!(b | a == c); + } + } + + #[test] + fn test_bitxor() { + for elm in BIT_TESTS { + let (a_vec, b_vec, _, _, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a ^ b == c); + assert_op!(b ^ a == c); + assert_op!(a ^ c == b); + assert_op!(c ^ a == b); + assert_op!(b ^ c == a); + assert_op!(c ^ b == a); + } + } + + #[test] + fn test_shl() { + fn check(s: &str, shift: usize, ans: &str) { + let opt_biguint = BigUint::from_str_radix(s, 16).ok(); + let bu = (opt_biguint.unwrap() << shift).to_str_radix(16); + assert_eq!(bu, ans); + } + + check("0", 3, "0"); + check("1", 3, "8"); + + check("1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "8\ + 0000\ + 0000\ + 0000\ + 0008\ + 0000\ + 0000\ + 0000\ + 0008"); + check("1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4\ + 0000\ + 0004\ + 0000\ + 0004"); + check("1\ + 0001\ + 0001", + 1, + "2\ + 0002\ + 0002"); + + check("\ + 4000\ + 0000\ + 0000\ + 0000", + 3, + "2\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000\ + 0000", + 2, + "1\ + 0000\ + 0000"); + check("4000", + 2, + "1\ + 0000"); + + check("4000\ + 0000\ + 0000\ + 0000", + 67, + "2\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000\ + 0000", + 35, + "2\ + 0000\ + 0000\ + 0000\ + 0000"); + check("4000", + 19, + "2\ + 0000\ + 0000"); + + check("fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210", + 4, + "f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100"); + check("88887777666655554444333322221111", + 16, + "888877776666555544443333222211110000"); + } + + #[test] + fn test_shr() { + fn check(s: &str, shift: usize, ans: &str) { + let opt_biguint = BigUint::from_str_radix(s, 16).ok(); + let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16); + assert_eq!(bu, ans); + } + + check("0", 3, "0"); + check("f", 3, "1"); + + check("1\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 3, + "2000\ + 0000\ + 0000\ + 0000\ + 2000\ + 0000\ + 0000\ + 0000"); + check("1\ + 0000\ + 0001\ + 0000\ + 0001", + 2, + "4000\ + 0000\ + 4000\ + 0000"); + check("1\ + 0001\ + 0001", + 1, + "8000\ + 8000"); + + check("2\ + 0000\ + 0000\ + 0000\ + 0001\ + 0000\ + 0000\ + 0000\ + 0001", + 67, + "4000\ + 0000\ + 0000\ + 0000"); + check("2\ + 0000\ + 0001\ + 0000\ + 0001", + 35, + "4000\ + 0000"); + check("2\ + 0001\ + 0001", + 19, + "4000"); + + check("1\ + 0000\ + 0000\ + 0000\ + 0000", + 1, + "8000\ + 0000\ + 0000\ + 0000"); + check("1\ + 0000\ + 0000", + 1, + "8000\ + 0000"); + check("1\ + 0000", + 1, + "8000"); + check("f\ + edcb\ + a987\ + 6543\ + 210f\ + edcb\ + a987\ + 6543\ + 2100", + 4, + "fedc\ + ba98\ + 7654\ + 3210\ + fedc\ + ba98\ + 7654\ + 3210"); + + check("888877776666555544443333222211110000", + 16, + "88887777666655554444333322221111"); + } + + const N1: BigDigit = -1i32 as BigDigit; + const N2: BigDigit = -2i32 as BigDigit; + + // `DoubleBigDigit` size dependent + #[test] + fn test_convert_i64() { + fn check(b1: BigUint, i: i64) { + let b2: BigUint = FromPrimitive::from_i64(i).unwrap(); + assert!(b1 == b2); + assert!(b1.to_i64().unwrap() == i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i64::MAX.to_biguint().unwrap(), i64::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), (1 << (0 * big_digit::BITS))); + check(BigUint::new(vec![N1]), (1 << (1 * big_digit::BITS)) - 1); + check(BigUint::new(vec![0, 1]), (1 << (1 * big_digit::BITS))); + check(BigUint::new(vec![N1, N1 >> 1]), i64::MAX); + + assert_eq!(i64::MIN.to_biguint(), None); + assert_eq!(BigUint::new(vec![N1, N1]).to_i64(), None); + assert_eq!(BigUint::new(vec![0, 0, 1]).to_i64(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1]).to_i64(), None); + } + + // `DoubleBigDigit` size dependent + #[test] + fn test_convert_u64() { + fn check(b1: BigUint, u: u64) { + let b2: BigUint = FromPrimitive::from_u64(u).unwrap(); + assert!(b1 == b2); + assert!(b1.to_u64().unwrap() == u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u64::MIN.to_biguint().unwrap(), u64::MIN); + check(u64::MAX.to_biguint().unwrap(), u64::MAX); + + check(BigUint::new(vec![]), 0); + check(BigUint::new(vec![1]), (1 << (0 * big_digit::BITS))); + check(BigUint::new(vec![N1]), (1 << (1 * big_digit::BITS)) - 1); + check(BigUint::new(vec![0, 1]), (1 << (1 * big_digit::BITS))); + check(BigUint::new(vec![N1, N1]), u64::MAX); + + assert_eq!(BigUint::new(vec![0, 0, 1]).to_u64(), None); + assert_eq!(BigUint::new(vec![N1, N1, N1]).to_u64(), None); + } + + #[test] + fn test_convert_f32() { + fn check(b1: &BigUint, f: f32) { + let b2 = BigUint::from_f32(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f32().unwrap(), f); + } + + check(&BigUint::zero(), 0.0); + check(&BigUint::one(), 1.0); + check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0); + check(&BigUint::from(1u64 << 32), 2.0.powi(32)); + check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); + check(&((BigUint::one() << 100) + (BigUint::one() << 123)), + 2.0.powi(100) + 2.0.powi(123)); + check(&(BigUint::one() << 127), 2.0.powi(127)); + check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); + + // keeping all 24 digits with the bits at different offsets to the BigDigits + let x: u32 = 0b00000000101111011111011011011101; + let mut f = x as f32; + let mut b = BigUint::from(x); + for _ in 0..64 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 + let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigUint::from(n).to_f32(), Some(n as f32)); + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 25) - 1) as f32; + let mut b = BigUint::from(1u64 << 25); + for _ in 0..64 { + assert_eq!(b.to_f32(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigUint::from_f32(-1.0), None); + assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE / 2.0), + Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32))); + assert_eq!(BigUint::from_f32(f32::consts::PI), + Some(BigUint::from(3u32))); + + // special float values + assert_eq!(BigUint::from_f32(f32::NAN), None); + assert_eq!(BigUint::from_f32(f32::INFINITY), None); + assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None); + assert_eq!(BigUint::from_f32(f32::MIN), None); + + // largest BigUint that will round to a finite f32 value + let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25)); + assert_eq!(big_num.to_f32(), Some(f32::MAX)); + assert_eq!((big_num + BigUint::one()).to_f32(), None); + + assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None); + assert_eq!((BigUint::one() << 128).to_f32(), None); + } + + #[test] + fn test_convert_f64() { + fn check(b1: &BigUint, f: f64) { + let b2 = BigUint::from_f64(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f64().unwrap(), f); + } + + check(&BigUint::zero(), 0.0); + check(&BigUint::one(), 1.0); + check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0); + check(&BigUint::from(1u64 << 32), 2.0.powi(32)); + check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); + check(&((BigUint::one() << 100) + (BigUint::one() << 152)), + 2.0.powi(100) + 2.0.powi(152)); + check(&(BigUint::one() << 1023), 2.0.powi(1023)); + check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); + + // keeping all 53 digits with the bits at different offsets to the BigDigits + let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let mut f = x as f64; + let mut b = BigUint::from(x); + for _ in 0..128 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 54) - 1) as f64; + let mut b = BigUint::from(1u64 << 54); + for _ in 0..128 { + assert_eq!(b.to_f64(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigUint::from_f64(-1.0), None); + assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE / 2.0), + Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero())); + assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32))); + assert_eq!(BigUint::from_f64(f64::consts::PI), + Some(BigUint::from(3u32))); + + // special float values + assert_eq!(BigUint::from_f64(f64::NAN), None); + assert_eq!(BigUint::from_f64(f64::INFINITY), None); + assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None); + assert_eq!(BigUint::from_f64(f64::MIN), None); + + // largest BigUint that will round to a finite f64 value + let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54)); + assert_eq!(big_num.to_f64(), Some(f64::MAX)); + assert_eq!((big_num + BigUint::one()).to_f64(), None); + + assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); + assert_eq!((BigUint::one() << 1024).to_f64(), None); + } + + #[test] + fn test_convert_to_bigint() { + fn check(n: BigUint, ans: BigInt) { + assert_eq!(n.to_bigint().unwrap(), ans); + assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n); + } + check(Zero::zero(), Zero::zero()); + check(BigUint::new(vec![1, 2, 3]), + BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3]))); + } + + #[test] + fn test_convert_from_uint() { + macro_rules! check { + ($ty:ident, $max:expr) => { + assert_eq!(BigUint::from($ty::zero()), BigUint::zero()); + assert_eq!(BigUint::from($ty::one()), BigUint::one()); + assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one()); + assert_eq!(BigUint::from($ty::MAX), $max); + } + } + + check!(u8, BigUint::from_slice(&[u8::MAX as BigDigit])); + check!(u16, BigUint::from_slice(&[u16::MAX as BigDigit])); + check!(u32, BigUint::from_slice(&[u32::MAX])); + check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX])); + check!(usize, BigUint::from(usize::MAX as u64)); + } + + const SUM_TRIPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[], &[], &[]), + (&[], &[1], &[1]), + (&[1], &[1], &[2]), + (&[1], &[1, 1], &[2, 1]), + (&[1], &[N1], &[0, 1]), + (&[1], &[N1, N1], &[0, 0, 1]), + (&[N1, N1], &[N1, N1], &[N2, N1, 1]), + (&[1, 1, 1], &[N1, N1], &[0, 1, 2]), + (&[2, 2, 1], &[N1, N2], &[1, 1, 2])]; + + #[test] + fn test_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a + b == c); + assert_op!(b + a == c); + } + } + + #[test] + fn test_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(c - a == b); + assert_op!(c - b == a); + } + } + + #[test] + #[should_panic] + fn test_sub_fail_on_underflow() { + let (a, b): (BigUint, BigUint) = (Zero::zero(), One::one()); + a - b; + } + + const M: u32 = ::std::u32::MAX; + const MUL_TRIPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[], &[], &[]), + (&[], &[1], &[]), + (&[2], &[], &[]), + (&[1], &[1], &[1]), + (&[2], &[3], &[6]), + (&[1], &[1, 1, 1], &[1, 1, 1]), + (&[1, 2, 3], &[3], &[3, 6, 9]), + (&[1, 1, 1], &[N1], &[N1, N1, N1]), + (&[1, 2, 3], &[N1], &[N1, N2, N2, 2]), + (&[1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), + (&[N1], &[N1], &[1, N2]), + (&[N1, N1], &[N1], &[1, N1, N2]), + (&[N1, N1, N1], &[N1], &[1, N1, N1, N2]), + (&[N1, N1, N1, N1], &[N1], &[1, N1, N1, N1, N2]), + (&[M / 2 + 1], &[2], &[0, 1]), + (&[0, M / 2 + 1], &[2], &[0, 0, 1]), + (&[1, 2], &[1, 2, 3], &[1, 4, 7, 6]), + (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), + (&[N1, N1, N1], + &[N1, N1, N1, N1], + &[1, 0, 0, N1, N2, N1, N1]), + (&[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 2, 3]), + (&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])]; + + const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[1], &[2], &[], &[1]), + (&[1, 1], &[2], &[M / 2 + 1], &[1]), + (&[1, 1, 1], &[2], &[M / 2 + 1, M / 2 + 1], &[1]), + (&[0, 1], &[N1], &[1], &[1]), + (&[N1, N1], &[N2], &[2, 1], &[3])]; + + #[test] + fn test_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert_op!(a * b == c); + assert_op!(b * a == c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + assert!(a == &b * &c + &d); + assert!(a == &c * &b + &d); + } + } + + #[test] + fn test_div_rem() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + if !a.is_zero() { + assert_op!(c / a == b); + assert_op!(c % a == Zero::zero()); + assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); + } + if !b.is_zero() { + assert_op!(c / b == a); + assert_op!(c % b == Zero::zero()); + assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + if !b.is_zero() { + assert_op!(a / b == c); + assert_op!(a % b == d); + assert!(a.div_rem(&b) == (c, d)); + } + } + } + + #[test] + fn test_checked_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(a.checked_add(&b).unwrap() == c); + assert!(b.checked_add(&a).unwrap() == c); + } + } + + #[test] + fn test_checked_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(c.checked_sub(&a).unwrap() == b); + assert!(c.checked_sub(&b).unwrap() == a); + + if a > c { + assert!(a.checked_sub(&c).is_none()); + } + if b > c { + assert!(b.checked_sub(&c).is_none()); + } + } + } + + #[test] + fn test_checked_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + assert!(a.checked_mul(&b).unwrap() == c); + assert!(b.checked_mul(&a).unwrap() == c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + let d = BigUint::from_slice(d_vec); + + assert!(a == b.checked_mul(&c).unwrap() + &d); + assert!(a == c.checked_mul(&b).unwrap() + &d); + } + } + + #[test] + fn test_checked_div() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigUint::from_slice(a_vec); + let b = BigUint::from_slice(b_vec); + let c = BigUint::from_slice(c_vec); + + if !a.is_zero() { + assert!(c.checked_div(&a).unwrap() == b); + } + if !b.is_zero() { + assert!(c.checked_div(&b).unwrap() == a); + } + + assert!(c.checked_div(&Zero::zero()).is_none()); + } + } + + #[test] + fn test_gcd() { + fn check(a: usize, b: usize, c: usize) { + let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); + let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); + let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); + + assert_eq!(big_a.gcd(&big_b), big_c); + } + + check(10, 2, 2); + check(10, 3, 1); + check(0, 3, 3); + check(3, 3, 3); + check(56, 42, 14); + } + + #[test] + fn test_lcm() { + fn check(a: usize, b: usize, c: usize) { + let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); + let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); + let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); + + assert_eq!(big_a.lcm(&big_b), big_c); + } + + check(1, 0, 0); + check(0, 1, 0); + check(1, 1, 1); + check(8, 9, 72); + check(11, 5, 55); + check(99, 17, 1683); + } + + #[test] + fn test_is_even() { + let one: BigUint = FromStr::from_str("1").unwrap(); + let two: BigUint = FromStr::from_str("2").unwrap(); + let thousand: BigUint = FromStr::from_str("1000").unwrap(); + let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap(); + let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap(); + assert!(one.is_odd()); + assert!(two.is_even()); + assert!(thousand.is_even()); + assert!(big.is_even()); + assert!(bigger.is_odd()); + assert!((&one << 64).is_even()); + assert!(((&one << 64) + one).is_odd()); + } + + fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { + let bits = big_digit::BITS; + vec![(Zero::zero(), + vec![(2, "0".to_string()), (3, "0".to_string())]), + (BigUint::from_slice(&[0xff]), + vec![(2, "11111111".to_string()), + (3, "100110".to_string()), + (4, "3333".to_string()), + (5, "2010".to_string()), + (6, "1103".to_string()), + (7, "513".to_string()), + (8, "377".to_string()), + (9, "313".to_string()), + (10, "255".to_string()), + (11, "212".to_string()), + (12, "193".to_string()), + (13, "168".to_string()), + (14, "143".to_string()), + (15, "120".to_string()), + (16, "ff".to_string())]), + (BigUint::from_slice(&[0xfff]), + vec![(2, "111111111111".to_string()), + (4, "333333".to_string()), + (16, "fff".to_string())]), + (BigUint::from_slice(&[1, 2]), + vec![(2, + format!("10{}1", repeat("0").take(bits - 1).collect::())), + (4, + format!("2{}1", repeat("0").take(bits / 2 - 1).collect::())), + (10, + match bits { + 32 => "8589934593".to_string(), + 16 => "131073".to_string(), + _ => panic!(), + }), + (16, + format!("2{}1", repeat("0").take(bits / 4 - 1).collect::()))]), + (BigUint::from_slice(&[1, 2, 3]), + vec![(2, + format!("11{}10{}1", + repeat("0").take(bits - 2).collect::(), + repeat("0").take(bits - 1).collect::())), + (4, + format!("3{}2{}1", + repeat("0").take(bits / 2 - 1).collect::(), + repeat("0").take(bits / 2 - 1).collect::())), + (8, + match bits { + 32 => "6000000000100000000001".to_string(), + 16 => "140000400001".to_string(), + _ => panic!(), + }), + (10, + match bits { + 32 => "55340232229718589441".to_string(), + 16 => "12885032961".to_string(), + _ => panic!(), + }), + (16, + format!("3{}2{}1", + repeat("0").take(bits / 4 - 1).collect::(), + repeat("0").take(bits / 4 - 1).collect::()))])] + } + + #[test] + fn test_to_str_radix() { + let r = to_str_pairs(); + for num_pair in r.iter() { + let &(ref n, ref rs) = num_pair; + for str_pair in rs.iter() { + let &(ref radix, ref str) = str_pair; + assert_eq!(n.to_str_radix(*radix), *str); + } + } + } + + #[test] + fn test_from_str_radix() { + let r = to_str_pairs(); + for num_pair in r.iter() { + let &(ref n, ref rs) = num_pair; + for str_pair in rs.iter() { + let &(ref radix, ref str) = str_pair; + assert_eq!(n, &BigUint::from_str_radix(str, *radix).unwrap()); + } + } + + let zed = BigUint::from_str_radix("Z", 10).ok(); + assert_eq!(zed, None); + let blank = BigUint::from_str_radix("_", 2).ok(); + assert_eq!(blank, None); + let plus_one = BigUint::from_str_radix("+1", 10).ok(); + assert_eq!(plus_one, Some(BigUint::from_slice(&[1]))); + let plus_plus_one = BigUint::from_str_radix("++1", 10).ok(); + assert_eq!(plus_plus_one, None); + let minus_one = BigUint::from_str_radix("-1", 10).ok(); + assert_eq!(minus_one, None); + } + + #[test] + fn test_all_str_radix() { + use std::ascii::AsciiExt; + + let n = BigUint::new((0..10).collect()); + for radix in 2..37 { + let s = n.to_str_radix(radix); + let x = BigUint::from_str_radix(&s, radix); + assert_eq!(x.unwrap(), n); + + let s = s.to_ascii_uppercase(); + let x = BigUint::from_str_radix(&s, radix); + assert_eq!(x.unwrap(), n); + } + } + + #[test] + fn test_lower_hex() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:x}", a), "a"); + assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421"); + assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); + } + + #[test] + fn test_upper_hex() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:X}", a), "A"); + assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421"); + assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); + } + + #[test] + fn test_binary() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("224055342307539".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:b}", a), "1010"); + assert_eq!(format!("{:b}", hello), + "110010111100011011110011000101101001100011010011"); + assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); + } + + #[test] + fn test_octal() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:o}", a), "12"); + assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041"); + assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); + } + + #[test] + fn test_display() { + let a = BigUint::parse_bytes(b"A", 16).unwrap(); + let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{}", a), "10"); + assert_eq!(format!("{}", hello), "22405534230753963835153736737"); + assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); + } + + #[test] + fn test_factor() { + fn factor(n: usize) -> BigUint { + let mut f: BigUint = One::one(); + for i in 2..n + 1 { + // FIXME(#5992): assignment operator overloads + // f *= FromPrimitive::from_usize(i); + let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); + f = f * bu; + } + return f; + } + + fn check(n: usize, s: &str) { + let n = factor(n); + let ans = match BigUint::from_str_radix(s, 10) { + Ok(x) => x, + Err(_) => panic!(), + }; + assert_eq!(n, ans); + } + + check(3, "6"); + check(10, "3628800"); + check(20, "2432902008176640000"); + check(30, "265252859812191058636308480000000"); + } + + #[test] + fn test_bits() { + assert_eq!(BigUint::new(vec![0, 0, 0, 0]).bits(), 0); + let n: BigUint = FromPrimitive::from_usize(0).unwrap(); + assert_eq!(n.bits(), 0); + let n: BigUint = FromPrimitive::from_usize(1).unwrap(); + assert_eq!(n.bits(), 1); + let n: BigUint = FromPrimitive::from_usize(3).unwrap(); + assert_eq!(n.bits(), 2); + let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap(); + assert_eq!(n.bits(), 39); + let one: BigUint = One::one(); + assert_eq!((one << 426).bits(), 427); + } + + #[test] + fn test_rand() { + let mut rng = thread_rng(); + let _n: BigUint = rng.gen_biguint(137); + assert!(rng.gen_biguint(0).is_zero()); + } + + #[test] + fn test_rand_range() { + let mut rng = thread_rng(); + + for _ in 0..10 { + assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(), + &FromPrimitive::from_usize(237).unwrap()), + FromPrimitive::from_usize(236).unwrap()); + } + + let l = FromPrimitive::from_usize(403469000 + 2352).unwrap(); + let u = FromPrimitive::from_usize(403469000 + 3513).unwrap(); + for _ in 0..1000 { + let n: BigUint = rng.gen_biguint_below(&u); + assert!(n < u); + + let n: BigUint = rng.gen_biguint_range(&l, &u); + assert!(n >= l); + assert!(n < u); + } + } + + #[test] + #[should_panic] + fn test_zero_rand_range() { + thread_rng().gen_biguint_range(&FromPrimitive::from_usize(54).unwrap(), + &FromPrimitive::from_usize(54).unwrap()); + } + + #[test] + #[should_panic] + fn test_negative_rand_range() { + let mut rng = thread_rng(); + let l = FromPrimitive::from_usize(2352).unwrap(); + let u = FromPrimitive::from_usize(3513).unwrap(); + // Switching u and l should fail: + let _n: BigUint = rng.gen_biguint_range(&u, &l); + } + + #[test] + fn test_sub_sign() { + use super::sub_sign; + let a = BigInt::from_str_radix("265252859812191058636308480000000", 10).unwrap(); + let b = BigInt::from_str_radix("26525285981219105863630848000000", 10).unwrap(); + + assert_eq!(sub_sign(&a.data.data[..], &b.data.data[..]), &a - &b); + assert_eq!(sub_sign(&b.data.data[..], &a.data.data[..]), &b - &a); + } + + fn test_mul_divide_torture_count(count: usize) { + use rand::{SeedableRng, StdRng, Rng}; + + let bits_max = 1 << 12; + let seed: &[_] = &[1, 2, 3, 4]; + let mut rng: StdRng = SeedableRng::from_seed(seed); + + for _ in 0..count { + // Test with numbers of random sizes: + let xbits = rng.gen_range(0, bits_max); + let ybits = rng.gen_range(0, bits_max); + + let x = rng.gen_biguint(xbits); + let y = rng.gen_biguint(ybits); + + if x.is_zero() || y.is_zero() { + continue; + } + + let prod = &x * &y; + assert_eq!(&prod / &x, y); + assert_eq!(&prod / &y, x); + } + } + + #[test] + fn test_mul_divide_torture() { + test_mul_divide_torture_count(1000); + } + + #[test] + #[ignore] + fn test_mul_divide_torture_long() { + test_mul_divide_torture_count(1000000); + } +} + +#[cfg(test)] +mod bigint_tests { + use Integer; + use super::{BigDigit, BigUint, ToBigUint}; + use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit}; + use super::Sign::{Minus, NoSign, Plus}; + + use std::cmp::Ordering::{Less, Equal, Greater}; + use std::{f32, f64}; + use std::{i8, i16, i32, i64, isize}; + use std::iter::repeat; + use std::{u8, u16, u32, u64, usize}; + use std::ops::Neg; + + use rand::thread_rng; + + use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num}; + use Float; + + /// Assert that an op works for all val/ref combinations + macro_rules! assert_op { + ($left:ident $op:tt $right:ident == $expected:expr) => { + assert_eq!((&$left) $op (&$right), $expected); + assert_eq!((&$left) $op $right.clone(), $expected); + assert_eq!($left.clone() $op (&$right), $expected); + assert_eq!($left.clone() $op $right.clone(), $expected); + }; + } + + #[test] + fn test_from_biguint() { + fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) { + let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap()); + let ans = BigInt { + sign: ans_s, + data: FromPrimitive::from_usize(ans_n).unwrap(), + }; + assert_eq!(inp, ans); + } + check(Plus, 1, Plus, 1); + check(Plus, 0, NoSign, 0); + check(Minus, 1, Minus, 1); + check(NoSign, 1, NoSign, 0); + } + + #[test] + fn test_from_bytes_be() { + fn check(s: &str, result: &str) { + assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap()); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero()); + assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero()); + } + + #[test] + fn test_to_bytes_be() { + fn check(s: &str, result: &str) { + let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); + let (sign, v) = b.to_bytes_be(); + assert_eq!((Plus, s.as_bytes()), (sign, &*v)); + } + check("A", "65"); + check("AA", "16705"); + check("AB", "16706"); + check("Hello world!", "22405534230753963835153736737"); + let b: BigInt = Zero::zero(); + assert_eq!(b.to_bytes_be(), (NoSign, vec![0])); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0])); + } + + #[test] + fn test_from_bytes_le() { + fn check(s: &str, result: &str) { + assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()), + BigInt::parse_bytes(result.as_bytes(), 10).unwrap()); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero()); + assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero()); + } + + #[test] + fn test_to_bytes_le() { + fn check(s: &str, result: &str) { + let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); + let (sign, v) = b.to_bytes_le(); + assert_eq!((Plus, s.as_bytes()), (sign, &*v)); + } + check("A", "65"); + check("AA", "16705"); + check("BA", "16706"); + check("!dlrow olleH", "22405534230753963835153736737"); + let b: BigInt = Zero::zero(); + assert_eq!(b.to_bytes_le(), (NoSign, vec![0])); + + // Test with leading/trailing zero bytes and a full BigDigit of value 0 + let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); + assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1])); + } + + #[test] + fn test_cmp() { + let vs: [&[BigDigit]; 4] = [&[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1]]; + let mut nums = Vec::new(); + for s in vs.iter().rev() { + nums.push(BigInt::from_slice(Minus, *s)); + } + nums.push(Zero::zero()); + nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); + + for (i, ni) in nums.iter().enumerate() { + for (j0, nj) in nums[i..].iter().enumerate() { + let j = i + j0; + if i == j { + assert_eq!(ni.cmp(nj), Equal); + assert_eq!(nj.cmp(ni), Equal); + assert_eq!(ni, nj); + assert!(!(ni != nj)); + assert!(ni <= nj); + assert!(ni >= nj); + assert!(!(ni < nj)); + assert!(!(ni > nj)); + } else { + assert_eq!(ni.cmp(nj), Less); + assert_eq!(nj.cmp(ni), Greater); + + assert!(!(ni == nj)); + assert!(ni != nj); + + assert!(ni <= nj); + assert!(!(ni >= nj)); + assert!(ni < nj); + assert!(!(ni > nj)); + + assert!(!(nj <= ni)); + assert!(nj >= ni); + assert!(!(nj < ni)); + assert!(nj > ni); + } + } + } + } + + + #[test] + fn test_hash() { + let a = BigInt::new(NoSign, vec![]); + let b = BigInt::new(NoSign, vec![0]); + let c = BigInt::new(Plus, vec![1]); + let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]); + let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]); + let f = BigInt::new(Minus, vec![1]); + assert!(::hash(&a) == ::hash(&b)); + assert!(::hash(&b) != ::hash(&c)); + assert!(::hash(&c) == ::hash(&d)); + assert!(::hash(&d) != ::hash(&e)); + assert!(::hash(&c) != ::hash(&f)); + } + + #[test] + fn test_convert_i64() { + fn check(b1: BigInt, i: i64) { + let b2: BigInt = FromPrimitive::from_i64(i).unwrap(); + assert!(b1 == b2); + assert!(b1.to_i64().unwrap() == i); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(i64::MIN.to_bigint().unwrap(), i64::MIN); + check(i64::MAX.to_bigint().unwrap(), i64::MAX); + + assert_eq!((i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), None); + + assert_eq!(BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), + None); + + assert_eq!(BigInt::from_biguint(Minus, + BigUint::new(vec![1, 0, 0, 1 << (big_digit::BITS - 1)])) + .to_i64(), + None); + + assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(), + None); + } + + #[test] + fn test_convert_u64() { + fn check(b1: BigInt, u: u64) { + let b2: BigInt = FromPrimitive::from_u64(u).unwrap(); + assert!(b1 == b2); + assert!(b1.to_u64().unwrap() == u); + } + + check(Zero::zero(), 0); + check(One::one(), 1); + check(u64::MIN.to_bigint().unwrap(), u64::MIN); + check(u64::MAX.to_bigint().unwrap(), u64::MAX); + + assert_eq!(BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), + None); + + let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap(); + assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None); + assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(), + None); + } + + #[test] + fn test_convert_f32() { + fn check(b1: &BigInt, f: f32) { + let b2 = BigInt::from_f32(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f32().unwrap(), f); + let neg_b1 = -b1; + let neg_b2 = BigInt::from_f32(-f).unwrap(); + assert_eq!(neg_b1, neg_b2); + assert_eq!(neg_b1.to_f32().unwrap(), -f); + } + + check(&BigInt::zero(), 0.0); + check(&BigInt::one(), 1.0); + check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0); + check(&BigInt::from(1u64 << 32), 2.0.powi(32)); + check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); + check(&((BigInt::one() << 100) + (BigInt::one() << 123)), + 2.0.powi(100) + 2.0.powi(123)); + check(&(BigInt::one() << 127), 2.0.powi(127)); + check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); + + // keeping all 24 digits with the bits at different offsets to the BigDigits + let x: u32 = 0b00000000101111011111011011011101; + let mut f = x as f32; + let mut b = BigInt::from(x); + for _ in 0..64 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 + let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); + n = -n; + assert!((n as f64) as f32 != n as f32); + assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 25) - 1) as f32; + let mut b = BigInt::from(1u64 << 25); + for _ in 0..64 { + assert_eq!(b.to_f32(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigInt::from_f32(-f32::consts::PI), + Some(BigInt::from(-3i32))); + assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32))); + assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE / 2.0), + Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32))); + assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32))); + + // special float values + assert_eq!(BigInt::from_f32(f32::NAN), None); + assert_eq!(BigInt::from_f32(f32::INFINITY), None); + assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None); + + // largest BigInt that will round to a finite f32 value + let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25)); + assert_eq!(big_num.to_f32(), Some(f32::MAX)); + assert_eq!((&big_num + BigInt::one()).to_f32(), None); + assert_eq!((-&big_num).to_f32(), Some(f32::MIN)); + assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None); + + assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None); + assert_eq!((BigInt::one() << 128).to_f32(), None); + assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None); + assert_eq!((-(BigInt::one() << 128)).to_f32(), None); + } + + #[test] + fn test_convert_f64() { + fn check(b1: &BigInt, f: f64) { + let b2 = BigInt::from_f64(f).unwrap(); + assert_eq!(b1, &b2); + assert_eq!(b1.to_f64().unwrap(), f); + let neg_b1 = -b1; + let neg_b2 = BigInt::from_f64(-f).unwrap(); + assert_eq!(neg_b1, neg_b2); + assert_eq!(neg_b1.to_f64().unwrap(), -f); + } + + check(&BigInt::zero(), 0.0); + check(&BigInt::one(), 1.0); + check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0); + check(&BigInt::from(1u64 << 32), 2.0.powi(32)); + check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); + check(&((BigInt::one() << 100) + (BigInt::one() << 152)), + 2.0.powi(100) + 2.0.powi(152)); + check(&(BigInt::one() << 1023), 2.0.powi(1023)); + check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); + + // keeping all 53 digits with the bits at different offsets to the BigDigits + let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let mut f = x as f64; + let mut b = BigInt::from(x); + for _ in 0..128 { + check(&b, f); + f *= 2.0; + b = b << 1; + } + + // test rounding up with the bits at different offsets to the BigDigits + let mut f = ((1u64 << 54) - 1) as f64; + let mut b = BigInt::from(1u64 << 54); + for _ in 0..128 { + assert_eq!(b.to_f64(), Some(f)); + f *= 2.0; + b = b << 1; + } + + // rounding + assert_eq!(BigInt::from_f64(-f64::consts::PI), + Some(BigInt::from(-3i32))); + assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32))); + assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE / 2.0), + Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero())); + assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32))); + assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32))); + + // special float values + assert_eq!(BigInt::from_f64(f64::NAN), None); + assert_eq!(BigInt::from_f64(f64::INFINITY), None); + assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None); + + // largest BigInt that will round to a finite f64 value + let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54)); + assert_eq!(big_num.to_f64(), Some(f64::MAX)); + assert_eq!((&big_num + BigInt::one()).to_f64(), None); + assert_eq!((-&big_num).to_f64(), Some(f64::MIN)); + assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None); + + assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); + assert_eq!((BigInt::one() << 1024).to_f64(), None); + assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None); + assert_eq!((-(BigInt::one() << 1024)).to_f64(), None); + } + + #[test] + fn test_convert_to_biguint() { + fn check(n: BigInt, ans_1: BigUint) { + assert_eq!(n.to_biguint().unwrap(), ans_1); + assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n); + } + let zero: BigInt = Zero::zero(); + let unsigned_zero: BigUint = Zero::zero(); + let positive = BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3])); + let negative = -&positive; + + check(zero, unsigned_zero); + check(positive, BigUint::new(vec![1, 2, 3])); + + assert_eq!(negative.to_biguint(), None); + } + + #[test] + fn test_convert_from_uint() { + macro_rules! check { + ($ty:ident, $max:expr) => { + assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); + assert_eq!(BigInt::from($ty::one()), BigInt::one()); + assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); + assert_eq!(BigInt::from($ty::MAX), $max); + } + } + + check!(u8, BigInt::from_slice(Plus, &[u8::MAX as BigDigit])); + check!(u16, BigInt::from_slice(Plus, &[u16::MAX as BigDigit])); + check!(u32, BigInt::from_slice(Plus, &[u32::MAX as BigDigit])); + check!(u64, + BigInt::from_slice(Plus, &[u32::MAX as BigDigit, u32::MAX as BigDigit])); + check!(usize, BigInt::from(usize::MAX as u64)); + } + + #[test] + fn test_convert_from_int() { + macro_rules! check { + ($ty:ident, $min:expr, $max:expr) => { + assert_eq!(BigInt::from($ty::MIN), $min); + assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one()); + assert_eq!(BigInt::from(-$ty::one()), -BigInt::one()); + assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); + assert_eq!(BigInt::from($ty::one()), BigInt::one()); + assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); + assert_eq!(BigInt::from($ty::MAX), $max); + } + } + + check!(i8, + BigInt::from_slice(Minus, &[1 << 7]), + BigInt::from_slice(Plus, &[i8::MAX as BigDigit])); + check!(i16, + BigInt::from_slice(Minus, &[1 << 15]), + BigInt::from_slice(Plus, &[i16::MAX as BigDigit])); + check!(i32, + BigInt::from_slice(Minus, &[1 << 31]), + BigInt::from_slice(Plus, &[i32::MAX as BigDigit])); + check!(i64, + BigInt::from_slice(Minus, &[0, 1 << 31]), + BigInt::from_slice(Plus, &[u32::MAX as BigDigit, i32::MAX as BigDigit])); + check!(isize, + BigInt::from(isize::MIN as i64), + BigInt::from(isize::MAX as i64)); + } + + #[test] + fn test_convert_from_biguint() { + assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero()); + assert_eq!(BigInt::from(BigUint::one()), BigInt::one()); + assert_eq!(BigInt::from(BigUint::from_slice(&[1, 2, 3])), + BigInt::from_slice(Plus, &[1, 2, 3])); + } + + const N1: BigDigit = -1i32 as BigDigit; + const N2: BigDigit = -2i32 as BigDigit; + + const SUM_TRIPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[], &[], &[]), + (&[], &[1], &[1]), + (&[1], &[1], &[2]), + (&[1], &[1, 1], &[2, 1]), + (&[1], &[N1], &[0, 1]), + (&[1], &[N1, N1], &[0, 0, 1]), + (&[N1, N1], &[N1, N1], &[N2, N1, 1]), + (&[1, 1, 1], &[N1, N1], &[0, 1, 2]), + (&[2, 2, 1], &[N1, N2], &[1, 1, 2])]; + + #[test] + fn test_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(a + b == c); + assert_op!(b + a == c); + assert_op!(c + na == b); + assert_op!(c + nb == a); + assert_op!(a + nc == nb); + assert_op!(b + nc == na); + assert_op!(na + nb == nc); + assert_op!(a + na == Zero::zero()); + } + } + + #[test] + fn test_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(c - a == b); + assert_op!(c - b == a); + assert_op!(nb - a == nc); + assert_op!(na - b == nc); + assert_op!(b - na == c); + assert_op!(a - nb == c); + assert_op!(nc - na == nb); + assert_op!(a - a == Zero::zero()); + } + } + + const M: u32 = ::std::u32::MAX; + static MUL_TRIPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[], &[], &[]), + (&[], &[1], &[]), + (&[2], &[], &[]), + (&[1], &[1], &[1]), + (&[2], &[3], &[6]), + (&[1], &[1, 1, 1], &[1, 1, 1]), + (&[1, 2, 3], &[3], &[3, 6, 9]), + (&[1, 1, 1], &[N1], &[N1, N1, N1]), + (&[1, 2, 3], &[N1], &[N1, N2, N2, 2]), + (&[1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), + (&[N1], &[N1], &[1, N2]), + (&[N1, N1], &[N1], &[1, N1, N2]), + (&[N1, N1, N1], &[N1], &[1, N1, N1, N2]), + (&[N1, N1, N1, N1], &[N1], &[1, N1, N1, N1, N2]), + (&[M / 2 + 1], &[2], &[0, 1]), + (&[0, M / 2 + 1], &[2], &[0, 0, 1]), + (&[1, 2], &[1, 2, 3], &[1, 4, 7, 6]), + (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), + (&[N1, N1, N1], + &[N1, N1, N1, N1], + &[1, 0, 0, N1, N2, N1, N1]), + (&[0, 0, 1], &[1, 2, 3], &[0, 0, 1, 2, 3]), + (&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])]; + + static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit], + &'static [BigDigit])] = &[(&[1], &[2], &[], &[1]), + (&[1, 1], &[2], &[M / 2 + 1], &[1]), + (&[1, 1, 1], &[2], &[M / 2 + 1, M / 2 + 1], &[1]), + (&[0, 1], &[N1], &[1], &[1]), + (&[N1, N1], &[N2], &[2, 1], &[3])]; + + #[test] + fn test_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let (na, nb, nc) = (-&a, -&b, -&c); + + assert_op!(a * b == c); + assert_op!(b * a == c); + assert_op!(na * nb == c); + + assert_op!(na * b == nc); + assert_op!(nb * a == nc); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + assert!(a == &b * &c + &d); + assert!(a == &c * &b + &d); + } + } + + #[test] + fn test_div_mod_floor() { + fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { + let (d, m) = a.div_mod_floor(b); + if !m.is_zero() { + assert_eq!(m.sign, b.sign); + } + assert!(m.abs() <= b.abs()); + assert!(*a == b * &d + &m); + assert!(d == *ans_d); + assert!(m == *ans_m); + } + + fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) { + if m.is_zero() { + check_sub(a, b, d, m); + check_sub(a, &b.neg(), &d.neg(), m); + check_sub(&a.neg(), b, &d.neg(), m); + check_sub(&a.neg(), &b.neg(), d, m); + } else { + let one: BigInt = One::one(); + check_sub(a, b, d, m); + check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b)); + check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m)); + check_sub(&a.neg(), &b.neg(), d, &m.neg()); + } + } + + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + check(&c, &a, &b, &Zero::zero()); + } + if !b.is_zero() { + check(&c, &b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + if !b.is_zero() { + check(&a, &b, &c, &d); + } + } + } + + + #[test] + fn test_div_rem() { + fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { + let (q, r) = a.div_rem(b); + if !r.is_zero() { + assert_eq!(r.sign, a.sign); + } + assert!(r.abs() <= b.abs()); + assert!(*a == b * &q + &r); + assert!(q == *ans_q); + assert!(r == *ans_r); + + let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); + assert_op!(a / b == ans_q); + assert_op!(a % b == ans_r); + } + + fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) { + check_sub(a, b, q, r); + check_sub(a, &b.neg(), &q.neg(), r); + check_sub(&a.neg(), b, &q.neg(), &r.neg()); + check_sub(&a.neg(), &b.neg(), q, &r.neg()); + } + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + check(&c, &a, &b, &Zero::zero()); + } + if !b.is_zero() { + check(&c, &b, &a, &Zero::zero()); + } + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + if !b.is_zero() { + check(&a, &b, &c, &d); + } + } + } + + #[test] + fn test_checked_add() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(a.checked_add(&b).unwrap() == c); + assert!(b.checked_add(&a).unwrap() == c); + assert!(c.checked_add(&(-&a)).unwrap() == b); + assert!(c.checked_add(&(-&b)).unwrap() == a); + assert!(a.checked_add(&(-&c)).unwrap() == (-&b)); + assert!(b.checked_add(&(-&c)).unwrap() == (-&a)); + assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c)); + assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero()); + } + } + + #[test] + fn test_checked_sub() { + for elm in SUM_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(c.checked_sub(&a).unwrap() == b); + assert!(c.checked_sub(&b).unwrap() == a); + assert!((-&b).checked_sub(&a).unwrap() == (-&c)); + assert!((-&a).checked_sub(&b).unwrap() == (-&c)); + assert!(b.checked_sub(&(-&a)).unwrap() == c); + assert!(a.checked_sub(&(-&b)).unwrap() == c); + assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b)); + assert!(a.checked_sub(&a).unwrap() == Zero::zero()); + } + } + + #[test] + fn test_checked_mul() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + assert!(a.checked_mul(&b).unwrap() == c); + assert!(b.checked_mul(&a).unwrap() == c); + + assert!((-&a).checked_mul(&b).unwrap() == -&c); + assert!((-&b).checked_mul(&a).unwrap() == -&c); + } + + for elm in DIV_REM_QUADRUPLES.iter() { + let (a_vec, b_vec, c_vec, d_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + let d = BigInt::from_slice(Plus, d_vec); + + assert!(a == b.checked_mul(&c).unwrap() + &d); + assert!(a == c.checked_mul(&b).unwrap() + &d); + } + } + #[test] + fn test_checked_div() { + for elm in MUL_TRIPLES.iter() { + let (a_vec, b_vec, c_vec) = *elm; + let a = BigInt::from_slice(Plus, a_vec); + let b = BigInt::from_slice(Plus, b_vec); + let c = BigInt::from_slice(Plus, c_vec); + + if !a.is_zero() { + assert!(c.checked_div(&a).unwrap() == b); + assert!((-&c).checked_div(&(-&a)).unwrap() == b); + assert!((-&c).checked_div(&a).unwrap() == -&b); + } + if !b.is_zero() { + assert!(c.checked_div(&b).unwrap() == a); + assert!((-&c).checked_div(&(-&b)).unwrap() == a); + assert!((-&c).checked_div(&b).unwrap() == -&a); + } + + assert!(c.checked_div(&Zero::zero()).is_none()); + assert!((-&c).checked_div(&Zero::zero()).is_none()); + } + } + + #[test] + fn test_gcd() { + fn check(a: isize, b: isize, c: isize) { + let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); + let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); + let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); + + assert_eq!(big_a.gcd(&big_b), big_c); + } + + check(10, 2, 2); + check(10, 3, 1); + check(0, 3, 3); + check(3, 3, 3); + check(56, 42, 14); + check(3, -3, 3); + check(-6, 3, 3); + check(-4, -2, 2); + } + + #[test] + fn test_lcm() { + fn check(a: isize, b: isize, c: isize) { + let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); + let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); + let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); + + assert_eq!(big_a.lcm(&big_b), big_c); + } + + check(1, 0, 0); + check(0, 1, 0); + check(1, 1, 1); + check(-1, 1, 1); + check(1, -1, 1); + check(-1, -1, 1); + check(8, 9, 72); + check(11, 5, 55); + } + + #[test] + fn test_abs_sub() { + let zero: BigInt = Zero::zero(); + let one: BigInt = One::one(); + assert_eq!((-&one).abs_sub(&one), zero); + let one: BigInt = One::one(); + let zero: BigInt = Zero::zero(); + assert_eq!(one.abs_sub(&one), zero); + let one: BigInt = One::one(); + let zero: BigInt = Zero::zero(); + assert_eq!(one.abs_sub(&zero), one); + let one: BigInt = One::one(); + let two: BigInt = FromPrimitive::from_isize(2).unwrap(); + assert_eq!(one.abs_sub(&-&one), two); + } + + #[test] + fn test_from_str_radix() { + fn check(s: &str, ans: Option) { + let ans = ans.map(|n| { + let x: BigInt = FromPrimitive::from_isize(n).unwrap(); + x + }); + assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans); + } + check("10", Some(10)); + check("1", Some(1)); + check("0", Some(0)); + check("-1", Some(-1)); + check("-10", Some(-10)); + check("+10", Some(10)); + check("--7", None); + check("++5", None); + check("+-9", None); + check("-+3", None); + check("Z", None); + check("_", None); + + // issue 10522, this hit an edge case that caused it to + // attempt to allocate a vector of size (-1u) == huge. + let x: BigInt = format!("1{}", repeat("0").take(36).collect::()).parse().unwrap(); + let _y = x.to_string(); + } + + #[test] + fn test_lower_hex() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:x}", a), "a"); + assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421"); + assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); + } + + #[test] + fn test_upper_hex() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:X}", a), "A"); + assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421"); + assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); + } + + #[test] + fn test_binary() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:b}", a), "1010"); + assert_eq!(format!("{:b}", hello), + "-110010111100011011110011000101101001100011010011"); + assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); + } + + #[test] + fn test_octal() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{:o}", a), "12"); + assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041"); + assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); + } + + #[test] + fn test_display() { + let a = BigInt::parse_bytes(b"A", 16).unwrap(); + let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); + + assert_eq!(format!("{}", a), "10"); + assert_eq!(format!("{}", hello), "-22405534230753963835153736737"); + assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); + } + + #[test] + fn test_neg() { + assert!(-BigInt::new(Plus, vec![1, 1, 1]) == BigInt::new(Minus, vec![1, 1, 1])); + assert!(-BigInt::new(Minus, vec![1, 1, 1]) == BigInt::new(Plus, vec![1, 1, 1])); + let zero: BigInt = Zero::zero(); + assert_eq!(-&zero, zero); + } + + #[test] + fn test_rand() { + let mut rng = thread_rng(); + let _n: BigInt = rng.gen_bigint(137); + assert!(rng.gen_bigint(0).is_zero()); + } + + #[test] + fn test_rand_range() { + let mut rng = thread_rng(); + + for _ in 0..10 { + assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(), + &FromPrimitive::from_usize(237).unwrap()), + FromPrimitive::from_usize(236).unwrap()); + } + + fn check(l: BigInt, u: BigInt) { + let mut rng = thread_rng(); + for _ in 0..1000 { + let n: BigInt = rng.gen_bigint_range(&l, &u); + assert!(n >= l); + assert!(n < u); + } + } + let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap(); + let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap(); + check(l.clone(), u.clone()); + check(-l.clone(), u.clone()); + check(-u.clone(), -l.clone()); + } + + #[test] + #[should_panic] + fn test_zero_rand_range() { + thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(), + &FromPrimitive::from_isize(54).unwrap()); + } + + #[test] + #[should_panic] + fn test_negative_rand_range() { + let mut rng = thread_rng(); + let l = FromPrimitive::from_usize(2352).unwrap(); + let u = FromPrimitive::from_usize(3513).unwrap(); + // Switching u and l should fail: + let _n: BigInt = rng.gen_bigint_range(&u, &l); + } +} diff --git a/integer/src/lib.rs b/integer/src/lib.rs index 94d5f82..6059133 100644 --- a/integer/src/lib.rs +++ b/integer/src/lib.rs @@ -14,11 +14,7 @@ extern crate num_traits as traits; use traits::{Num, Signed}; -pub trait Integer - : Sized - + Num - + PartialOrd + Ord + Eq -{ +pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// Floored integer division. /// /// # Examples @@ -162,19 +158,37 @@ pub trait Integer } /// Simultaneous integer division and modulus -#[inline] pub fn div_rem(x: T, y: T) -> (T, T) { x.div_rem(&y) } +#[inline] +pub fn div_rem(x: T, y: T) -> (T, T) { + x.div_rem(&y) +} /// Floored integer division -#[inline] pub fn div_floor(x: T, y: T) -> T { x.div_floor(&y) } +#[inline] +pub fn div_floor(x: T, y: T) -> T { + x.div_floor(&y) +} /// Floored integer modulus -#[inline] pub fn mod_floor(x: T, y: T) -> T { x.mod_floor(&y) } +#[inline] +pub fn mod_floor(x: T, y: T) -> T { + x.mod_floor(&y) +} /// Simultaneous floored integer division and modulus -#[inline] pub fn div_mod_floor(x: T, y: T) -> (T, T) { x.div_mod_floor(&y) } +#[inline] +pub fn div_mod_floor(x: T, y: T) -> (T, T) { + x.div_mod_floor(&y) +} /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. The /// result is always positive. -#[inline(always)] pub fn gcd(x: T, y: T) -> T { x.gcd(&y) } +#[inline(always)] +pub fn gcd(x: T, y: T) -> T { + x.gcd(&y) +} /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. -#[inline(always)] pub fn lcm(x: T, y: T) -> T { x.lcm(&y) } +#[inline(always)] +pub fn lcm(x: T, y: T) -> T { + x.lcm(&y) +} macro_rules! impl_integer_for_isize { ($T:ty, $test_mod:ident) => ( @@ -470,11 +484,11 @@ macro_rules! impl_integer_for_isize { ) } -impl_integer_for_isize!(i8, test_integer_i8); -impl_integer_for_isize!(i16, test_integer_i16); -impl_integer_for_isize!(i32, test_integer_i32); -impl_integer_for_isize!(i64, test_integer_i64); -impl_integer_for_isize!(isize, test_integer_isize); +impl_integer_for_isize!(i8, test_integer_i8); +impl_integer_for_isize!(i16, test_integer_i16); +impl_integer_for_isize!(i32, test_integer_i32); +impl_integer_for_isize!(i64, test_integer_i64); +impl_integer_for_isize!(isize, test_integer_isize); macro_rules! impl_integer_for_usize { ($T:ty, $test_mod:ident) => ( @@ -641,8 +655,8 @@ macro_rules! impl_integer_for_usize { ) } -impl_integer_for_usize!(u8, test_integer_u8); -impl_integer_for_usize!(u16, test_integer_u16); -impl_integer_for_usize!(u32, test_integer_u32); -impl_integer_for_usize!(u64, test_integer_u64); +impl_integer_for_usize!(u8, test_integer_u8); +impl_integer_for_usize!(u16, test_integer_u16); +impl_integer_for_usize!(u32, test_integer_u32); +impl_integer_for_usize!(u64, test_integer_u64); impl_integer_for_usize!(usize, test_integer_usize); diff --git a/src/lib.rs b/src/lib.rs index 46e0adb..a44bb9b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,7 @@ extern crate num_traits; extern crate num_integer; +extern crate num_bigint; #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; @@ -91,7 +92,7 @@ pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded, use std::ops::{Mul}; #[cfg(feature = "bigint")] -pub mod bigint; +pub mod bigint { pub use num_bigint::*; } pub mod complex; pub mod integer { pub use num_integer::*; } pub mod iter; diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 9665094..c0dce24 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -34,16 +34,16 @@ pub trait Num: PartialEq + Zero + One + Add + Sub + Mul + Div + Rem { - type Error; + type FromStrRadixErr; /// Convert from a string and radix <= 36. - fn from_str_radix(str: &str, radix: u32) -> Result; + fn from_str_radix(str: &str, radix: u32) -> Result; } macro_rules! int_trait_impl { ($name:ident for $($t:ty)*) => ($( impl $name for $t { - type Error = ::std::num::ParseIntError; + type FromStrRadixErr = ::std::num::ParseIntError; fn from_str_radix(s: &str, radix: u32) -> Result { @@ -65,10 +65,10 @@ pub struct ParseFloatError { macro_rules! float_trait_impl { ($name:ident for $($t:ty)*) => ($( impl $name for $t { - type Error = ParseFloatError; + type FromStrRadixErr = ParseFloatError; fn from_str_radix(src: &str, radix: u32) - -> Result + -> Result { use self::FloatErrorKind::*; use self::ParseFloatError as PFE; From 54685c46a1973e86f70d8eccc9dc0ebb3a251c17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 4 Mar 2016 12:32:44 +0100 Subject: [PATCH 05/31] Extract rational --- .travis.yml | 7 +- .travis/test_features.sh | 2 - Cargo.toml | 10 +- Makefile | 14 + bigint/Cargo.toml | 5 +- bigint/src/lib.rs | 74 +-- integer/src/lib.rs | 20 +- rational/Cargo.toml | 24 + rational/src/lib.rs | 1091 ++++++++++++++++++++++++++++++++++++++ src/lib.rs | 29 +- traits/src/cast.rs | 3 +- traits/src/float.rs | 108 ++-- traits/src/int.rs | 32 +- 13 files changed, 1277 insertions(+), 142 deletions(-) create mode 100644 Makefile create mode 100644 rational/Cargo.toml create mode 100644 rational/src/lib.rs diff --git a/.travis.yml b/.travis.yml index fa2027b..beadc77 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,12 +5,9 @@ rust: - nightly sudo: false script: - - cargo build --verbose - - cargo test --verbose - - .travis/test_features.sh + - make test - | - [ $TRAVIS_RUST_VERSION != nightly ] || - .travis/test_nightly.sh + [ $TRAVIS_RUST_VERSION != nightly ] || .travis/test_nightly.sh - cargo doc after_success: | [ $TRAVIS_BRANCH = master ] && diff --git a/.travis/test_features.sh b/.travis/test_features.sh index 150ac41..5ff01c0 100755 --- a/.travis/test_features.sh +++ b/.travis/test_features.sh @@ -3,7 +3,5 @@ set -ex for feature in '' bigint rational complex; do - cargo build --verbose --no-default-features --features="$feature" cargo test --verbose --no-default-features --features="$feature" done - diff --git a/Cargo.toml b/Cargo.toml index 378484a..d833beb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,12 +19,16 @@ name = "shootout-pidigits" [dependencies] [dependencies.num-bigint] -optional = false +optional = true path = "bigint" [dependencies.num-integer] path = "./integer" +[dependencies.num-rational] +optional = true +path = "rational" + [dependencies.num-traits] path = "./traits" @@ -46,7 +50,7 @@ version = "^0.7.0" version = "0.3.8" [features] -bigint = [] +bigint = ["num-bigint"] complex = [] default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] -rational = [] +rational = ["num-rational"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..74a3a93 --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +CARGO_CMD ?= cargo + +packages = bigint integer rational traits + +test: + $(MAKE) run-all TASK="test --no-fail-fast" + +run-all: $(packages) + $(CARGO_CMD) $(TASK) + +$(packages): + $(CARGO_CMD) $(TASK) --manifest-path $@/Cargo.toml + +.PHONY: $(packages) test diff --git a/bigint/Cargo.toml b/bigint/Cargo.toml index 729e5cc..657e511 100644 --- a/bigint/Cargo.toml +++ b/bigint/Cargo.toml @@ -6,11 +6,9 @@ version = "0.1.0" [dependencies] [dependencies.num-integer] -optional = false path = "../integer" [dependencies.num-traits] -optional = false path = "../traits" [dependencies.rand] @@ -20,3 +18,6 @@ version = "0.3.14" [dependencies.serde] optional = true version = "0.7.0" + +[features] +default = ["rand"] diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index 7bb3cc5..4f5b0a3 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -18,8 +18,9 @@ //! //! ## Example //! -//! ```rust -//! use num::{BigUint, Zero, One}; +//! ```rust,ignore +//! use num_bigint::BigUint; +//! use num_traits::{Zero, One}; //! use std::mem::replace; //! //! // Calculate large fibonacci numbers. @@ -42,11 +43,11 @@ //! //! ```rust //! extern crate rand; -//! extern crate num; +//! extern crate num_bigint as bigint; //! //! # #[cfg(feature = "rand")] //! # fn main() { -//! use num::bigint::{ToBigInt, RandBigInt}; +//! use bigint::{ToBigInt, RandBigInt}; //! //! let mut rng = rand::thread_rng(); //! let a = rng.gen_bigint(1000); @@ -64,6 +65,9 @@ //! # } //! ``` +#[cfg(any(feature = "rand", test))] +extern crate rand; + extern crate num_integer as integer; extern crate num_traits as traits; @@ -75,6 +79,7 @@ use std::num::ParseIntError; use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub}; use std::str::{self, FromStr}; use std::fmt; +use std::hash; use std::cmp::Ordering::{self, Less, Greater, Equal}; use std::{f32, f64}; use std::{u8, i64, u64}; @@ -1655,7 +1660,7 @@ impl BigUint { /// # Examples /// /// ``` - /// use num::bigint::BigUint; + /// use num_bigint::BigUint; /// /// assert_eq!(BigUint::from_bytes_be(b"A"), /// BigUint::parse_bytes(b"65", 10).unwrap()); @@ -1694,7 +1699,7 @@ impl BigUint { /// # Examples /// /// ``` - /// use num::bigint::BigUint; + /// use num_bigint::BigUint; /// /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_le(), vec![101, 4]); @@ -1713,7 +1718,7 @@ impl BigUint { /// # Examples /// /// ``` - /// use num::bigint::BigUint; + /// use num_bigint::BigUint; /// /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_be(), vec![4, 101]); @@ -1731,7 +1736,7 @@ impl BigUint { /// # Examples /// /// ``` - /// use num::bigint::BigUint; + /// use num_bigint::BigUint; /// /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); @@ -1748,7 +1753,7 @@ impl BigUint { /// # Examples /// /// ``` - /// use num::bigint::{BigUint, ToBigUint}; + /// use num_bigint::{BigUint, ToBigUint}; /// /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234)); /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); @@ -2764,7 +2769,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::{BigInt, Sign}; + /// use num_bigint::{BigInt, Sign}; /// /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"), /// BigInt::parse_bytes(b"65", 10).unwrap()); @@ -2793,7 +2798,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::{ToBigInt, Sign}; + /// use num_bigint::{ToBigInt, Sign}; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); @@ -2808,7 +2813,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::{ToBigInt, Sign}; + /// use num_bigint::{ToBigInt, Sign}; /// /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); @@ -2824,7 +2829,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::BigInt; + /// use num_bigint::BigInt; /// /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); @@ -2846,7 +2851,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::{ToBigInt, Sign}; + /// use num_bigint::{ToBigInt, Sign}; /// /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus); /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus); @@ -2862,7 +2867,7 @@ impl BigInt { /// # Examples /// /// ``` - /// use num::bigint::{BigInt, ToBigInt}; + /// use num_bigint::{BigInt, ToBigInt}; /// /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234)); /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); @@ -2935,9 +2940,17 @@ impl From for ParseBigIntError { } } +#[cfg(test)] +fn hash(x: &T) -> u64 { + use std::hash::Hasher; + let mut hasher = hash::SipHasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + #[cfg(test)] mod biguint_tests { - use Integer; + use integer::Integer; use super::{BigDigit, BigUint, ToBigUint, big_digit}; use super::{BigInt, RandBigInt, ToBigInt}; use super::Sign::Plus; @@ -2950,9 +2963,9 @@ mod biguint_tests { use std::{u8, u16, u32, u64, usize}; use rand::thread_rng; - use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv}; - use {ToPrimitive, FromPrimitive}; - use Float; + use traits::{Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, ToPrimitive, + FromPrimitive, Float}; + /// Assert that an op works for all val/ref combinations macro_rules! assert_op { @@ -3083,10 +3096,10 @@ mod biguint_tests { let c = BigUint::new(vec![1]); let d = BigUint::new(vec![1, 0, 0, 0, 0, 0]); let e = BigUint::new(vec![0, 0, 0, 0, 0, 1]); - assert!(::hash(&a) == ::hash(&b)); - assert!(::hash(&b) != ::hash(&c)); - assert!(::hash(&c) == ::hash(&d)); - assert!(::hash(&d) != ::hash(&e)); + assert!(super::hash(&a) == super::hash(&b)); + assert!(super::hash(&b) != super::hash(&c)); + assert!(super::hash(&c) == super::hash(&d)); + assert!(super::hash(&d) != super::hash(&e)); } const BIT_TESTS: &'static [(&'static [BigDigit], @@ -4173,7 +4186,6 @@ mod biguint_tests { #[cfg(test)] mod bigint_tests { - use Integer; use super::{BigDigit, BigUint, ToBigUint}; use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit}; use super::Sign::{Minus, NoSign, Plus}; @@ -4187,8 +4199,8 @@ mod bigint_tests { use rand::thread_rng; - use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num}; - use Float; + use integer::Integer; + use traits::{Zero, One, Signed, ToPrimitive, FromPrimitive, Num, Float}; /// Assert that an op works for all val/ref combinations macro_rules! assert_op { @@ -4334,11 +4346,11 @@ mod bigint_tests { let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]); let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]); let f = BigInt::new(Minus, vec![1]); - assert!(::hash(&a) == ::hash(&b)); - assert!(::hash(&b) != ::hash(&c)); - assert!(::hash(&c) == ::hash(&d)); - assert!(::hash(&d) != ::hash(&e)); - assert!(::hash(&c) != ::hash(&f)); + assert!(super::hash(&a) == super::hash(&b)); + assert!(super::hash(&b) != super::hash(&c)); + assert!(super::hash(&c) == super::hash(&d)); + assert!(super::hash(&d) != super::hash(&e)); + assert!(super::hash(&c) != super::hash(&f)); } #[test] diff --git a/integer/src/lib.rs b/integer/src/lib.rs index 6059133..eee4ba2 100644 --- a/integer/src/lib.rs +++ b/integer/src/lib.rs @@ -20,7 +20,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert!(( 8).div_floor(& 3) == 2); /// assert!(( 8).div_floor(&-3) == -3); /// assert!((-8).div_floor(& 3) == -3); @@ -36,7 +36,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// Floored integer modulo, satisfying: /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// # let n = 1; let d = 1; /// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n) /// ~~~ @@ -44,7 +44,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert!(( 8).mod_floor(& 3) == 2); /// assert!(( 8).mod_floor(&-3) == -1); /// assert!((-8).mod_floor(& 3) == 1); @@ -62,7 +62,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(6.gcd(&8), 2); /// assert_eq!(7.gcd(&3), 1); /// ~~~ @@ -73,7 +73,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(7.lcm(&3), 21); /// assert_eq!(2.lcm(&4), 4); /// ~~~ @@ -87,7 +87,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(9.is_multiple_of(&3), true); /// assert_eq!(3.is_multiple_of(&9), false); /// ~~~ @@ -98,7 +98,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(3.is_even(), false); /// assert_eq!(4.is_even(), true); /// ~~~ @@ -109,7 +109,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(3.is_odd(), true); /// assert_eq!(4.is_odd(), false); /// ~~~ @@ -121,7 +121,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(( 8).div_rem( &3), ( 2, 2)); /// assert_eq!(( 8).div_rem(&-3), (-2, 2)); /// assert_eq!((-8).div_rem( &3), (-2, -2)); @@ -141,7 +141,7 @@ pub trait Integer: Sized + Num + PartialOrd + Ord + Eq { /// # Examples /// /// ~~~ - /// # use num::Integer; + /// # use num_integer::Integer; /// assert_eq!(( 8).div_mod_floor( &3), ( 2, 2)); /// assert_eq!(( 8).div_mod_floor(&-3), (-3, -1)); /// assert_eq!((-8).div_mod_floor( &3), (-3, 1)); diff --git a/rational/Cargo.toml b/rational/Cargo.toml new file mode 100644 index 0000000..5524742 --- /dev/null +++ b/rational/Cargo.toml @@ -0,0 +1,24 @@ +[package] +authors = ["Łukasz Jan Niemier "] +name = "num-rational" +version = "0.1.0" + +[dependencies] + +[dependencies.num-bigint] +optional = true +path = "../bigint" + +[dependencies.num-integer] +path = "../integer" + +[dependencies.num-traits] +path = "../traits" + +[dependencies.serde] +optional = true +version = "0.7.0" + +[features] +default = ["bigint"] +bigint = ["num-bigint"] diff --git a/rational/src/lib.rs b/rational/src/lib.rs new file mode 100644 index 0000000..09ecafb --- /dev/null +++ b/rational/src/lib.rs @@ -0,0 +1,1091 @@ +// Copyright 2013-2014 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. + +//! Rational numbers + +#[cfg(feature = "serde")] +extern crate serde; +#[cfg(feature = "num-bigint")] +extern crate num_bigint as bigint; + +extern crate num_traits as traits; +extern crate num_integer as integer; + +use std::cmp; +use std::error::Error; +use std::fmt; +use std::hash; +use std::ops::{Add, Div, Mul, Neg, Rem, Sub}; +use std::str::FromStr; + +#[cfg(feature = "serde")] +use serde; + +#[cfg(feature = "num-bigint")] +use bigint::{BigInt, BigUint, Sign}; + +use integer::Integer; +use traits::{FromPrimitive, Float, PrimInt, Num, Signed, Zero, One}; + +/// Represents the ratio between 2 numbers. +#[derive(Copy, Clone, Hash, Debug)] +#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] +#[allow(missing_docs)] +pub struct Ratio { + numer: T, + denom: T, +} + +/// Alias for a `Ratio` of machine-sized integers. +pub type Rational = Ratio; +pub type Rational32 = Ratio; +pub type Rational64 = Ratio; + +#[cfg(feature = "num-bigint")] +/// Alias for arbitrary precision rationals. +pub type BigRational = Ratio; + +impl Ratio { + /// Creates a ratio representing the integer `t`. + #[inline] + pub fn from_integer(t: T) -> Ratio { + Ratio::new_raw(t, One::one()) + } + + /// Creates a ratio without checking for `denom == 0` or reducing. + #[inline] + pub fn new_raw(numer: T, denom: T) -> Ratio { + Ratio { + numer: numer, + denom: denom, + } + } + + /// Create a new Ratio. Fails if `denom == 0`. + #[inline] + pub fn new(numer: T, denom: T) -> Ratio { + if denom == Zero::zero() { + panic!("denominator == 0"); + } + let mut ret = Ratio::new_raw(numer, denom); + ret.reduce(); + ret + } + + /// Converts to an integer. + #[inline] + pub fn to_integer(&self) -> T { + self.trunc().numer + } + + /// Gets an immutable reference to the numerator. + #[inline] + pub fn numer<'a>(&'a self) -> &'a T { + &self.numer + } + + /// Gets an immutable reference to the denominator. + #[inline] + pub fn denom<'a>(&'a self) -> &'a T { + &self.denom + } + + /// Returns true if the rational number is an integer (denominator is 1). + #[inline] + pub fn is_integer(&self) -> bool { + self.denom == One::one() + } + + /// Put self into lowest terms, with denom > 0. + fn reduce(&mut self) { + let g: T = self.numer.gcd(&self.denom); + + // FIXME(#5992): assignment operator overloads + // self.numer /= g; + self.numer = self.numer.clone() / g.clone(); + // FIXME(#5992): assignment operator overloads + // self.denom /= g; + self.denom = self.denom.clone() / g; + + // keep denom positive! + if self.denom < T::zero() { + self.numer = T::zero() - self.numer.clone(); + self.denom = T::zero() - self.denom.clone(); + } + } + + /// Returns a `reduce`d copy of self. + pub fn reduced(&self) -> Ratio { + let mut ret = self.clone(); + ret.reduce(); + ret + } + + /// Returns the reciprocal. + #[inline] + pub fn recip(&self) -> Ratio { + Ratio::new_raw(self.denom.clone(), self.numer.clone()) + } + + /// Rounds towards minus infinity. + #[inline] + pub fn floor(&self) -> Ratio { + if *self < Zero::zero() { + let one: T = One::one(); + Ratio::from_integer((self.numer.clone() - self.denom.clone() + one) / + self.denom.clone()) + } else { + Ratio::from_integer(self.numer.clone() / self.denom.clone()) + } + } + + /// Rounds towards plus infinity. + #[inline] + pub fn ceil(&self) -> Ratio { + if *self < Zero::zero() { + Ratio::from_integer(self.numer.clone() / self.denom.clone()) + } else { + let one: T = One::one(); + Ratio::from_integer((self.numer.clone() + self.denom.clone() - one) / + self.denom.clone()) + } + } + + /// Rounds to the nearest integer. Rounds half-way cases away from zero. + #[inline] + pub fn round(&self) -> Ratio { + let zero: Ratio = Zero::zero(); + let one: T = One::one(); + let two: T = one.clone() + one.clone(); + + // Find unsigned fractional part of rational number + let mut fractional = self.fract(); + if fractional < zero { + fractional = zero - fractional + }; + + // The algorithm compares the unsigned fractional part with 1/2, that + // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use + // a >= (b/2)+1. This avoids overflow issues. + let half_or_larger = if fractional.denom().is_even() { + *fractional.numer() >= fractional.denom().clone() / two.clone() + } else { + *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone() + }; + + if half_or_larger { + let one: Ratio = One::one(); + if *self >= Zero::zero() { + self.trunc() + one + } else { + self.trunc() - one + } + } else { + self.trunc() + } + } + + /// Rounds towards zero. + #[inline] + pub fn trunc(&self) -> Ratio { + Ratio::from_integer(self.numer.clone() / self.denom.clone()) + } + + /// Returns the fractional part of a number. + #[inline] + pub fn fract(&self) -> Ratio { + Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone()) + } +} + +impl Ratio { + /// Raises the ratio to the power of an exponent + #[inline] + pub fn pow(&self, expon: i32) -> Ratio { + match expon.cmp(&0) { + cmp::Ordering::Equal => One::one(), + cmp::Ordering::Less => self.recip().pow(-expon), + cmp::Ordering::Greater => { + Ratio::new_raw(self.numer.pow(expon as u32), self.denom.pow(expon as u32)) + } + } + } +} + +#[cfg(feature = "num-bigint")] +impl Ratio { + /// Converts a float into a rational number. + pub fn from_float(f: T) -> Option { + if !f.is_finite() { + return None; + } + let (mantissa, exponent, sign) = f.integer_decode(); + let bigint_sign = if sign == 1 { + Sign::Plus + } else { + Sign::Minus + }; + if exponent < 0 { + let one: BigInt = One::one(); + let denom: BigInt = one << ((-exponent) as usize); + let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); + Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom)) + } else { + let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); + numer = numer << (exponent as usize); + Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer))) + } + } +} + +// Comparisons + +// Mathematically, comparing a/b and c/d is the same as comparing a*d and b*c, but it's very easy +// for those multiplications to overflow fixed-size integers, so we need to take care. + +impl Ord for Ratio { + #[inline] + fn cmp(&self, other: &Self) -> cmp::Ordering { + // With equal denominators, the numerators can be directly compared + if self.denom == other.denom { + let ord = self.numer.cmp(&other.numer); + return if self.denom < T::zero() { + ord.reverse() + } else { + ord + }; + } + + // With equal numerators, the denominators can be inversely compared + if self.numer == other.numer { + let ord = self.denom.cmp(&other.denom); + return if self.numer < T::zero() { + ord + } else { + ord.reverse() + }; + } + + // Unfortunately, we don't have CheckedMul to try. That could sometimes avoid all the + // division below, or even always avoid it for BigInt and BigUint. + // FIXME- future breaking change to add Checked* to Integer? + + // Compare as floored integers and remainders + let (self_int, self_rem) = self.numer.div_mod_floor(&self.denom); + let (other_int, other_rem) = other.numer.div_mod_floor(&other.denom); + match self_int.cmp(&other_int) { + cmp::Ordering::Greater => cmp::Ordering::Greater, + cmp::Ordering::Less => cmp::Ordering::Less, + cmp::Ordering::Equal => { + match (self_rem.is_zero(), other_rem.is_zero()) { + (true, true) => cmp::Ordering::Equal, + (true, false) => cmp::Ordering::Less, + (false, true) => cmp::Ordering::Greater, + (false, false) => { + // Compare the reciprocals of the remaining fractions in reverse + let self_recip = Ratio::new_raw(self.denom.clone(), self_rem); + let other_recip = Ratio::new_raw(other.denom.clone(), other_rem); + self_recip.cmp(&other_recip).reverse() + } + } + } + } + } +} + +impl PartialOrd for Ratio { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for Ratio { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == cmp::Ordering::Equal + } +} + +impl Eq for Ratio {} + + +macro_rules! forward_val_val_binop { + (impl $imp:ident, $method:ident) => { + impl $imp> for Ratio { + type Output = Ratio; + + #[inline] + fn $method(self, other: Ratio) -> Ratio { + (&self).$method(&other) + } + } + } +} + +macro_rules! forward_ref_val_binop { + (impl $imp:ident, $method:ident) => { + impl<'a, T> $imp> for &'a Ratio where + T: Clone + Integer + { + type Output = Ratio; + + #[inline] + fn $method(self, other: Ratio) -> Ratio { + self.$method(&other) + } + } + } +} + +macro_rules! forward_val_ref_binop { + (impl $imp:ident, $method:ident) => { + impl<'a, T> $imp<&'a Ratio> for Ratio where + T: Clone + Integer + { + type Output = Ratio; + + #[inline] + fn $method(self, other: &Ratio) -> Ratio { + (&self).$method(other) + } + } + } +} + +macro_rules! forward_all_binop { + (impl $imp:ident, $method:ident) => { + forward_val_val_binop!(impl $imp, $method); + forward_ref_val_binop!(impl $imp, $method); + forward_val_ref_binop!(impl $imp, $method); + }; +} + +// Arithmetic +forward_all_binop!(impl Mul, mul); +// a/b * c/d = (a*c)/(b*d) +impl<'a, 'b, T> Mul<&'b Ratio> for &'a Ratio + where T: Clone + Integer +{ + type Output = Ratio; + #[inline] + fn mul(self, rhs: &Ratio) -> Ratio { + Ratio::new(self.numer.clone() * rhs.numer.clone(), + self.denom.clone() * rhs.denom.clone()) + } +} + +forward_all_binop!(impl Div, div); +// (a/b) / (c/d) = (a*d)/(b*c) +impl<'a, 'b, T> Div<&'b Ratio> for &'a Ratio + where T: Clone + Integer +{ + type Output = Ratio; + + #[inline] + fn div(self, rhs: &Ratio) -> Ratio { + Ratio::new(self.numer.clone() * rhs.denom.clone(), + self.denom.clone() * rhs.numer.clone()) + } +} + +// Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern +macro_rules! arith_impl { + (impl $imp:ident, $method:ident) => { + forward_all_binop!(impl $imp, $method); + impl<'a, 'b, T: Clone + Integer> + $imp<&'b Ratio> for &'a Ratio { + type Output = Ratio; + #[inline] + fn $method(self, rhs: &Ratio) -> Ratio { + Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()), + self.denom.clone() * rhs.denom.clone()) + } + } + } +} + +// a/b + c/d = (a*d + b*c)/(b*d) +arith_impl!(impl Add, add); + +// a/b - c/d = (a*d - b*c)/(b*d) +arith_impl!(impl Sub, sub); + +// a/b % c/d = (a*d % b*c)/(b*d) +arith_impl!(impl Rem, rem); + +impl Neg for Ratio + where T: Clone + Integer + Neg +{ + type Output = Ratio; + + #[inline] + fn neg(self) -> Ratio { + Ratio::new_raw(-self.numer, self.denom) + } +} + +impl<'a, T> Neg for &'a Ratio + where T: Clone + Integer + Neg +{ + type Output = Ratio; + + #[inline] + fn neg(self) -> Ratio { + -self.clone() + } +} + +// Constants +impl Zero for Ratio { + #[inline] + fn zero() -> Ratio { + Ratio::new_raw(Zero::zero(), One::one()) + } + + #[inline] + fn is_zero(&self) -> bool { + self.numer.is_zero() + } +} + +impl One for Ratio { + #[inline] + fn one() -> Ratio { + Ratio::new_raw(One::one(), One::one()) + } +} + +impl Num for Ratio { + type FromStrRadixErr = ParseRatioError; + + /// Parses `numer/denom` where the numbers are in base `radix`. + fn from_str_radix(s: &str, radix: u32) -> Result, ParseRatioError> { + let split: Vec<&str> = s.splitn(2, '/').collect(); + if split.len() < 2 { + Err(ParseRatioError { kind: RatioErrorKind::ParseError }) + } else { + let a_result: Result = T::from_str_radix(split[0], radix).map_err(|_| { + ParseRatioError { kind: RatioErrorKind::ParseError } + }); + a_result.and_then(|a| { + let b_result: Result = T::from_str_radix(split[1], radix).map_err(|_| { + ParseRatioError { kind: RatioErrorKind::ParseError } + }); + b_result.and_then(|b| { + if b.is_zero() { + Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator }) + } else { + Ok(Ratio::new(a.clone(), b.clone())) + } + }) + }) + } + } +} + +impl Signed for Ratio { + #[inline] + fn abs(&self) -> Ratio { + if self.is_negative() { + -self.clone() + } else { + self.clone() + } + } + + #[inline] + fn abs_sub(&self, other: &Ratio) -> Ratio { + if *self <= *other { + Zero::zero() + } else { + self - other + } + } + + #[inline] + fn signum(&self) -> Ratio { + if self.is_positive() { + Self::one() + } else if self.is_zero() { + Self::zero() + } else { + -Self::one() + } + } + + #[inline] + fn is_positive(&self) -> bool { + !self.is_negative() + } + + #[inline] + fn is_negative(&self) -> bool { + self.numer.is_negative() ^ self.denom.is_negative() + } +} + +// String conversions +impl fmt::Display for Ratio + where T: fmt::Display + Eq + One +{ + /// Renders as `numer/denom`. If denom=1, renders as numer. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.denom == One::one() { + write!(f, "{}", self.numer) + } else { + write!(f, "{}/{}", self.numer, self.denom) + } + } +} + +impl FromStr for Ratio { + type Err = ParseRatioError; + + /// Parses `numer/denom` or just `numer`. + fn from_str(s: &str) -> Result, ParseRatioError> { + let mut split = s.splitn(2, '/'); + + let n = try!(split.next().ok_or(ParseRatioError { kind: RatioErrorKind::ParseError })); + let num = try!(FromStr::from_str(n) + .map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError })); + + let d = split.next().unwrap_or("1"); + let den = try!(FromStr::from_str(d) + .map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError })); + + if Zero::is_zero(&den) { + Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator }) + } else { + Ok(Ratio::new(num, den)) + } + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for Ratio + where T: serde::Serialize + Clone + Integer + PartialOrd +{ + fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> + where S: serde::Serializer + { + (self.numer(), self.denom()).serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl serde::Deserialize for Ratio + where T: serde::Deserialize + Clone + Integer + PartialOrd +{ + fn deserialize(deserializer: &mut D) -> Result + where D: serde::Deserializer + { + let (numer, denom) = try!(serde::Deserialize::deserialize(deserializer)); + if denom == Zero::zero() { + Err(serde::de::Error::invalid_value("denominator is zero")) + } else { + Ok(Ratio::new_raw(numer, denom)) + } + } +} + +// FIXME: Bubble up specific errors +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct ParseRatioError { + kind: RatioErrorKind, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +enum RatioErrorKind { + ParseError, + ZeroDenominator, +} + +impl fmt::Display for ParseRatioError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl Error for ParseRatioError { + fn description(&self) -> &str { + self.kind.description() + } +} + +impl RatioErrorKind { + fn description(&self) -> &'static str { + match *self { + RatioErrorKind::ParseError => "failed to parse integer", + RatioErrorKind::ZeroDenominator => "zero value denominator", + } + } +} + +#[cfg(test)] +fn hash(x: &T) -> u64 { + use std::hash::Hasher; + let mut hasher = hash::SipHasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +mod test { + use super::{Ratio, Rational}; + #[cfg(feature = "num-bigint")] + use super::BigRational; + + use std::str::FromStr; + use std::i32; + use traits::{Zero, One, Signed, FromPrimitive, Float}; + + pub const _0: Rational = Ratio { + numer: 0, + denom: 1, + }; + pub const _1: Rational = Ratio { + numer: 1, + denom: 1, + }; + pub const _2: Rational = Ratio { + numer: 2, + denom: 1, + }; + pub const _1_2: Rational = Ratio { + numer: 1, + denom: 2, + }; + pub const _3_2: Rational = Ratio { + numer: 3, + denom: 2, + }; + pub const _NEG1_2: Rational = Ratio { + numer: -1, + denom: 2, + }; + pub const _1_3: Rational = Ratio { + numer: 1, + denom: 3, + }; + pub const _NEG1_3: Rational = Ratio { + numer: -1, + denom: 3, + }; + pub const _2_3: Rational = Ratio { + numer: 2, + denom: 3, + }; + pub const _NEG2_3: Rational = Ratio { + numer: -2, + denom: 3, + }; + + #[cfg(feature = "num-bigint")] + pub fn to_big(n: Rational) -> BigRational { + Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(), + FromPrimitive::from_isize(n.denom).unwrap()) + } + #[cfg(not(feature = "num-bigint"))] + pub fn to_big(n: Rational) -> Rational { + Ratio::new(FromPrimitive::from_isize(n.numer).unwrap(), + FromPrimitive::from_isize(n.denom).unwrap()) + } + + #[test] + fn test_test_constants() { + // check our constants are what Ratio::new etc. would make. + assert_eq!(_0, Zero::zero()); + assert_eq!(_1, One::one()); + assert_eq!(_2, Ratio::from_integer(2)); + assert_eq!(_1_2, Ratio::new(1, 2)); + assert_eq!(_3_2, Ratio::new(3, 2)); + assert_eq!(_NEG1_2, Ratio::new(-1, 2)); + } + + #[test] + fn test_new_reduce() { + let one22 = Ratio::new(2, 2); + + assert_eq!(one22, One::one()); + } + #[test] + #[should_panic] + fn test_new_zero() { + let _a = Ratio::new(1, 0); + } + + + #[test] + fn test_cmp() { + assert!(_0 == _0 && _1 == _1); + assert!(_0 != _1 && _1 != _0); + assert!(_0 < _1 && !(_1 < _0)); + assert!(_1 > _0 && !(_0 > _1)); + + assert!(_0 <= _0 && _1 <= _1); + assert!(_0 <= _1 && !(_1 <= _0)); + + assert!(_0 >= _0 && _1 >= _1); + assert!(_1 >= _0 && !(_0 >= _1)); + } + + #[test] + fn test_cmp_overflow() { + use std::cmp::Ordering; + + // issue #7 example: + let big = Ratio::new(128u8, 1); + let small = big.recip(); + assert!(big > small); + + // try a few that are closer together + // (some matching numer, some matching denom, some neither) + let ratios = vec![ + Ratio::new(125_i8, 127_i8), + Ratio::new(63_i8, 64_i8), + Ratio::new(124_i8, 125_i8), + Ratio::new(125_i8, 126_i8), + Ratio::new(126_i8, 127_i8), + Ratio::new(127_i8, 126_i8), + ]; + + fn check_cmp(a: Ratio, b: Ratio, ord: Ordering) { + println!("comparing {} and {}", a, b); + assert_eq!(a.cmp(&b), ord); + assert_eq!(b.cmp(&a), ord.reverse()); + } + + for (i, &a) in ratios.iter().enumerate() { + check_cmp(a, a, Ordering::Equal); + check_cmp(-a, a, Ordering::Less); + for &b in &ratios[i + 1..] { + check_cmp(a, b, Ordering::Less); + check_cmp(-a, -b, Ordering::Greater); + check_cmp(a.recip(), b.recip(), Ordering::Greater); + check_cmp(-a.recip(), -b.recip(), Ordering::Less); + } + } + } + + #[test] + fn test_to_integer() { + assert_eq!(_0.to_integer(), 0); + assert_eq!(_1.to_integer(), 1); + assert_eq!(_2.to_integer(), 2); + assert_eq!(_1_2.to_integer(), 0); + assert_eq!(_3_2.to_integer(), 1); + assert_eq!(_NEG1_2.to_integer(), 0); + } + + + #[test] + fn test_numer() { + assert_eq!(_0.numer(), &0); + assert_eq!(_1.numer(), &1); + assert_eq!(_2.numer(), &2); + assert_eq!(_1_2.numer(), &1); + assert_eq!(_3_2.numer(), &3); + assert_eq!(_NEG1_2.numer(), &(-1)); + } + #[test] + fn test_denom() { + assert_eq!(_0.denom(), &1); + assert_eq!(_1.denom(), &1); + assert_eq!(_2.denom(), &1); + assert_eq!(_1_2.denom(), &2); + assert_eq!(_3_2.denom(), &2); + assert_eq!(_NEG1_2.denom(), &2); + } + + + #[test] + fn test_is_integer() { + assert!(_0.is_integer()); + assert!(_1.is_integer()); + assert!(_2.is_integer()); + assert!(!_1_2.is_integer()); + assert!(!_3_2.is_integer()); + assert!(!_NEG1_2.is_integer()); + } + + #[test] + fn test_show() { + assert_eq!(format!("{}", _2), "2".to_string()); + assert_eq!(format!("{}", _1_2), "1/2".to_string()); + assert_eq!(format!("{}", _0), "0".to_string()); + assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string()); + } + + mod arith { + use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big}; + use super::super::{Ratio, Rational}; + + #[test] + fn test_add() { + fn test(a: Rational, b: Rational, c: Rational) { + assert_eq!(a + b, c); + assert_eq!(to_big(a) + to_big(b), to_big(c)); + } + + test(_1, _1_2, _3_2); + test(_1, _1, _2); + test(_1_2, _3_2, _2); + test(_1_2, _NEG1_2, _0); + } + + #[test] + fn test_sub() { + fn test(a: Rational, b: Rational, c: Rational) { + assert_eq!(a - b, c); + assert_eq!(to_big(a) - to_big(b), to_big(c)) + } + + test(_1, _1_2, _1_2); + test(_3_2, _1_2, _1); + test(_1, _NEG1_2, _3_2); + } + + #[test] + fn test_mul() { + fn test(a: Rational, b: Rational, c: Rational) { + assert_eq!(a * b, c); + assert_eq!(to_big(a) * to_big(b), to_big(c)) + } + + test(_1, _1_2, _1_2); + test(_1_2, _3_2, Ratio::new(3, 4)); + test(_1_2, _NEG1_2, Ratio::new(-1, 4)); + } + + #[test] + fn test_div() { + fn test(a: Rational, b: Rational, c: Rational) { + assert_eq!(a / b, c); + assert_eq!(to_big(a) / to_big(b), to_big(c)) + } + + test(_1, _1_2, _2); + test(_3_2, _1_2, _1 + _2); + test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2); + } + + #[test] + fn test_rem() { + fn test(a: Rational, b: Rational, c: Rational) { + assert_eq!(a % b, c); + assert_eq!(to_big(a) % to_big(b), to_big(c)) + } + + test(_3_2, _1, _1_2); + test(_2, _NEG1_2, _0); + test(_1_2, _2, _1_2); + } + + #[test] + fn test_neg() { + fn test(a: Rational, b: Rational) { + assert_eq!(-a, b); + assert_eq!(-to_big(a), to_big(b)) + } + + test(_0, _0); + test(_1_2, _NEG1_2); + test(-_1, _1); + } + #[test] + fn test_zero() { + assert_eq!(_0 + _0, _0); + assert_eq!(_0 * _0, _0); + assert_eq!(_0 * _1, _0); + assert_eq!(_0 / _NEG1_2, _0); + assert_eq!(_0 - _0, _0); + } + #[test] + #[should_panic] + fn test_div_0() { + let _a = _1 / _0; + } + } + + #[test] + fn test_round() { + assert_eq!(_1_3.ceil(), _1); + assert_eq!(_1_3.floor(), _0); + assert_eq!(_1_3.round(), _0); + assert_eq!(_1_3.trunc(), _0); + + assert_eq!(_NEG1_3.ceil(), _0); + assert_eq!(_NEG1_3.floor(), -_1); + assert_eq!(_NEG1_3.round(), _0); + assert_eq!(_NEG1_3.trunc(), _0); + + assert_eq!(_2_3.ceil(), _1); + assert_eq!(_2_3.floor(), _0); + assert_eq!(_2_3.round(), _1); + assert_eq!(_2_3.trunc(), _0); + + assert_eq!(_NEG2_3.ceil(), _0); + assert_eq!(_NEG2_3.floor(), -_1); + assert_eq!(_NEG2_3.round(), -_1); + assert_eq!(_NEG2_3.trunc(), _0); + + assert_eq!(_1_2.ceil(), _1); + assert_eq!(_1_2.floor(), _0); + assert_eq!(_1_2.round(), _1); + assert_eq!(_1_2.trunc(), _0); + + assert_eq!(_NEG1_2.ceil(), _0); + assert_eq!(_NEG1_2.floor(), -_1); + assert_eq!(_NEG1_2.round(), -_1); + assert_eq!(_NEG1_2.trunc(), _0); + + assert_eq!(_1.ceil(), _1); + assert_eq!(_1.floor(), _1); + assert_eq!(_1.round(), _1); + assert_eq!(_1.trunc(), _1); + + // Overflow checks + + let _neg1 = Ratio::from_integer(-1); + let _large_rat1 = Ratio::new(i32::MAX, i32::MAX - 1); + let _large_rat2 = Ratio::new(i32::MAX - 1, i32::MAX); + let _large_rat3 = Ratio::new(i32::MIN + 2, i32::MIN + 1); + let _large_rat4 = Ratio::new(i32::MIN + 1, i32::MIN + 2); + let _large_rat5 = Ratio::new(i32::MIN + 2, i32::MAX); + let _large_rat6 = Ratio::new(i32::MAX, i32::MIN + 2); + let _large_rat7 = Ratio::new(1, i32::MIN + 1); + let _large_rat8 = Ratio::new(1, i32::MAX); + + assert_eq!(_large_rat1.round(), One::one()); + assert_eq!(_large_rat2.round(), One::one()); + assert_eq!(_large_rat3.round(), One::one()); + assert_eq!(_large_rat4.round(), One::one()); + assert_eq!(_large_rat5.round(), _neg1); + assert_eq!(_large_rat6.round(), _neg1); + assert_eq!(_large_rat7.round(), Zero::zero()); + assert_eq!(_large_rat8.round(), Zero::zero()); + } + + #[test] + fn test_fract() { + assert_eq!(_1.fract(), _0); + assert_eq!(_NEG1_2.fract(), _NEG1_2); + assert_eq!(_1_2.fract(), _1_2); + assert_eq!(_3_2.fract(), _1_2); + } + + #[test] + fn test_recip() { + assert_eq!(_1 * _1.recip(), _1); + assert_eq!(_2 * _2.recip(), _1); + assert_eq!(_1_2 * _1_2.recip(), _1); + assert_eq!(_3_2 * _3_2.recip(), _1); + assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1); + } + + #[test] + fn test_pow() { + assert_eq!(_1_2.pow(2), Ratio::new(1, 4)); + assert_eq!(_1_2.pow(-2), Ratio::new(4, 1)); + assert_eq!(_1.pow(1), _1); + assert_eq!(_NEG1_2.pow(2), _1_2.pow(2)); + assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3)); + assert_eq!(_3_2.pow(0), _1); + assert_eq!(_3_2.pow(-1), _3_2.recip()); + assert_eq!(_3_2.pow(3), Ratio::new(27, 8)); + } + + #[test] + fn test_to_from_str() { + fn test(r: Rational, s: String) { + assert_eq!(FromStr::from_str(&s), Ok(r)); + assert_eq!(r.to_string(), s); + } + test(_1, "1".to_string()); + test(_0, "0".to_string()); + test(_1_2, "1/2".to_string()); + test(_3_2, "3/2".to_string()); + test(_2, "2".to_string()); + test(_NEG1_2, "-1/2".to_string()); + } + #[test] + fn test_from_str_fail() { + fn test(s: &str) { + let rational: Result = FromStr::from_str(s); + assert!(rational.is_err()); + } + + let xs = ["0 /1", "abc", "", "1/", "--1/2", "3/2/1", "1/0"]; + for &s in xs.iter() { + test(s); + } + } + + #[cfg(feature = "num-bigint")] + #[test] + fn test_from_float() { + fn test(given: T, (numer, denom): (&str, &str)) { + let ratio: BigRational = Ratio::from_float(given).unwrap(); + assert_eq!(ratio, + Ratio::new(FromStr::from_str(numer).unwrap(), + FromStr::from_str(denom).unwrap())); + } + + // f32 + test(3.14159265359f32, ("13176795", "4194304")); + test(2f32.powf(100.), ("1267650600228229401496703205376", "1")); + test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1")); + test(1.0 / 2f32.powf(100.), + ("1", "1267650600228229401496703205376")); + test(684729.48391f32, ("1369459", "2")); + test(-8573.5918555f32, ("-4389679", "512")); + + // f64 + test(3.14159265359f64, ("3537118876014453", "1125899906842624")); + test(2f64.powf(100.), ("1267650600228229401496703205376", "1")); + test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1")); + test(684729.48391f64, ("367611342500051", "536870912")); + test(-8573.5918555f64, ("-4713381968463931", "549755813888")); + test(1.0 / 2f64.powf(100.), + ("1", "1267650600228229401496703205376")); + } + + #[cfg(feature = "num-bigint")] + #[test] + fn test_from_float_fail() { + use std::{f32, f64}; + + assert_eq!(Ratio::from_float(f32::NAN), None); + assert_eq!(Ratio::from_float(f32::INFINITY), None); + assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None); + assert_eq!(Ratio::from_float(f64::NAN), None); + assert_eq!(Ratio::from_float(f64::INFINITY), None); + assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None); + } + + #[test] + fn test_signed() { + assert_eq!(_NEG1_2.abs(), _1_2); + assert_eq!(_3_2.abs_sub(&_1_2), _1); + assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero()); + assert_eq!(_1_2.signum(), One::one()); + assert_eq!(_NEG1_2.signum(), ->::one()); + assert!(_NEG1_2.is_negative()); + assert!(!_NEG1_2.is_positive()); + assert!(!_1_2.is_negative()); + } + + #[test] + fn test_hash() { + assert!(::hash(&_0) != ::hash(&_1)); + assert!(::hash(&_0) != ::hash(&_3_2)); + } +} diff --git a/src/lib.rs b/src/lib.rs index a44bb9b..4fce75d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,7 +59,10 @@ extern crate num_traits; extern crate num_integer; +#[cfg(feature = "num-bigint")] extern crate num_bigint; +#[cfg(feature = "num-rational")] +extern crate num_rational; #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; @@ -73,11 +76,11 @@ extern crate rand; #[cfg(feature = "serde")] extern crate serde; -#[cfg(feature = "bigint")] +#[cfg(feature = "num-bigint")] pub use bigint::{BigInt, BigUint}; -#[cfg(feature = "rational")] +#[cfg(feature = "num-rational")] pub use rational::Rational; -#[cfg(all(feature = "rational", feature="bigint"))] +#[cfg(all(feature = "num-rational", feature="num-bigint"))] pub use rational::BigRational; #[cfg(feature = "complex")] pub use complex::Complex; @@ -91,14 +94,14 @@ pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded, use std::ops::{Mul}; -#[cfg(feature = "bigint")] -pub mod bigint { pub use num_bigint::*; } +#[cfg(feature = "num-bigint")] +pub use num_bigint as bigint; pub mod complex; -pub mod integer { pub use num_integer::*; } +pub use num_integer as integers; pub mod iter; -pub mod traits { pub use num_traits::*; } -#[cfg(feature = "rational")] -pub mod rational; +pub use num_traits as traits; +#[cfg(feature = "num-rational")] +pub use num_rational as rational; /// Returns the additive identity, `0`. #[inline(always)] pub fn zero() -> T { Zero::zero() } @@ -210,11 +213,3 @@ pub fn checked_pow(mut base: T, mut exp: usize) -> } Some(acc) } - -#[cfg(test)] -fn hash(x: &T) -> u64 { - use std::hash::Hasher; - let mut hasher = hash::SipHasher::new(); - x.hash(&mut hasher); - hasher.finish() -} diff --git a/traits/src/cast.rs b/traits/src/cast.rs index 90b99ef..cefa7ff 100644 --- a/traits/src/cast.rs +++ b/traits/src/cast.rs @@ -388,8 +388,7 @@ impl_from_primitive!(f64, to_f64); /// # Examples /// /// ``` -/// use num; -/// +/// # use num_traits as num; /// let twenty: f32 = num::cast(0x14).unwrap(); /// assert_eq!(twenty, 20f32); /// ``` diff --git a/traits/src/float.rs b/traits/src/float.rs index 5d1f0e0..f8c19ae 100644 --- a/traits/src/float.rs +++ b/traits/src/float.rs @@ -14,7 +14,7 @@ pub trait Float /// Returns the `NaN` value. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let nan: f32 = Float::nan(); /// @@ -24,7 +24,7 @@ pub trait Float /// Returns the infinite value. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f32; /// /// let infinity: f32 = Float::infinity(); @@ -37,7 +37,7 @@ pub trait Float /// Returns the negative infinite value. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f32; /// /// let neg_infinity: f32 = Float::neg_infinity(); @@ -50,7 +50,7 @@ pub trait Float /// Returns `-0.0`. /// /// ``` - /// use num::traits::{Zero, Float}; + /// use num_traits::{Zero, Float}; /// /// let inf: f32 = Float::infinity(); /// let zero: f32 = Zero::zero(); @@ -65,7 +65,7 @@ pub trait Float /// Returns the smallest finite value that this type can represent. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x: f64 = Float::min_value(); @@ -77,7 +77,7 @@ pub trait Float /// Returns the smallest positive, normalized value that this type can represent. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x: f64 = Float::min_positive_value(); @@ -89,7 +89,7 @@ pub trait Float /// Returns the largest finite value that this type can represent. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x: f64 = Float::max_value(); @@ -100,7 +100,7 @@ pub trait Float /// Returns `true` if this value is `NaN` and false otherwise. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let nan = f64::NAN; @@ -115,7 +115,7 @@ pub trait Float /// false otherwise. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f32; /// /// let f = 7.0f32; @@ -134,7 +134,7 @@ pub trait Float /// Returns `true` if this number is neither infinite nor `NaN`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f32; /// /// let f = 7.0f32; @@ -154,7 +154,7 @@ pub trait Float /// [subnormal][subnormal], or `NaN`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f32; /// /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 @@ -179,7 +179,7 @@ pub trait Float /// predicate instead. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::num::FpCategory; /// use std::f32; /// @@ -194,7 +194,7 @@ pub trait Float /// Returns the largest integer less than or equal to a number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 3.99; /// let g = 3.0; @@ -207,7 +207,7 @@ pub trait Float /// Returns the smallest integer greater than or equal to a number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 3.01; /// let g = 4.0; @@ -221,7 +221,7 @@ pub trait Float /// `0.0`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 3.3; /// let g = -3.3; @@ -234,7 +234,7 @@ pub trait Float /// Return the integer part of a number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 3.3; /// let g = -3.7; @@ -247,7 +247,7 @@ pub trait Float /// Returns the fractional part of a number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 3.5; /// let y = -3.5; @@ -263,7 +263,7 @@ pub trait Float /// number is `Float::nan()`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = 3.5; @@ -286,7 +286,7 @@ pub trait Float /// - `Float::nan()` if the number is `Float::nan()` /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let f = 3.5; @@ -302,7 +302,7 @@ pub trait Float /// `Float::infinity()`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let nan: f64 = f64::NAN; @@ -321,7 +321,7 @@ pub trait Float /// `Float::neg_infinity()`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let nan = f64::NAN; @@ -341,7 +341,7 @@ pub trait Float /// a separate multiplication operation followed by an add. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let m = 10.0; /// let x = 4.0; @@ -356,7 +356,7 @@ pub trait Float /// Take the reciprocal (inverse) of a number, `1/x`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 2.0; /// let abs_difference = (x.recip() - (1.0/x)).abs(); @@ -370,7 +370,7 @@ pub trait Float /// Using this function is generally faster than using `powf` /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 2.0; /// let abs_difference = (x.powi(2) - x*x).abs(); @@ -382,7 +382,7 @@ pub trait Float /// Raise a number to a floating point power. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 2.0; /// let abs_difference = (x.powf(2.0) - x*x).abs(); @@ -396,7 +396,7 @@ pub trait Float /// Returns NaN if `self` is a negative number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let positive = 4.0; /// let negative = -4.0; @@ -411,7 +411,7 @@ pub trait Float /// Returns `e^(self)`, (the exponential function). /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let one = 1.0; /// // e^1 @@ -427,7 +427,7 @@ pub trait Float /// Returns `2^(self)`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 2.0; /// @@ -441,7 +441,7 @@ pub trait Float /// Returns the natural logarithm of the number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let one = 1.0; /// // e^1 @@ -457,7 +457,7 @@ pub trait Float /// Returns the logarithm of the number with respect to an arbitrary base. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let ten = 10.0; /// let two = 2.0; @@ -476,7 +476,7 @@ pub trait Float /// Returns the base 2 logarithm of the number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let two = 2.0; /// @@ -490,7 +490,7 @@ pub trait Float /// Returns the base 10 logarithm of the number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let ten = 10.0; /// @@ -504,7 +504,7 @@ pub trait Float /// Returns the maximum of the two numbers. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 1.0; /// let y = 2.0; @@ -516,7 +516,7 @@ pub trait Float /// Returns the minimum of the two numbers. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 1.0; /// let y = 2.0; @@ -531,7 +531,7 @@ pub trait Float /// * Else: `self - other` /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 3.0; /// let y = -3.0; @@ -547,7 +547,7 @@ pub trait Float /// Take the cubic root of a number. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 8.0; /// @@ -562,7 +562,7 @@ pub trait Float /// legs of length `x` and `y`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 2.0; /// let y = 3.0; @@ -577,7 +577,7 @@ pub trait Float /// Computes the sine of a number (in radians). /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = f64::consts::PI/2.0; @@ -591,7 +591,7 @@ pub trait Float /// Computes the cosine of a number (in radians). /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = 2.0*f64::consts::PI; @@ -605,7 +605,7 @@ pub trait Float /// Computes the tangent of a number (in radians). /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = f64::consts::PI/4.0; @@ -620,7 +620,7 @@ pub trait Float /// [-1, 1]. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let f = f64::consts::PI / 2.0; @@ -637,7 +637,7 @@ pub trait Float /// [-1, 1]. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let f = f64::consts::PI / 4.0; @@ -653,7 +653,7 @@ pub trait Float /// range [-pi/2, pi/2]; /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let f = 1.0; /// @@ -672,7 +672,7 @@ pub trait Float /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let pi = f64::consts::PI; @@ -697,7 +697,7 @@ pub trait Float /// `(sin(x), cos(x))`. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = f64::consts::PI/4.0; @@ -715,7 +715,7 @@ pub trait Float /// number is close to zero. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 7.0; /// @@ -730,7 +730,7 @@ pub trait Float /// the operations were performed separately. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let x = f64::consts::E - 1.0; @@ -745,7 +745,7 @@ pub trait Float /// Hyperbolic sine function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let e = f64::consts::E; @@ -763,7 +763,7 @@ pub trait Float /// Hyperbolic cosine function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let e = f64::consts::E; @@ -781,7 +781,7 @@ pub trait Float /// Hyperbolic tangent function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let e = f64::consts::E; @@ -799,7 +799,7 @@ pub trait Float /// Inverse hyperbolic sine function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 1.0; /// let f = x.sinh().asinh(); @@ -813,7 +813,7 @@ pub trait Float /// Inverse hyperbolic cosine function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let x = 1.0; /// let f = x.cosh().acosh(); @@ -827,7 +827,7 @@ pub trait Float /// Inverse hyperbolic tangent function. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// use std::f64; /// /// let e = f64::consts::E; @@ -845,7 +845,7 @@ pub trait Float /// The floating point encoding is documented in the [Reference][floating-point]. /// /// ``` - /// use num::traits::Float; + /// use num_traits::Float; /// /// let num = 2.0f32; /// diff --git a/traits/src/int.rs b/traits/src/int.rs index 071df7f..6cc90ca 100644 --- a/traits/src/int.rs +++ b/traits/src/int.rs @@ -28,7 +28,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0b01001100u8; /// @@ -41,7 +41,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0b01001100u8; /// @@ -55,7 +55,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0b0101000u16; /// @@ -69,7 +69,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0b0101000u16; /// @@ -83,7 +83,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0x3456789ABCDEF012u64; @@ -98,7 +98,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0xDEF0123456789ABCu64; @@ -115,7 +115,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0x3456789ABCDEF000u64; @@ -132,7 +132,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0xFEDCBA9876543210u64; /// let m = 0xFFFFEDCBA9876543u64; @@ -149,7 +149,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFi64; /// let m = 0x3456789ABCDEF000i64; @@ -166,7 +166,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0xFEDCBA9876543210i64; /// let m = 0x000FEDCBA9876543i64; @@ -180,7 +180,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0xEFCDAB8967452301u64; @@ -196,7 +196,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// @@ -215,7 +215,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// @@ -234,7 +234,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// @@ -253,7 +253,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// let n = 0x0123456789ABCDEFu64; /// @@ -270,7 +270,7 @@ pub trait PrimInt /// # Examples /// /// ``` - /// use num::traits::PrimInt; + /// use num_traits::PrimInt; /// /// assert_eq!(2i32.pow(4), 16); /// ``` From 2a67a5b86e3dc34193a3c414d95f00accf580e3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 11 Mar 2016 00:42:46 +0100 Subject: [PATCH 06/31] Extract num-rational --- src/rational.rs | 1013 ----------------------------------------------- 1 file changed, 1013 deletions(-) delete mode 100644 src/rational.rs diff --git a/src/rational.rs b/src/rational.rs deleted file mode 100644 index 5778839..0000000 --- a/src/rational.rs +++ /dev/null @@ -1,1013 +0,0 @@ -// Copyright 2013-2014 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. - -//! Rational numbers - -use Integer; - -use std::cmp; -use std::error::Error; -use std::fmt; -use std::ops::{Add, Div, Mul, Neg, Rem, Sub}; -use std::str::FromStr; - -#[cfg(feature = "serde")] -use serde; - -#[cfg(feature = "bigint")] -use bigint::{BigInt, BigUint, Sign}; -use traits::{FromPrimitive, Float, PrimInt}; -use {Num, Signed, Zero, One}; - -/// Represents the ratio between 2 numbers. -#[derive(Copy, Clone, Hash, Debug)] -#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] -#[allow(missing_docs)] -pub struct Ratio { - numer: T, - denom: T -} - -/// Alias for a `Ratio` of machine-sized integers. -pub type Rational = Ratio; -pub type Rational32 = Ratio; -pub type Rational64 = Ratio; - -#[cfg(feature = "bigint")] -/// Alias for arbitrary precision rationals. -pub type BigRational = Ratio; - -impl Ratio { - /// Creates a ratio representing the integer `t`. - #[inline] - pub fn from_integer(t: T) -> Ratio { - Ratio::new_raw(t, One::one()) - } - - /// Creates a ratio without checking for `denom == 0` or reducing. - #[inline] - pub fn new_raw(numer: T, denom: T) -> Ratio { - Ratio { numer: numer, denom: denom } - } - - /// Create a new Ratio. Fails if `denom == 0`. - #[inline] - pub fn new(numer: T, denom: T) -> Ratio { - if denom == Zero::zero() { - panic!("denominator == 0"); - } - let mut ret = Ratio::new_raw(numer, denom); - ret.reduce(); - ret - } - - /// Converts to an integer. - #[inline] - pub fn to_integer(&self) -> T { - self.trunc().numer - } - - /// Gets an immutable reference to the numerator. - #[inline] - pub fn numer<'a>(&'a self) -> &'a T { - &self.numer - } - - /// Gets an immutable reference to the denominator. - #[inline] - pub fn denom<'a>(&'a self) -> &'a T { - &self.denom - } - - /// Returns true if the rational number is an integer (denominator is 1). - #[inline] - pub fn is_integer(&self) -> bool { - self.denom == One::one() - } - - /// Put self into lowest terms, with denom > 0. - fn reduce(&mut self) { - let g : T = self.numer.gcd(&self.denom); - - // FIXME(#5992): assignment operator overloads - // self.numer /= g; - self.numer = self.numer.clone() / g.clone(); - // FIXME(#5992): assignment operator overloads - // self.denom /= g; - self.denom = self.denom.clone() / g; - - // keep denom positive! - if self.denom < T::zero() { - self.numer = T::zero() - self.numer.clone(); - self.denom = T::zero() - self.denom.clone(); - } - } - - /// Returns a `reduce`d copy of self. - pub fn reduced(&self) -> Ratio { - let mut ret = self.clone(); - ret.reduce(); - ret - } - - /// Returns the reciprocal. - #[inline] - pub fn recip(&self) -> Ratio { - Ratio::new_raw(self.denom.clone(), self.numer.clone()) - } - - /// Rounds towards minus infinity. - #[inline] - pub fn floor(&self) -> Ratio { - if *self < Zero::zero() { - let one: T = One::one(); - Ratio::from_integer((self.numer.clone() - self.denom.clone() + one) / self.denom.clone()) - } else { - Ratio::from_integer(self.numer.clone() / self.denom.clone()) - } - } - - /// Rounds towards plus infinity. - #[inline] - pub fn ceil(&self) -> Ratio { - if *self < Zero::zero() { - Ratio::from_integer(self.numer.clone() / self.denom.clone()) - } else { - let one: T = One::one(); - Ratio::from_integer((self.numer.clone() + self.denom.clone() - one) / self.denom.clone()) - } - } - - /// Rounds to the nearest integer. Rounds half-way cases away from zero. - #[inline] - pub fn round(&self) -> Ratio { - let zero: Ratio = Zero::zero(); - let one: T = One::one(); - let two: T = one.clone() + one.clone(); - - // Find unsigned fractional part of rational number - let mut fractional = self.fract(); - if fractional < zero { fractional = zero - fractional }; - - // The algorithm compares the unsigned fractional part with 1/2, that - // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use - // a >= (b/2)+1. This avoids overflow issues. - let half_or_larger = if fractional.denom().is_even() { - *fractional.numer() >= fractional.denom().clone() / two.clone() - } else { - *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone() - }; - - if half_or_larger { - let one: Ratio = One::one(); - if *self >= Zero::zero() { - self.trunc() + one - } else { - self.trunc() - one - } - } else { - self.trunc() - } - } - - /// Rounds towards zero. - #[inline] - pub fn trunc(&self) -> Ratio { - Ratio::from_integer(self.numer.clone() / self.denom.clone()) - } - - /// Returns the fractional part of a number. - #[inline] - pub fn fract(&self) -> Ratio { - Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone()) - } -} - -impl Ratio { - /// Raises the ratio to the power of an exponent - #[inline] - pub fn pow(&self, expon: i32) -> Ratio { - match expon.cmp(&0) { - cmp::Ordering::Equal => One::one(), - cmp::Ordering::Less => self.recip().pow(-expon), - cmp::Ordering::Greater => Ratio::new_raw(self.numer.pow(expon as u32), - self.denom.pow(expon as u32)), - } - } -} - -#[cfg(feature = "bigint")] -impl Ratio { - /// Converts a float into a rational number. - pub fn from_float(f: T) -> Option { - if !f.is_finite() { - return None; - } - let (mantissa, exponent, sign) = f.integer_decode(); - let bigint_sign = if sign == 1 { Sign::Plus } else { Sign::Minus }; - if exponent < 0 { - let one: BigInt = One::one(); - let denom: BigInt = one << ((-exponent) as usize); - let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); - Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom)) - } else { - let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); - numer = numer << (exponent as usize); - Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer))) - } - } -} - -/* Comparisons */ - -// Mathematically, comparing a/b and c/d is the same as comparing a*d and b*c, but it's very easy -// for those multiplications to overflow fixed-size integers, so we need to take care. - -impl Ord for Ratio { - #[inline] - fn cmp(&self, other: &Self) -> cmp::Ordering { - // With equal denominators, the numerators can be directly compared - if self.denom == other.denom { - let ord = self.numer.cmp(&other.numer); - return if self.denom < T::zero() { ord.reverse() } else { ord }; - } - - // With equal numerators, the denominators can be inversely compared - if self.numer == other.numer { - let ord = self.denom.cmp(&other.denom); - return if self.numer < T::zero() { ord } else { ord.reverse() }; - } - - // Unfortunately, we don't have CheckedMul to try. That could sometimes avoid all the - // division below, or even always avoid it for BigInt and BigUint. - // FIXME- future breaking change to add Checked* to Integer? - - // Compare as floored integers and remainders - let (self_int, self_rem) = self.numer.div_mod_floor(&self.denom); - let (other_int, other_rem) = other.numer.div_mod_floor(&other.denom); - match self_int.cmp(&other_int) { - cmp::Ordering::Greater => cmp::Ordering::Greater, - cmp::Ordering::Less => cmp::Ordering::Less, - cmp::Ordering::Equal => { - match (self_rem.is_zero(), other_rem.is_zero()) { - (true, true) => cmp::Ordering::Equal, - (true, false) => cmp::Ordering::Less, - (false, true) => cmp::Ordering::Greater, - (false, false) => { - // Compare the reciprocals of the remaining fractions in reverse - let self_recip = Ratio::new_raw(self.denom.clone(), self_rem); - let other_recip = Ratio::new_raw(other.denom.clone(), other_rem); - self_recip.cmp(&other_recip).reverse() - } - } - }, - } - } -} - -impl PartialOrd for Ratio { - #[inline] - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl PartialEq for Ratio { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.cmp(other) == cmp::Ordering::Equal - } -} - -impl Eq for Ratio {} - - -macro_rules! forward_val_val_binop { - (impl $imp:ident, $method:ident) => { - impl $imp> for Ratio { - type Output = Ratio; - - #[inline] - fn $method(self, other: Ratio) -> Ratio { - (&self).$method(&other) - } - } - } -} - -macro_rules! forward_ref_val_binop { - (impl $imp:ident, $method:ident) => { - impl<'a, T> $imp> for &'a Ratio where - T: Clone + Integer - { - type Output = Ratio; - - #[inline] - fn $method(self, other: Ratio) -> Ratio { - self.$method(&other) - } - } - } -} - -macro_rules! forward_val_ref_binop { - (impl $imp:ident, $method:ident) => { - impl<'a, T> $imp<&'a Ratio> for Ratio where - T: Clone + Integer - { - type Output = Ratio; - - #[inline] - fn $method(self, other: &Ratio) -> Ratio { - (&self).$method(other) - } - } - } -} - -macro_rules! forward_all_binop { - (impl $imp:ident, $method:ident) => { - forward_val_val_binop!(impl $imp, $method); - forward_ref_val_binop!(impl $imp, $method); - forward_val_ref_binop!(impl $imp, $method); - }; -} - -/* Arithmetic */ -forward_all_binop!(impl Mul, mul); -// a/b * c/d = (a*c)/(b*d) -impl<'a, 'b, T> Mul<&'b Ratio> for &'a Ratio - where T: Clone + Integer -{ - - type Output = Ratio; - #[inline] - fn mul(self, rhs: &Ratio) -> Ratio { - Ratio::new(self.numer.clone() * rhs.numer.clone(), self.denom.clone() * rhs.denom.clone()) - } -} - -forward_all_binop!(impl Div, div); -// (a/b) / (c/d) = (a*d)/(b*c) -impl<'a, 'b, T> Div<&'b Ratio> for &'a Ratio - where T: Clone + Integer -{ - type Output = Ratio; - - #[inline] - fn div(self, rhs: &Ratio) -> Ratio { - Ratio::new(self.numer.clone() * rhs.denom.clone(), self.denom.clone() * rhs.numer.clone()) - } -} - -// Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern -macro_rules! arith_impl { - (impl $imp:ident, $method:ident) => { - forward_all_binop!(impl $imp, $method); - impl<'a, 'b, T: Clone + Integer> - $imp<&'b Ratio> for &'a Ratio { - type Output = Ratio; - #[inline] - fn $method(self, rhs: &Ratio) -> Ratio { - Ratio::new((self.numer.clone() * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer.clone()), - self.denom.clone() * rhs.denom.clone()) - } - } - } -} - -// a/b + c/d = (a*d + b*c)/(b*d) -arith_impl!(impl Add, add); - -// a/b - c/d = (a*d - b*c)/(b*d) -arith_impl!(impl Sub, sub); - -// a/b % c/d = (a*d % b*c)/(b*d) -arith_impl!(impl Rem, rem); - -impl Neg for Ratio - where T: Clone + Integer + Neg -{ - type Output = Ratio; - - #[inline] - fn neg(self) -> Ratio { - Ratio::new_raw(-self.numer, self.denom) - } -} - -impl<'a, T> Neg for &'a Ratio - where T: Clone + Integer + Neg -{ - type Output = Ratio; - - #[inline] - fn neg(self) -> Ratio { - -self.clone() - } -} - -/* Constants */ -impl - Zero for Ratio { - #[inline] - fn zero() -> Ratio { - Ratio::new_raw(Zero::zero(), One::one()) - } - - #[inline] - fn is_zero(&self) -> bool { - self.numer.is_zero() - } -} - -impl - One for Ratio { - #[inline] - fn one() -> Ratio { - Ratio::new_raw(One::one(), One::one()) - } -} - -impl Num for Ratio { - type FromStrRadixErr = ParseRatioError; - - /// Parses `numer/denom` where the numbers are in base `radix`. - fn from_str_radix(s: &str, radix: u32) -> Result, ParseRatioError> { - let split: Vec<&str> = s.splitn(2, '/').collect(); - if split.len() < 2 { - Err(ParseRatioError{kind: RatioErrorKind::ParseError}) - } else { - let a_result: Result = T::from_str_radix( - split[0], - radix).map_err(|_| ParseRatioError{kind: RatioErrorKind::ParseError}); - a_result.and_then(|a| { - let b_result: Result = - T::from_str_radix(split[1], radix).map_err( - |_| ParseRatioError{kind: RatioErrorKind::ParseError}); - b_result.and_then(|b| if b.is_zero() { - Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator}) - } else { - Ok(Ratio::new(a.clone(), b.clone())) - }) - }) - } - } -} - -impl Signed for Ratio { - #[inline] - fn abs(&self) -> Ratio { - if self.is_negative() { -self.clone() } else { self.clone() } - } - - #[inline] - fn abs_sub(&self, other: &Ratio) -> Ratio { - if *self <= *other { Zero::zero() } else { self - other } - } - - #[inline] - fn signum(&self) -> Ratio { - if self.is_positive() { - Self::one() - } else if self.is_zero() { - Self::zero() - } else { - - Self::one() - } - } - - #[inline] - fn is_positive(&self) -> bool { !self.is_negative() } - - #[inline] - fn is_negative(&self) -> bool { - self.numer.is_negative() ^ self.denom.is_negative() - } -} - -/* String conversions */ -impl fmt::Display for Ratio where - T: fmt::Display + Eq + One -{ - /// Renders as `numer/denom`. If denom=1, renders as numer. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.denom == One::one() { - write!(f, "{}", self.numer) - } else { - write!(f, "{}/{}", self.numer, self.denom) - } - } -} - -impl FromStr for Ratio { - type Err = ParseRatioError; - - /// Parses `numer/denom` or just `numer`. - fn from_str(s: &str) -> Result, ParseRatioError> { - let mut split = s.splitn(2, '/'); - - let n = try!(split.next().ok_or( - ParseRatioError{kind: RatioErrorKind::ParseError})); - let num = try!(FromStr::from_str(n).map_err( - |_| ParseRatioError{kind: RatioErrorKind::ParseError})); - - let d = split.next().unwrap_or("1"); - let den = try!(FromStr::from_str(d).map_err( - |_| ParseRatioError{kind: RatioErrorKind::ParseError})); - - if Zero::is_zero(&den) { - Err(ParseRatioError{kind: RatioErrorKind::ZeroDenominator}) - } else { - Ok(Ratio::new(num, den)) - } - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for Ratio - where T: serde::Serialize + Clone + Integer + PartialOrd -{ - fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where - S: serde::Serializer - { - (self.numer(), self.denom()).serialize(serializer) - } -} - -#[cfg(feature = "serde")] -impl serde::Deserialize for Ratio - where T: serde::Deserialize + Clone + Integer + PartialOrd -{ - fn deserialize(deserializer: &mut D) -> Result where - D: serde::Deserializer, - { - let (numer, denom) = try!(serde::Deserialize::deserialize(deserializer)); - if denom == Zero::zero() { - Err(serde::de::Error::invalid_value("denominator is zero")) - } else { - Ok(Ratio::new_raw(numer, denom)) - } - } -} - -// FIXME: Bubble up specific errors -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct ParseRatioError { kind: RatioErrorKind } - -#[derive(Copy, Clone, Debug, PartialEq)] -enum RatioErrorKind { - ParseError, - ZeroDenominator, -} - -impl fmt::Display for ParseRatioError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.description().fmt(f) - } -} - -impl Error for ParseRatioError { - fn description(&self) -> &str { self.kind.description() } -} - -impl RatioErrorKind { - fn description(&self) -> &'static str { - match *self { - RatioErrorKind::ParseError => "failed to parse integer", - RatioErrorKind::ZeroDenominator => "zero value denominator", - } - } -} - -#[cfg(test)] -mod test { - - use super::{Ratio, Rational}; - #[cfg(feature = "bigint")] - use super::BigRational; - use std::str::FromStr; - use std::i32; - use {Zero, One, Signed, FromPrimitive, Float}; - - pub const _0 : Rational = Ratio { numer: 0, denom: 1}; - pub const _1 : Rational = Ratio { numer: 1, denom: 1}; - pub const _2: Rational = Ratio { numer: 2, denom: 1}; - pub const _1_2: Rational = Ratio { numer: 1, denom: 2}; - pub const _3_2: Rational = Ratio { numer: 3, denom: 2}; - pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2}; - pub const _1_3: Rational = Ratio { numer: 1, denom: 3}; - pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3}; - pub const _2_3: Rational = Ratio { numer: 2, denom: 3}; - pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3}; - - #[cfg(feature = "bigint")] - pub fn to_big(n: Rational) -> BigRational { - Ratio::new( - FromPrimitive::from_isize(n.numer).unwrap(), - FromPrimitive::from_isize(n.denom).unwrap() - ) - } - #[cfg(not(feature = "bigint"))] - pub fn to_big(n: Rational) -> Rational { - Ratio::new( - FromPrimitive::from_isize(n.numer).unwrap(), - FromPrimitive::from_isize(n.denom).unwrap() - ) - } - - #[test] - fn test_test_constants() { - // check our constants are what Ratio::new etc. would make. - assert_eq!(_0, Zero::zero()); - assert_eq!(_1, One::one()); - assert_eq!(_2, Ratio::from_integer(2)); - assert_eq!(_1_2, Ratio::new(1,2)); - assert_eq!(_3_2, Ratio::new(3,2)); - assert_eq!(_NEG1_2, Ratio::new(-1,2)); - } - - #[test] - fn test_new_reduce() { - let one22 = Ratio::new(2,2); - - assert_eq!(one22, One::one()); - } - #[test] - #[should_panic] - fn test_new_zero() { - let _a = Ratio::new(1,0); - } - - - #[test] - fn test_cmp() { - assert!(_0 == _0 && _1 == _1); - assert!(_0 != _1 && _1 != _0); - assert!(_0 < _1 && !(_1 < _0)); - assert!(_1 > _0 && !(_0 > _1)); - - assert!(_0 <= _0 && _1 <= _1); - assert!(_0 <= _1 && !(_1 <= _0)); - - assert!(_0 >= _0 && _1 >= _1); - assert!(_1 >= _0 && !(_0 >= _1)); - } - - #[test] - fn test_cmp_overflow() { - use std::cmp::Ordering; - - // issue #7 example: - let big = Ratio::new(128u8, 1); - let small = big.recip(); - assert!(big > small); - - // try a few that are closer together - // (some matching numer, some matching denom, some neither) - let ratios = vec![ - Ratio::new(125_i8, 127_i8), - Ratio::new(63_i8, 64_i8), - Ratio::new(124_i8, 125_i8), - Ratio::new(125_i8, 126_i8), - Ratio::new(126_i8, 127_i8), - Ratio::new(127_i8, 126_i8), - ]; - - fn check_cmp(a: Ratio, b: Ratio, ord: Ordering) { - println!("comparing {} and {}", a, b); - assert_eq!(a.cmp(&b), ord); - assert_eq!(b.cmp(&a), ord.reverse()); - } - - for (i, &a) in ratios.iter().enumerate() { - check_cmp(a, a, Ordering::Equal); - check_cmp(-a, a, Ordering::Less); - for &b in &ratios[i+1..] { - check_cmp(a, b, Ordering::Less); - check_cmp(-a, -b, Ordering::Greater); - check_cmp(a.recip(), b.recip(), Ordering::Greater); - check_cmp(-a.recip(), -b.recip(), Ordering::Less); - } - } - } - - #[test] - fn test_to_integer() { - assert_eq!(_0.to_integer(), 0); - assert_eq!(_1.to_integer(), 1); - assert_eq!(_2.to_integer(), 2); - assert_eq!(_1_2.to_integer(), 0); - assert_eq!(_3_2.to_integer(), 1); - assert_eq!(_NEG1_2.to_integer(), 0); - } - - - #[test] - fn test_numer() { - assert_eq!(_0.numer(), &0); - assert_eq!(_1.numer(), &1); - assert_eq!(_2.numer(), &2); - assert_eq!(_1_2.numer(), &1); - assert_eq!(_3_2.numer(), &3); - assert_eq!(_NEG1_2.numer(), &(-1)); - } - #[test] - fn test_denom() { - assert_eq!(_0.denom(), &1); - assert_eq!(_1.denom(), &1); - assert_eq!(_2.denom(), &1); - assert_eq!(_1_2.denom(), &2); - assert_eq!(_3_2.denom(), &2); - assert_eq!(_NEG1_2.denom(), &2); - } - - - #[test] - fn test_is_integer() { - assert!(_0.is_integer()); - assert!(_1.is_integer()); - assert!(_2.is_integer()); - assert!(!_1_2.is_integer()); - assert!(!_3_2.is_integer()); - assert!(!_NEG1_2.is_integer()); - } - - #[test] - fn test_show() { - assert_eq!(format!("{}", _2), "2".to_string()); - assert_eq!(format!("{}", _1_2), "1/2".to_string()); - assert_eq!(format!("{}", _0), "0".to_string()); - assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string()); - } - - mod arith { - use super::{_0, _1, _2, _1_2, _3_2, _NEG1_2, to_big}; - use super::super::{Ratio, Rational}; - - #[test] - fn test_add() { - fn test(a: Rational, b: Rational, c: Rational) { - assert_eq!(a + b, c); - assert_eq!(to_big(a) + to_big(b), to_big(c)); - } - - test(_1, _1_2, _3_2); - test(_1, _1, _2); - test(_1_2, _3_2, _2); - test(_1_2, _NEG1_2, _0); - } - - #[test] - fn test_sub() { - fn test(a: Rational, b: Rational, c: Rational) { - assert_eq!(a - b, c); - assert_eq!(to_big(a) - to_big(b), to_big(c)) - } - - test(_1, _1_2, _1_2); - test(_3_2, _1_2, _1); - test(_1, _NEG1_2, _3_2); - } - - #[test] - fn test_mul() { - fn test(a: Rational, b: Rational, c: Rational) { - assert_eq!(a * b, c); - assert_eq!(to_big(a) * to_big(b), to_big(c)) - } - - test(_1, _1_2, _1_2); - test(_1_2, _3_2, Ratio::new(3,4)); - test(_1_2, _NEG1_2, Ratio::new(-1, 4)); - } - - #[test] - fn test_div() { - fn test(a: Rational, b: Rational, c: Rational) { - assert_eq!(a / b, c); - assert_eq!(to_big(a) / to_big(b), to_big(c)) - } - - test(_1, _1_2, _2); - test(_3_2, _1_2, _1 + _2); - test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2); - } - - #[test] - fn test_rem() { - fn test(a: Rational, b: Rational, c: Rational) { - assert_eq!(a % b, c); - assert_eq!(to_big(a) % to_big(b), to_big(c)) - } - - test(_3_2, _1, _1_2); - test(_2, _NEG1_2, _0); - test(_1_2, _2, _1_2); - } - - #[test] - fn test_neg() { - fn test(a: Rational, b: Rational) { - assert_eq!(-a, b); - assert_eq!(-to_big(a), to_big(b)) - } - - test(_0, _0); - test(_1_2, _NEG1_2); - test(-_1, _1); - } - #[test] - fn test_zero() { - assert_eq!(_0 + _0, _0); - assert_eq!(_0 * _0, _0); - assert_eq!(_0 * _1, _0); - assert_eq!(_0 / _NEG1_2, _0); - assert_eq!(_0 - _0, _0); - } - #[test] - #[should_panic] - fn test_div_0() { - let _a = _1 / _0; - } - } - - #[test] - fn test_round() { - assert_eq!(_1_3.ceil(), _1); - assert_eq!(_1_3.floor(), _0); - assert_eq!(_1_3.round(), _0); - assert_eq!(_1_3.trunc(), _0); - - assert_eq!(_NEG1_3.ceil(), _0); - assert_eq!(_NEG1_3.floor(), -_1); - assert_eq!(_NEG1_3.round(), _0); - assert_eq!(_NEG1_3.trunc(), _0); - - assert_eq!(_2_3.ceil(), _1); - assert_eq!(_2_3.floor(), _0); - assert_eq!(_2_3.round(), _1); - assert_eq!(_2_3.trunc(), _0); - - assert_eq!(_NEG2_3.ceil(), _0); - assert_eq!(_NEG2_3.floor(), -_1); - assert_eq!(_NEG2_3.round(), -_1); - assert_eq!(_NEG2_3.trunc(), _0); - - assert_eq!(_1_2.ceil(), _1); - assert_eq!(_1_2.floor(), _0); - assert_eq!(_1_2.round(), _1); - assert_eq!(_1_2.trunc(), _0); - - assert_eq!(_NEG1_2.ceil(), _0); - assert_eq!(_NEG1_2.floor(), -_1); - assert_eq!(_NEG1_2.round(), -_1); - assert_eq!(_NEG1_2.trunc(), _0); - - assert_eq!(_1.ceil(), _1); - assert_eq!(_1.floor(), _1); - assert_eq!(_1.round(), _1); - assert_eq!(_1.trunc(), _1); - - // Overflow checks - - let _neg1 = Ratio::from_integer(-1); - let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1); - let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX); - let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1); - let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2); - let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX); - let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2); - let _large_rat7 = Ratio::new(1, i32::MIN+1); - let _large_rat8 = Ratio::new(1, i32::MAX); - - assert_eq!(_large_rat1.round(), One::one()); - assert_eq!(_large_rat2.round(), One::one()); - assert_eq!(_large_rat3.round(), One::one()); - assert_eq!(_large_rat4.round(), One::one()); - assert_eq!(_large_rat5.round(), _neg1); - assert_eq!(_large_rat6.round(), _neg1); - assert_eq!(_large_rat7.round(), Zero::zero()); - assert_eq!(_large_rat8.round(), Zero::zero()); - } - - #[test] - fn test_fract() { - assert_eq!(_1.fract(), _0); - assert_eq!(_NEG1_2.fract(), _NEG1_2); - assert_eq!(_1_2.fract(), _1_2); - assert_eq!(_3_2.fract(), _1_2); - } - - #[test] - fn test_recip() { - assert_eq!(_1 * _1.recip(), _1); - assert_eq!(_2 * _2.recip(), _1); - assert_eq!(_1_2 * _1_2.recip(), _1); - assert_eq!(_3_2 * _3_2.recip(), _1); - assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1); - } - - #[test] - fn test_pow() { - assert_eq!(_1_2.pow(2), Ratio::new(1, 4)); - assert_eq!(_1_2.pow(-2), Ratio::new(4, 1)); - assert_eq!(_1.pow(1), _1); - assert_eq!(_NEG1_2.pow(2), _1_2.pow(2)); - assert_eq!(_NEG1_2.pow(3), -_1_2.pow(3)); - assert_eq!(_3_2.pow(0), _1); - assert_eq!(_3_2.pow(-1), _3_2.recip()); - assert_eq!(_3_2.pow(3), Ratio::new(27, 8)); - } - - #[test] - fn test_to_from_str() { - fn test(r: Rational, s: String) { - assert_eq!(FromStr::from_str(&s), Ok(r)); - assert_eq!(r.to_string(), s); - } - test(_1, "1".to_string()); - test(_0, "0".to_string()); - test(_1_2, "1/2".to_string()); - test(_3_2, "3/2".to_string()); - test(_2, "2".to_string()); - test(_NEG1_2, "-1/2".to_string()); - } - #[test] - fn test_from_str_fail() { - fn test(s: &str) { - let rational: Result = FromStr::from_str(s); - assert!(rational.is_err()); - } - - let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "1/0"]; - for &s in xs.iter() { - test(s); - } - } - - #[cfg(feature = "bigint")] - #[test] - fn test_from_float() { - fn test(given: T, (numer, denom): (&str, &str)) { - let ratio: BigRational = Ratio::from_float(given).unwrap(); - assert_eq!(ratio, Ratio::new( - FromStr::from_str(numer).unwrap(), - FromStr::from_str(denom).unwrap())); - } - - // f32 - test(3.14159265359f32, ("13176795", "4194304")); - test(2f32.powf(100.), ("1267650600228229401496703205376", "1")); - test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1")); - test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376")); - test(684729.48391f32, ("1369459", "2")); - test(-8573.5918555f32, ("-4389679", "512")); - - // f64 - test(3.14159265359f64, ("3537118876014453", "1125899906842624")); - test(2f64.powf(100.), ("1267650600228229401496703205376", "1")); - test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1")); - test(684729.48391f64, ("367611342500051", "536870912")); - test(-8573.5918555f64, ("-4713381968463931", "549755813888")); - test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376")); - } - - #[cfg(feature = "bigint")] - #[test] - fn test_from_float_fail() { - use std::{f32, f64}; - - assert_eq!(Ratio::from_float(f32::NAN), None); - assert_eq!(Ratio::from_float(f32::INFINITY), None); - assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None); - assert_eq!(Ratio::from_float(f64::NAN), None); - assert_eq!(Ratio::from_float(f64::INFINITY), None); - assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None); - } - - #[test] - fn test_signed() { - assert_eq!(_NEG1_2.abs(), _1_2); - assert_eq!(_3_2.abs_sub(&_1_2), _1); - assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero()); - assert_eq!(_1_2.signum(), One::one()); - assert_eq!(_NEG1_2.signum(), - ::one::>()); - assert!(_NEG1_2.is_negative()); - assert!(! _NEG1_2.is_positive()); - assert!(! _1_2.is_negative()); - } - - #[test] - fn test_hash() { - assert!(::hash(&_0) != ::hash(&_1)); - assert!(::hash(&_0) != ::hash(&_3_2)); - } -} From ed076070e69ec8c79657b6c7332ebb1521aa1b7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 11 Mar 2016 00:55:53 +0100 Subject: [PATCH 07/31] Extract complex --- Cargo.toml | 4 ++++ complex/Cargo.toml | 10 ++++++++++ src/complex.rs => complex/src/lib.rs | 5 +++-- src/lib.rs | 4 +++- 4 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 complex/Cargo.toml rename src/complex.rs => complex/src/lib.rs (99%) diff --git a/Cargo.toml b/Cargo.toml index d833beb..dc89349 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,10 @@ name = "shootout-pidigits" optional = true path = "bigint" +[dependencies.num-complex] +optional = false +path = "complex" + [dependencies.num-integer] path = "./integer" diff --git a/complex/Cargo.toml b/complex/Cargo.toml new file mode 100644 index 0000000..3c719fb --- /dev/null +++ b/complex/Cargo.toml @@ -0,0 +1,10 @@ +[package] +authors = ["Łukasz Jan Niemier "] +name = "num-complex" +version = "0.1.0" + +[dependencies] + +[dependencies.num-traits] +optional = false +path = "../traits" diff --git a/src/complex.rs b/complex/src/lib.rs similarity index 99% rename from src/complex.rs rename to complex/src/lib.rs index 8f8cfae..854fb34 100644 --- a/src/complex.rs +++ b/complex/src/lib.rs @@ -8,16 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - //! Complex numbers. +extern crate num_traits as traits; + use std::fmt; use std::ops::{Add, Div, Mul, Neg, Sub}; #[cfg(feature = "serde")] use serde; -use {Zero, One, Num, Float}; +use traits::{Zero, One, Num, Float}; // FIXME #1284: handle complex NaN & infinity etc. This // probably doesn't map to C's _Complex correctly. diff --git a/src/lib.rs b/src/lib.rs index 4fce75d..36723ee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,8 @@ extern crate num_traits; extern crate num_integer; +#[cfg(feature = "complex")] +extern crate num_complex; #[cfg(feature = "num-bigint")] extern crate num_bigint; #[cfg(feature = "num-rational")] @@ -96,7 +98,7 @@ use std::ops::{Mul}; #[cfg(feature = "num-bigint")] pub use num_bigint as bigint; -pub mod complex; +pub use num_complex as complex; pub use num_integer as integers; pub mod iter; pub use num_traits as traits; From 96e9166b0a31f4be5f5dabbebcd2a4cc278ffaab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 11 Mar 2016 01:05:40 +0100 Subject: [PATCH 08/31] Extract iter --- Cargo.toml | 10 +- iter/Cargo.toml | 14 ++ iter/src/lib.rs | 376 ++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 19 +-- traits/src/lib.rs | 14 +- 5 files changed, 414 insertions(+), 19 deletions(-) create mode 100644 iter/Cargo.toml create mode 100644 iter/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index dc89349..5ef3ccd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,12 +23,16 @@ optional = true path = "bigint" [dependencies.num-complex] -optional = false +optional = true path = "complex" [dependencies.num-integer] path = "./integer" +[dependencies.num-iter] +optional = false +path = "iter" + [dependencies.num-rational] optional = true path = "rational" @@ -55,6 +59,6 @@ version = "0.3.8" [features] bigint = ["num-bigint"] -complex = [] -default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] +complex = ["num-complex"] rational = ["num-rational"] +default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] diff --git a/iter/Cargo.toml b/iter/Cargo.toml new file mode 100644 index 0000000..0c69411 --- /dev/null +++ b/iter/Cargo.toml @@ -0,0 +1,14 @@ +[package] +authors = ["Łukasz Jan Niemier "] +name = "num-iter" +version = "0.1.0" + +[dependencies] + +[dependencies.num-integer] +optional = false +path = "../integer" + +[dependencies.num-traits] +optional = false +path = "../traits" diff --git a/iter/src/lib.rs b/iter/src/lib.rs new file mode 100644 index 0000000..8f567d7 --- /dev/null +++ b/iter/src/lib.rs @@ -0,0 +1,376 @@ +// Copyright 2013-2014 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. + +//! External iterators for generic mathematics + +extern crate num_traits as traits; +extern crate num_integer as integer; + +use integer::Integer; +use traits::{Zero, One, CheckedAdd, ToPrimitive}; +use std::ops::{Add, Sub}; + +/// An iterator over the range [start, stop) +#[derive(Clone)] +pub struct Range { + state: A, + stop: A, + one: A +} + +/// Returns an iterator over the given range [start, stop) (that is, starting +/// at start (inclusive), and ending at stop (exclusive)). +/// +/// # Example +/// +/// ```rust +/// use num::iter; +/// +/// let array = [0, 1, 2, 3, 4]; +/// +/// for i in iter::range(0, 5) { +/// println!("{}", i); +/// assert_eq!(i, array[i]); +/// } +/// ``` +#[inline] +pub fn range(start: A, stop: A) -> Range + where A: Add + PartialOrd + Clone + One +{ + Range{state: start, stop: stop, one: One::one()} +} + +// FIXME: rust-lang/rust#10414: Unfortunate type bound +impl Iterator for Range + where A: Add + PartialOrd + Clone + ToPrimitive +{ + type Item = A; + + #[inline] + fn next(&mut self) -> Option { + if self.state < self.stop { + let result = self.state.clone(); + self.state = self.state.clone() + self.one.clone(); + Some(result) + } else { + None + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + // This first checks if the elements are representable as i64. If they aren't, try u64 (to + // handle cases like range(huge, huger)). We don't use usize/int because the difference of + // the i64/u64 might lie within their range. + let bound = match self.state.to_i64() { + Some(a) => { + let sz = self.stop.to_i64().map(|b| b.checked_sub(a)); + match sz { + Some(Some(bound)) => bound.to_usize(), + _ => None, + } + }, + None => match self.state.to_u64() { + Some(a) => { + let sz = self.stop.to_u64().map(|b| b.checked_sub(a)); + match sz { + Some(Some(bound)) => bound.to_usize(), + _ => None + } + }, + None => None + } + }; + + match bound { + Some(b) => (b, Some(b)), + // Standard fallback for unbounded/unrepresentable bounds + None => (0, None) + } + } +} + +/// `Integer` is required to ensure the range will be the same regardless of +/// the direction it is consumed. +impl DoubleEndedIterator for Range + where A: Integer + Clone + ToPrimitive +{ + #[inline] + fn next_back(&mut self) -> Option { + if self.stop > self.state { + self.stop = self.stop.clone() - self.one.clone(); + Some(self.stop.clone()) + } else { + None + } + } +} + +/// An iterator over the range [start, stop] +#[derive(Clone)] +pub struct RangeInclusive { + range: Range, + done: bool, +} + +/// Return an iterator over the range [start, stop] +#[inline] +pub fn range_inclusive(start: A, stop: A) -> RangeInclusive + where A: Add + PartialOrd + Clone + One +{ + RangeInclusive{range: range(start, stop), done: false} +} + +impl Iterator for RangeInclusive + where A: Add + PartialOrd + Clone + ToPrimitive +{ + type Item = A; + + #[inline] + fn next(&mut self) -> Option { + match self.range.next() { + Some(x) => Some(x), + None => { + if !self.done && self.range.state == self.range.stop { + self.done = true; + Some(self.range.stop.clone()) + } else { + None + } + } + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + let (lo, hi) = self.range.size_hint(); + if self.done { + (lo, hi) + } else { + let lo = lo.saturating_add(1); + let hi = match hi { + Some(x) => x.checked_add(1), + None => None + }; + (lo, hi) + } + } +} + +impl DoubleEndedIterator for RangeInclusive + where A: Sub + Integer + Clone + ToPrimitive +{ + #[inline] + fn next_back(&mut self) -> Option { + if self.range.stop > self.range.state { + let result = self.range.stop.clone(); + self.range.stop = self.range.stop.clone() - self.range.one.clone(); + Some(result) + } else if !self.done && self.range.state == self.range.stop { + self.done = true; + Some(self.range.stop.clone()) + } else { + None + } + } +} + +/// An iterator over the range [start, stop) by `step`. It handles overflow by stopping. +#[derive(Clone)] +pub struct RangeStep { + state: A, + stop: A, + step: A, + rev: bool, +} + +/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping. +#[inline] +pub fn range_step(start: A, stop: A, step: A) -> RangeStep + where A: CheckedAdd + PartialOrd + Clone + Zero +{ + let rev = step < Zero::zero(); + RangeStep{state: start, stop: stop, step: step, rev: rev} +} + +impl Iterator for RangeStep + where A: CheckedAdd + PartialOrd + Clone +{ + type Item = A; + + #[inline] + fn next(&mut self) -> Option { + if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) { + let result = self.state.clone(); + match self.state.checked_add(&self.step) { + Some(x) => self.state = x, + None => self.state = self.stop.clone() + } + Some(result) + } else { + None + } + } +} + +/// An iterator over the range [start, stop] by `step`. It handles overflow by stopping. +#[derive(Clone)] +pub struct RangeStepInclusive { + state: A, + stop: A, + step: A, + rev: bool, + done: bool, +} + +/// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping. +#[inline] +pub fn range_step_inclusive(start: A, stop: A, step: A) -> RangeStepInclusive + where A: CheckedAdd + PartialOrd + Clone + Zero +{ + let rev = step < Zero::zero(); + RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false} +} + +impl Iterator for RangeStepInclusive + where A: CheckedAdd + PartialOrd + Clone + PartialEq +{ + type Item = A; + + #[inline] + fn next(&mut self) -> Option { + if !self.done && ((self.rev && self.state >= self.stop) || + (!self.rev && self.state <= self.stop)) { + let result = self.state.clone(); + match self.state.checked_add(&self.step) { + Some(x) => self.state = x, + None => self.done = true + } + Some(result) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use std::usize; + use std::ops::{Add, Mul}; + use std::cmp::Ordering; + use {One, ToPrimitive}; + + #[test] + fn test_range() { + /// A mock type to check Range when ToPrimitive returns None + struct Foo; + + impl ToPrimitive for Foo { + fn to_i64(&self) -> Option { None } + fn to_u64(&self) -> Option { None } + } + + impl Add for Foo { + type Output = Foo; + + fn add(self, _: Foo) -> Foo { + Foo + } + } + + impl PartialEq for Foo { + fn eq(&self, _: &Foo) -> bool { + true + } + } + + impl PartialOrd for Foo { + fn partial_cmp(&self, _: &Foo) -> Option { + None + } + } + + impl Clone for Foo { + fn clone(&self) -> Foo { + Foo + } + } + + impl Mul for Foo { + type Output = Foo; + + fn mul(self, _: Foo) -> Foo { + Foo + } + } + + impl One for Foo { + fn one() -> Foo { + Foo + } + } + + assert!(super::range(0, 5).collect::>() == vec![0, 1, 2, 3, 4]); + assert!(super::range(-10, -1).collect::>() == + vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); + assert!(super::range(0, 5).rev().collect::>() == vec![4, 3, 2, 1, 0]); + assert_eq!(super::range(200, -5).count(), 0); + assert_eq!(super::range(200, -5).rev().count(), 0); + assert_eq!(super::range(200, 200).count(), 0); + assert_eq!(super::range(200, 200).rev().count(), 0); + + assert_eq!(super::range(0, 100).size_hint(), (100, Some(100))); + // this test is only meaningful when sizeof usize < sizeof u64 + assert_eq!(super::range(usize::MAX - 1, usize::MAX).size_hint(), (1, Some(1))); + assert_eq!(super::range(-10, -1).size_hint(), (9, Some(9))); + } + + #[test] + fn test_range_inclusive() { + assert!(super::range_inclusive(0, 5).collect::>() == + vec![0, 1, 2, 3, 4, 5]); + assert!(super::range_inclusive(0, 5).rev().collect::>() == + vec![5, 4, 3, 2, 1, 0]); + assert_eq!(super::range_inclusive(200, -5).count(), 0); + assert_eq!(super::range_inclusive(200, -5).rev().count(), 0); + assert!(super::range_inclusive(200, 200).collect::>() == vec![200]); + assert!(super::range_inclusive(200, 200).rev().collect::>() == vec![200]); + } + + #[test] + fn test_range_step() { + assert!(super::range_step(0, 20, 5).collect::>() == + vec![0, 5, 10, 15]); + assert!(super::range_step(20, 0, -5).collect::>() == + vec![20, 15, 10, 5]); + assert!(super::range_step(20, 0, -6).collect::>() == + vec![20, 14, 8, 2]); + assert!(super::range_step(200u8, 255, 50).collect::>() == + vec![200u8, 250]); + assert!(super::range_step(200, -5, 1).collect::>() == vec![]); + assert!(super::range_step(200, 200, 1).collect::>() == vec![]); + } + + #[test] + fn test_range_step_inclusive() { + assert!(super::range_step_inclusive(0, 20, 5).collect::>() == + vec![0, 5, 10, 15, 20]); + assert!(super::range_step_inclusive(20, 0, -5).collect::>() == + vec![20, 15, 10, 5, 0]); + assert!(super::range_step_inclusive(20, 0, -6).collect::>() == + vec![20, 14, 8, 2]); + assert!(super::range_step_inclusive(200u8, 255, 50).collect::>() == + vec![200u8, 250]); + assert!(super::range_step_inclusive(200, -5, 1).collect::>() == + vec![]); + assert!(super::range_step_inclusive(200, 200, 1).collect::>() == + vec![200]); + } +} diff --git a/src/lib.rs b/src/lib.rs index 36723ee..4ba0ead 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,14 +57,15 @@ html_root_url = "http://rust-num.github.io/num/", html_playground_url = "http://play.rust-lang.org/")] -extern crate num_traits; -extern crate num_integer; -#[cfg(feature = "complex")] -extern crate num_complex; +pub extern crate num_traits; +pub extern crate num_integer; +pub extern crate num_iter; +#[cfg(feature = "num-complex")] +pub extern crate num_complex; #[cfg(feature = "num-bigint")] -extern crate num_bigint; +pub extern crate num_bigint; #[cfg(feature = "num-rational")] -extern crate num_rational; +pub extern crate num_rational; #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; @@ -84,7 +85,7 @@ pub use bigint::{BigInt, BigUint}; pub use rational::Rational; #[cfg(all(feature = "num-rational", feature="num-bigint"))] pub use rational::BigRational; -#[cfg(feature = "complex")] +#[cfg(feature = "num-complex")] pub use complex::Complex; pub use integer::Integer; pub use iter::{range, range_inclusive, range_step, range_step_inclusive}; @@ -99,8 +100,8 @@ use std::ops::{Mul}; #[cfg(feature = "num-bigint")] pub use num_bigint as bigint; pub use num_complex as complex; -pub use num_integer as integers; -pub mod iter; +pub use num_integer as integer; +pub use num_iter as iter; pub use num_traits as traits; #[cfg(feature = "num-rational")] pub use num_rational as rational; diff --git a/traits/src/lib.rs b/traits/src/lib.rs index c0dce24..869b92f 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -21,13 +21,13 @@ pub use sign::{Signed, Unsigned}; pub use int::PrimInt; pub use cast::*; -mod identities; -mod sign; -mod ops; -mod bounds; -mod float; -mod int; -mod cast; +pub mod identities; +pub mod sign; +pub mod ops; +pub mod bounds; +pub mod float; +pub mod int; +pub mod cast; /// The base trait for numeric types pub trait Num: PartialEq + Zero + One From 7c0ab30bdc53702209bc5feadf99a2a5e43ce57a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 11 Mar 2016 10:22:26 +0100 Subject: [PATCH 09/31] Fix subpackages metadata --- Cargo.toml | 2 +- bigint/Cargo.toml | 8 +++++++- complex/Cargo.toml | 8 +++++++- integer/Cargo.toml | 8 +++++++- iter/Cargo.toml | 8 +++++++- rational/Cargo.toml | 8 +++++++- traits/Cargo.toml | 8 +++++++- 7 files changed, 43 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5ef3ccd..e35c26c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,8 +5,8 @@ documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] license = "MIT/Apache-2.0" -name = "num" repository = "https://github.com/rust-num/num" +name = "num" version = "0.1.31" [[bench]] diff --git a/bigint/Cargo.toml b/bigint/Cargo.toml index 657e511..883fb50 100644 --- a/bigint/Cargo.toml +++ b/bigint/Cargo.toml @@ -1,5 +1,11 @@ [package] -authors = ["Łukasz Jan Niemier "] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-bigint" version = "0.1.0" diff --git a/complex/Cargo.toml b/complex/Cargo.toml index 3c719fb..3dc0a52 100644 --- a/complex/Cargo.toml +++ b/complex/Cargo.toml @@ -1,5 +1,11 @@ [package] -authors = ["Łukasz Jan Niemier "] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-complex" version = "0.1.0" diff --git a/integer/Cargo.toml b/integer/Cargo.toml index 29991b3..413a99b 100644 --- a/integer/Cargo.toml +++ b/integer/Cargo.toml @@ -1,7 +1,13 @@ [package] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-integer" version = "0.1.0" -authors = ["Łukasz Jan Niemier "] [dependencies.num-traits] path = "../traits" diff --git a/iter/Cargo.toml b/iter/Cargo.toml index 0c69411..e36b457 100644 --- a/iter/Cargo.toml +++ b/iter/Cargo.toml @@ -1,5 +1,11 @@ [package] -authors = ["Łukasz Jan Niemier "] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-iter" version = "0.1.0" diff --git a/rational/Cargo.toml b/rational/Cargo.toml index 5524742..10b51f8 100644 --- a/rational/Cargo.toml +++ b/rational/Cargo.toml @@ -1,5 +1,11 @@ [package] -authors = ["Łukasz Jan Niemier "] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-rational" version = "0.1.0" diff --git a/traits/Cargo.toml b/traits/Cargo.toml index ee01da4..ab72a01 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,12 @@ [package] +authors = ["The Rust Project Developers"] +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +documentation = "http://rust-num.github.io/num" +homepage = "https://github.com/rust-num/num" +keywords = ["mathematics", "numerics"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num" name = "num-traits" version = "0.1.0" -authors = ["Łukasz Jan Niemier "] [dependencies] From 72fa7ece483da16b238e7a37ac41c766bd99b60b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 11 Mar 2016 10:24:10 +0100 Subject: [PATCH 10/31] Reapply #167 --- integer/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integer/src/lib.rs b/integer/src/lib.rs index eee4ba2..5fdaf10 100644 --- a/integer/src/lib.rs +++ b/integer/src/lib.rs @@ -275,7 +275,7 @@ macro_rules! impl_integer_for_isize { #[inline] fn lcm(&self, other: &Self) -> Self { // should not have to recalculate abs - ((*self * *other) / self.gcd(other)).abs() + (*self * (*other / self.gcd(other))).abs() } /// Deprecated, use `is_multiple_of` instead. From 956bb0f4db0312a56e87be155954697ace9cd325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 25 Mar 2016 12:34:48 +0100 Subject: [PATCH 11/31] Reapply ebed6756de732f959bbc72bbb9ec8c4e28b19143 --- traits/src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 869b92f..366b1db 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -54,14 +54,21 @@ macro_rules! int_trait_impl { } int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); +#[derive(Debug)] pub enum FloatErrorKind { Empty, Invalid, } +// FIXME: std::num::ParseFloatError is stable in 1.0, but opaque to us, +// so there's not really any way for us to reuse it. +#[derive(Debug)] pub struct ParseFloatError { pub kind: FloatErrorKind, } +// FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck +// with this implementation ourselves until we want to make a breaking change. +// (would have to drop it from `Num` though) macro_rules! float_trait_impl { ($name:ident for $($t:ty)*) => ($( impl $name for $t { @@ -213,3 +220,14 @@ macro_rules! float_trait_impl { )*) } float_trait_impl!(Num for f32 f64); + +#[test] +fn from_str_radix_unwrap() { + // The Result error must impl Debug to allow unwrap() + + let i: i32 = Num::from_str_radix("0", 10).unwrap(); + assert_eq!(i, 0); + + let f: f32 = Num::from_str_radix("0.0", 10).unwrap(); + assert_eq!(f, 0.0); +} From b962e2b7088b3f19522a371f99bf601a4a2d6885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 25 Mar 2016 12:40:34 +0100 Subject: [PATCH 12/31] Remove leftovers --- src/bigint.rs | 4987 ------------------------------------------------- src/iter.rs | 372 ---- 2 files changed, 5359 deletions(-) delete mode 100644 src/bigint.rs delete mode 100644 src/iter.rs diff --git a/src/bigint.rs b/src/bigint.rs deleted file mode 100644 index a98752d..0000000 --- a/src/bigint.rs +++ /dev/null @@ -1,4987 +0,0 @@ -// Copyright 2013-2014 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. - -//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`). -//! -//! A `BigUint` is represented as a vector of `BigDigit`s. -//! A `BigInt` is a combination of `BigUint` and `Sign`. -//! -//! Common numerical operations are overloaded, so we can treat them -//! the same way we treat other numbers. -//! -//! ## Example -//! -//! ```rust -//! use num::{BigUint, Zero, One}; -//! use std::mem::replace; -//! -//! // Calculate large fibonacci numbers. -//! fn fib(n: usize) -> BigUint { -//! let mut f0: BigUint = Zero::zero(); -//! let mut f1: BigUint = One::one(); -//! for _ in 0..n { -//! let f2 = f0 + &f1; -//! // This is a low cost way of swapping f0 with f1 and f1 with f2. -//! f0 = replace(&mut f1, f2); -//! } -//! f0 -//! } -//! -//! // This is a very large number. -//! println!("fib(1000) = {}", fib(1000)); -//! ``` -//! -//! It's easy to generate large random numbers: -//! -//! ```rust -//! extern crate rand; -//! extern crate num; -//! -//! # #[cfg(feature = "rand")] -//! # fn main() { -//! use num::bigint::{ToBigInt, RandBigInt}; -//! -//! let mut rng = rand::thread_rng(); -//! let a = rng.gen_bigint(1000); -//! -//! let low = -10000.to_bigint().unwrap(); -//! let high = 10000.to_bigint().unwrap(); -//! let b = rng.gen_bigint_range(&low, &high); -//! -//! // Probably an even larger number. -//! println!("{}", a * b); -//! # } -//! -//! # #[cfg(not(feature = "rand"))] -//! # fn main() { -//! # } -//! ``` - -use Integer; - -use std::borrow::Cow; -use std::default::Default; -use std::error::Error; -use std::iter::repeat; -use std::num::ParseIntError; -use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub}; -use std::str::{self, FromStr}; -use std::fmt; -use std::cmp::Ordering::{self, Less, Greater, Equal}; -use std::{f32, f64}; -use std::{u8, i64, u64}; -use std::ascii::AsciiExt; - -#[cfg(feature = "serde")] -use serde; - -// Some of the tests of non-RNG-based functionality are randomized using the -// RNG-based functionality, so the RNG-based functionality needs to be enabled -// for tests. -#[cfg(any(feature = "rand", test))] -use rand::Rng; - -use traits::{ToPrimitive, FromPrimitive, Float}; - -use {Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, Signed, Zero, One}; -use self::Sign::{Minus, NoSign, Plus}; - -/// A `BigDigit` is a `BigUint`'s composing element. -pub type BigDigit = u32; - -/// A `DoubleBigDigit` is the internal type used to do the computations. Its -/// size is the double of the size of `BigDigit`. -pub type DoubleBigDigit = u64; - -pub const ZERO_BIG_DIGIT: BigDigit = 0; - -#[allow(non_snake_case)] -pub mod big_digit { - use super::BigDigit; - use super::DoubleBigDigit; - - // `DoubleBigDigit` size dependent - pub const BITS: usize = 32; - - pub const BASE: DoubleBigDigit = 1 << BITS; - const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS; - - #[inline] - fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit } - #[inline] - fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit } - - /// Split one `DoubleBigDigit` into two `BigDigit`s. - #[inline] - pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { - (get_hi(n), get_lo(n)) - } - - /// Join two `BigDigit`s into one `DoubleBigDigit` - #[inline] - pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit { - (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS) - } -} - -/* - * Generic functions for add/subtract/multiply with carry/borrow: - */ - -// Add with carry: -#[inline] -fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit { - let (hi, lo) = big_digit::from_doublebigdigit( - (a as DoubleBigDigit) + - (b as DoubleBigDigit) + - (*carry as DoubleBigDigit)); - - *carry = hi; - lo -} - -// Subtract with borrow: -#[inline] -fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit { - let (hi, lo) = big_digit::from_doublebigdigit( - big_digit::BASE - + (a as DoubleBigDigit) - - (b as DoubleBigDigit) - - (*borrow as DoubleBigDigit)); - /* - hi * (base) + lo == 1*(base) + ai - bi - borrow - => ai - bi - borrow < 0 <=> hi == 0 - */ - *borrow = if hi == 0 { 1 } else { 0 }; - lo -} - -#[inline] -fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit { - let (hi, lo) = big_digit::from_doublebigdigit( - (a as DoubleBigDigit) + - (b as DoubleBigDigit) * (c as DoubleBigDigit) + - (*carry as DoubleBigDigit)); - *carry = hi; - lo -} - -/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder: -/// -/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit. -/// This is _not_ true for an arbitrary numerator/denominator. -/// -/// (This function also matches what the x86 divide instruction does). -#[inline] -fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) { - debug_assert!(hi < divisor); - - let lhs = big_digit::to_doublebigdigit(hi, lo); - let rhs = divisor as DoubleBigDigit; - ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit) -} - -/// A big unsigned integer type. -/// -/// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number -/// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`. -#[derive(Clone, Debug, Hash)] -#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] -pub struct BigUint { - data: Vec -} - -impl PartialEq for BigUint { - #[inline] - fn eq(&self, other: &BigUint) -> bool { - match self.cmp(other) { Equal => true, _ => false } - } -} -impl Eq for BigUint {} - -impl PartialOrd for BigUint { - #[inline] - fn partial_cmp(&self, other: &BigUint) -> Option { - Some(self.cmp(other)) - } -} - -fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering { - debug_assert!(a.last() != Some(&0)); - debug_assert!(b.last() != Some(&0)); - - let (a_len, b_len) = (a.len(), b.len()); - if a_len < b_len { return Less; } - if a_len > b_len { return Greater; } - - for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) { - if ai < bi { return Less; } - if ai > bi { return Greater; } - } - return Equal; -} - -impl Ord for BigUint { - #[inline] - fn cmp(&self, other: &BigUint) -> Ordering { - cmp_slice(&self.data[..], &other.data[..]) - } -} - -impl Default for BigUint { - #[inline] - fn default() -> BigUint { Zero::zero() } -} - -impl fmt::Display for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(true, "", &self.to_str_radix(10)) - } -} - -impl fmt::LowerHex for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(true, "0x", &self.to_str_radix(16)) - } -} - -impl fmt::UpperHex for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(true, "0x", &self.to_str_radix(16).to_ascii_uppercase()) - } -} - -impl fmt::Binary for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(true, "0b", &self.to_str_radix(2)) - } -} - -impl fmt::Octal for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(true, "0o", &self.to_str_radix(8)) - } -} - -impl FromStr for BigUint { - type Err = ParseBigIntError; - - #[inline] - fn from_str(s: &str) -> Result { - BigUint::from_str_radix(s, 10) - } -} - -// Read bitwise digits that evenly divide BigDigit -fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { - debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0); - debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); - - let digits_per_big_digit = big_digit::BITS / bits; - - let data = v.chunks(digits_per_big_digit).map(|chunk| { - chunk.iter().rev().fold(0u32, |acc, &c| (acc << bits) | c as BigDigit) - }).collect(); - - BigUint::new(data) -} - -// Read bitwise digits that don't evenly divide BigDigit -fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint { - debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0); - debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits))); - - let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS; - let mut data = Vec::with_capacity(big_digits); - - let mut d = 0; - let mut dbits = 0; - for &c in v { - d |= (c as DoubleBigDigit) << dbits; - dbits += bits; - if dbits >= big_digit::BITS { - let (hi, lo) = big_digit::from_doublebigdigit(d); - data.push(lo); - d = hi as DoubleBigDigit; - dbits -= big_digit::BITS; - } - } - - if dbits > 0 { - debug_assert!(dbits < big_digit::BITS); - data.push(d as BigDigit); - } - - BigUint::new(data) -} - -// Read little-endian radix digits -fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint { - debug_assert!(!v.is_empty() && !radix.is_power_of_two()); - debug_assert!(v.iter().all(|&c| (c as u32) < radix)); - - // Estimate how big the result will be, so we can pre-allocate it. - let bits = (radix as f64).log2() * v.len() as f64; - let big_digits = (bits / big_digit::BITS as f64).ceil(); - let mut data = Vec::with_capacity(big_digits as usize); - - let (base, power) = get_radix_base(radix); - debug_assert!(base < (1 << 32)); - let base = base as BigDigit; - - let r = v.len() % power; - let i = if r == 0 { power } else { r }; - let (head, tail) = v.split_at(i); - - let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); - data.push(first); - - debug_assert!(tail.len() % power == 0); - for chunk in tail.chunks(power) { - if data.last() != Some(&0) { - data.push(0); - } - - let mut carry = 0; - for d in data.iter_mut() { - *d = mac_with_carry(0, *d, base, &mut carry); - } - debug_assert!(carry == 0); - - let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit); - add2(&mut data, &[n]); - } - - BigUint::new(data) -} - -impl Num for BigUint { - type Error = ParseBigIntError; - - /// Creates and initializes a `BigUint`. - fn from_str_radix(s: &str, radix: u32) -> Result { - assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); - let mut s = s; - if s.starts_with('+') { - let tail = &s[1..]; - if !tail.starts_with('+') { s = tail } - } - - if s.is_empty() { - // create ParseIntError::Empty - let e = u64::from_str_radix(s, radix).unwrap_err(); - return Err(e.into()); - } - - // First normalize all characters to plain digit values - let mut v = Vec::with_capacity(s.len()); - for b in s.bytes() { - let d = match b { - b'0' ... b'9' => b - b'0', - b'a' ... b'z' => b - b'a' + 10, - b'A' ... b'Z' => b - b'A' + 10, - _ => u8::MAX, - }; - if d < radix as u8 { - v.push(d); - } else { - // create ParseIntError::InvalidDigit - let e = u64::from_str_radix(&s[v.len()..], radix).unwrap_err(); - return Err(e.into()); - } - } - - let res = if radix.is_power_of_two() { - // Powers of two can use bitwise masks and shifting instead of multiplication - let bits = radix.trailing_zeros() as usize; - v.reverse(); - if big_digit::BITS % bits == 0 { - from_bitwise_digits_le(&v, bits) - } else { - from_inexact_bitwise_digits_le(&v, bits) - } - } else { - from_radix_digits_be(&v, radix) - }; - Ok(res) - } -} - -macro_rules! forward_val_val_binop { - (impl $imp:ident for $res:ty, $method:ident) => { - impl $imp<$res> for $res { - type Output = $res; - - #[inline] - fn $method(self, other: $res) -> $res { - // forward to val-ref - $imp::$method(self, &other) - } - } - } -} - -macro_rules! forward_val_val_binop_commutative { - (impl $imp:ident for $res:ty, $method:ident) => { - impl $imp<$res> for $res { - type Output = $res; - - #[inline] - fn $method(self, other: $res) -> $res { - // forward to val-ref, with the larger capacity as val - if self.data.capacity() >= other.data.capacity() { - $imp::$method(self, &other) - } else { - $imp::$method(other, &self) - } - } - } - } -} - -macro_rules! forward_ref_val_binop { - (impl $imp:ident for $res:ty, $method:ident) => { - impl<'a> $imp<$res> for &'a $res { - type Output = $res; - - #[inline] - fn $method(self, other: $res) -> $res { - // forward to ref-ref - $imp::$method(self, &other) - } - } - } -} - -macro_rules! forward_ref_val_binop_commutative { - (impl $imp:ident for $res:ty, $method:ident) => { - impl<'a> $imp<$res> for &'a $res { - type Output = $res; - - #[inline] - fn $method(self, other: $res) -> $res { - // reverse, forward to val-ref - $imp::$method(other, self) - } - } - } -} - -macro_rules! forward_val_ref_binop { - (impl $imp:ident for $res:ty, $method:ident) => { - impl<'a> $imp<&'a $res> for $res { - type Output = $res; - - #[inline] - fn $method(self, other: &$res) -> $res { - // forward to ref-ref - $imp::$method(&self, other) - } - } - } -} - -macro_rules! forward_ref_ref_binop { - (impl $imp:ident for $res:ty, $method:ident) => { - impl<'a, 'b> $imp<&'b $res> for &'a $res { - type Output = $res; - - #[inline] - fn $method(self, other: &$res) -> $res { - // forward to val-ref - $imp::$method(self.clone(), other) - } - } - } -} - -macro_rules! forward_ref_ref_binop_commutative { - (impl $imp:ident for $res:ty, $method:ident) => { - impl<'a, 'b> $imp<&'b $res> for &'a $res { - type Output = $res; - - #[inline] - fn $method(self, other: &$res) -> $res { - // forward to val-ref, choosing the larger to clone - if self.data.len() >= other.data.len() { - $imp::$method(self.clone(), other) - } else { - $imp::$method(other.clone(), self) - } - } - } - } -} - -// Forward everything to ref-ref, when reusing storage is not helpful -macro_rules! forward_all_binop_to_ref_ref { - (impl $imp:ident for $res:ty, $method:ident) => { - forward_val_val_binop!(impl $imp for $res, $method); - forward_val_ref_binop!(impl $imp for $res, $method); - forward_ref_val_binop!(impl $imp for $res, $method); - }; -} - -// Forward everything to val-ref, so LHS storage can be reused -macro_rules! forward_all_binop_to_val_ref { - (impl $imp:ident for $res:ty, $method:ident) => { - forward_val_val_binop!(impl $imp for $res, $method); - forward_ref_val_binop!(impl $imp for $res, $method); - forward_ref_ref_binop!(impl $imp for $res, $method); - }; -} - -// Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused -macro_rules! forward_all_binop_to_val_ref_commutative { - (impl $imp:ident for $res:ty, $method:ident) => { - forward_val_val_binop_commutative!(impl $imp for $res, $method); - forward_ref_val_binop_commutative!(impl $imp for $res, $method); - forward_ref_ref_binop_commutative!(impl $imp for $res, $method); - }; -} - -forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand); - -impl<'a> BitAnd<&'a BigUint> for BigUint { - type Output = BigUint; - - #[inline] - fn bitand(self, other: &BigUint) -> BigUint { - let mut data = self.data; - for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { - *ai &= bi; - } - data.truncate(other.data.len()); - BigUint::new(data) - } -} - -forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor); - -impl<'a> BitOr<&'a BigUint> for BigUint { - type Output = BigUint; - - fn bitor(self, other: &BigUint) -> BigUint { - let mut data = self.data; - for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { - *ai |= bi; - } - if other.data.len() > data.len() { - let extra = &other.data[data.len()..]; - data.extend(extra.iter().cloned()); - } - BigUint::new(data) - } -} - -forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor); - -impl<'a> BitXor<&'a BigUint> for BigUint { - type Output = BigUint; - - fn bitxor(self, other: &BigUint) -> BigUint { - let mut data = self.data; - for (ai, &bi) in data.iter_mut().zip(other.data.iter()) { - *ai ^= bi; - } - if other.data.len() > data.len() { - let extra = &other.data[data.len()..]; - data.extend(extra.iter().cloned()); - } - BigUint::new(data) - } -} - -#[inline] -fn biguint_shl(n: Cow, bits: usize) -> BigUint { - let n_unit = bits / big_digit::BITS; - let mut data = match n_unit { - 0 => n.into_owned().data, - _ => { - let len = n_unit + n.data.len() + 1; - let mut data = Vec::with_capacity(len); - data.extend(repeat(0).take(n_unit)); - data.extend(n.data.iter().cloned()); - data - }, - }; - - let n_bits = bits % big_digit::BITS; - if n_bits > 0 { - let mut carry = 0; - for elem in data[n_unit..].iter_mut() { - let new_carry = *elem >> (big_digit::BITS - n_bits); - *elem = (*elem << n_bits) | carry; - carry = new_carry; - } - if carry != 0 { - data.push(carry); - } - } - - BigUint::new(data) -} - -impl Shl for BigUint { - type Output = BigUint; - - #[inline] - fn shl(self, rhs: usize) -> BigUint { - biguint_shl(Cow::Owned(self), rhs) - } -} - -impl<'a> Shl for &'a BigUint { - type Output = BigUint; - - #[inline] - fn shl(self, rhs: usize) -> BigUint { - biguint_shl(Cow::Borrowed(self), rhs) - } -} - -#[inline] -fn biguint_shr(n: Cow, bits: usize) -> BigUint { - let n_unit = bits / big_digit::BITS; - if n_unit >= n.data.len() { return Zero::zero(); } - let mut data = match n_unit { - 0 => n.into_owned().data, - _ => n.data[n_unit..].to_vec(), - }; - - let n_bits = bits % big_digit::BITS; - if n_bits > 0 { - let mut borrow = 0; - for elem in data.iter_mut().rev() { - let new_borrow = *elem << (big_digit::BITS - n_bits); - *elem = (*elem >> n_bits) | borrow; - borrow = new_borrow; - } - } - - BigUint::new(data) -} - -impl Shr for BigUint { - type Output = BigUint; - - #[inline] - fn shr(self, rhs: usize) -> BigUint { - biguint_shr(Cow::Owned(self), rhs) - } -} - -impl<'a> Shr for &'a BigUint { - type Output = BigUint; - - #[inline] - fn shr(self, rhs: usize) -> BigUint { - biguint_shr(Cow::Borrowed(self), rhs) - } -} - -impl Zero for BigUint { - #[inline] - fn zero() -> BigUint { BigUint::new(Vec::new()) } - - #[inline] - fn is_zero(&self) -> bool { self.data.is_empty() } -} - -impl One for BigUint { - #[inline] - fn one() -> BigUint { BigUint::new(vec!(1)) } -} - -impl Unsigned for BigUint {} - -forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add); - -// Only for the Add impl: -#[must_use] -#[inline] -fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit { - let mut b_iter = b.iter(); - let mut carry = 0; - - for ai in a.iter_mut() { - if let Some(bi) = b_iter.next() { - *ai = adc(*ai, *bi, &mut carry); - } else if carry != 0 { - *ai = adc(*ai, 0, &mut carry); - } else { - break; - } - } - - debug_assert!(b_iter.next() == None); - carry -} - -/// /Two argument addition of raw slices: -/// a += b -/// -/// The caller _must_ ensure that a is big enough to store the result - typically this means -/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry. -fn add2(a: &mut [BigDigit], b: &[BigDigit]) { - let carry = __add2(a, b); - - debug_assert!(carry == 0); -} - -/* - * We'd really prefer to avoid using add2/sub2 directly as much as possible - since they make the - * caller entirely responsible for ensuring a's vector is big enough, and that the result is - * normalized, they're rather error prone and verbose: - * - * We could implement the Add and Sub traits for BigUint + BigDigit slices, like below - this works - * great, except that then it becomes the module's public interface, which we probably don't want: - * - * I'm keeping the code commented out, because I think this is worth revisiting: - -impl<'a> Add<&'a [BigDigit]> for BigUint { - type Output = BigUint; - - fn add(mut self, other: &[BigDigit]) -> BigUint { - if self.data.len() < other.len() { - let extra = other.len() - self.data.len(); - self.data.extend(repeat(0).take(extra)); - } - - let carry = __add2(&mut self.data[..], other); - if carry != 0 { - self.data.push(carry); - } - - self - } -} - */ - -impl<'a> Add<&'a BigUint> for BigUint { - type Output = BigUint; - - fn add(mut self, other: &BigUint) -> BigUint { - if self.data.len() < other.data.len() { - let extra = other.data.len() - self.data.len(); - self.data.extend(repeat(0).take(extra)); - } - - let carry = __add2(&mut self.data[..], &other.data[..]); - if carry != 0 { - self.data.push(carry); - } - - self - } -} - -forward_all_binop_to_val_ref!(impl Sub for BigUint, sub); - -fn sub2(a: &mut [BigDigit], b: &[BigDigit]) { - let mut b_iter = b.iter(); - let mut borrow = 0; - - for ai in a.iter_mut() { - if let Some(bi) = b_iter.next() { - *ai = sbb(*ai, *bi, &mut borrow); - } else if borrow != 0 { - *ai = sbb(*ai, 0, &mut borrow); - } else { - break; - } - } - - /* note: we're _required_ to fail on underflow */ - assert!(borrow == 0 && b_iter.all(|x| *x == 0), - "Cannot subtract b from a because b is larger than a."); -} - -impl<'a> Sub<&'a BigUint> for BigUint { - type Output = BigUint; - - fn sub(mut self, other: &BigUint) -> BigUint { - sub2(&mut self.data[..], &other.data[..]); - self.normalize() - } -} - -fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> BigInt { - // Normalize: - let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; - let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; - - match cmp_slice(a, b) { - Greater => { - let mut ret = BigUint::from_slice(a); - sub2(&mut ret.data[..], b); - BigInt::from_biguint(Plus, ret.normalize()) - }, - Less => { - let mut ret = BigUint::from_slice(b); - sub2(&mut ret.data[..], a); - BigInt::from_biguint(Minus, ret.normalize()) - }, - _ => Zero::zero(), - } -} - -forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul); - -/// Three argument multiply accumulate: -/// acc += b * c -fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) { - if c == 0 { return; } - - let mut b_iter = b.iter(); - let mut carry = 0; - - for ai in acc.iter_mut() { - if let Some(bi) = b_iter.next() { - *ai = mac_with_carry(*ai, *bi, c, &mut carry); - } else if carry != 0 { - *ai = mac_with_carry(*ai, 0, c, &mut carry); - } else { - break; - } - } - - assert!(carry == 0); -} - -/// Three argument multiply accumulate: -/// acc += b * c -fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) { - let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) }; - - /* - * Karatsuba multiplication is slower than long multiplication for small x and y: - */ - if x.len() <= 4 { - for (i, xi) in x.iter().enumerate() { - mac_digit(&mut acc[i..], y, *xi); - } - } else { - /* - * Karatsuba multiplication: - * - * The idea is that we break x and y up into two smaller numbers that each have about half - * as many digits, like so (note that multiplying by b is just a shift): - * - * x = x0 + x1 * b - * y = y0 + y1 * b - * - * With some algebra, we can compute x * y with three smaller products, where the inputs to - * each of the smaller products have only about half as many digits as x and y: - * - * x * y = (x0 + x1 * b) * (y0 + y1 * b) - * - * x * y = x0 * y0 - * + x0 * y1 * b - * + x1 * y0 * b - * + x1 * y1 * b^2 - * - * Let p0 = x0 * y0 and p2 = x1 * y1: - * - * x * y = p0 - * + (x0 * y1 + x1 * p0) * b - * + p2 * b^2 - * - * The real trick is that middle term: - * - * x0 * y1 + x1 * y0 - * - * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2 - * - * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2 - * - * Now we complete the square: - * - * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2 - * - * = -((x1 - x0) * (y1 - y0)) + p0 + p2 - * - * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula: - * - * x * y = p0 - * + (p0 + p2 - p1) * b - * + p2 * b^2 - * - * Where the three intermediate products are: - * - * p0 = x0 * y0 - * p1 = (x1 - x0) * (y1 - y0) - * p2 = x1 * y1 - * - * In doing the computation, we take great care to avoid unnecessary temporary variables - * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a - * bit so we can use the same temporary variable for all the intermediate products: - * - * x * y = p2 * b^2 + p2 * b - * + p0 * b + p0 - * - p1 * b - * - * The other trick we use is instead of doing explicit shifts, we slice acc at the - * appropriate offset when doing the add. - */ - - /* - * When x is smaller than y, it's significantly faster to pick b such that x is split in - * half, not y: - */ - let b = x.len() / 2; - let (x0, x1) = x.split_at(b); - let (y0, y1) = y.split_at(b); - - /* We reuse the same BigUint for all the intermediate multiplies: */ - - let len = y.len() + 1; - let mut p = BigUint { data: vec![0; len] }; - - // p2 = x1 * y1 - mac3(&mut p.data[..], x1, y1); - - // Not required, but the adds go faster if we drop any unneeded 0s from the end: - p = p.normalize(); - - add2(&mut acc[b..], &p.data[..]); - add2(&mut acc[b * 2..], &p.data[..]); - - // Zero out p before the next multiply: - p.data.truncate(0); - p.data.extend(repeat(0).take(len)); - - // p0 = x0 * y0 - mac3(&mut p.data[..], x0, y0); - p = p.normalize(); - - add2(&mut acc[..], &p.data[..]); - add2(&mut acc[b..], &p.data[..]); - - // p1 = (x1 - x0) * (y1 - y0) - // We do this one last, since it may be negative and acc can't ever be negative: - let j0 = sub_sign(x1, x0); - let j1 = sub_sign(y1, y0); - - match j0.sign * j1.sign { - Plus => { - p.data.truncate(0); - p.data.extend(repeat(0).take(len)); - - mac3(&mut p.data[..], &j0.data.data[..], &j1.data.data[..]); - p = p.normalize(); - - sub2(&mut acc[b..], &p.data[..]); - }, - Minus => { - mac3(&mut acc[b..], &j0.data.data[..], &j1.data.data[..]); - }, - NoSign => (), - } - } -} - -fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint { - let len = x.len() + y.len() + 1; - let mut prod = BigUint { data: vec![0; len] }; - - mac3(&mut prod.data[..], x, y); - prod.normalize() -} - -impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint { - type Output = BigUint; - - #[inline] - fn mul(self, other: &BigUint) -> BigUint { - mul3(&self.data[..], &other.data[..]) - } -} - -fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) { - let mut rem = 0; - - for d in a.data.iter_mut().rev() { - let (q, r) = div_wide(rem, *d, b); - *d = q; - rem = r; - } - - (a.normalize(), rem) -} - -forward_all_binop_to_ref_ref!(impl Div for BigUint, div); - -impl<'a, 'b> Div<&'b BigUint> for &'a BigUint { - type Output = BigUint; - - #[inline] - fn div(self, other: &BigUint) -> BigUint { - let (q, _) = self.div_rem(other); - return q; - } -} - -forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem); - -impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint { - type Output = BigUint; - - #[inline] - fn rem(self, other: &BigUint) -> BigUint { - let (_, r) = self.div_rem(other); - return r; - } -} - -impl Neg for BigUint { - type Output = BigUint; - - #[inline] - fn neg(self) -> BigUint { panic!() } -} - -impl<'a> Neg for &'a BigUint { - type Output = BigUint; - - #[inline] - fn neg(self) -> BigUint { panic!() } -} - -impl CheckedAdd for BigUint { - #[inline] - fn checked_add(&self, v: &BigUint) -> Option { - return Some(self.add(v)); - } -} - -impl CheckedSub for BigUint { - #[inline] - fn checked_sub(&self, v: &BigUint) -> Option { - match self.cmp(v) { - Less => None, - Equal => Some(Zero::zero()), - Greater => Some(self.sub(v)), - } - } -} - -impl CheckedMul for BigUint { - #[inline] - fn checked_mul(&self, v: &BigUint) -> Option { - return Some(self.mul(v)); - } -} - -impl CheckedDiv for BigUint { - #[inline] - fn checked_div(&self, v: &BigUint) -> Option { - if v.is_zero() { - return None; - } - return Some(self.div(v)); - } -} - -impl Integer for BigUint { - #[inline] - fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { - self.div_mod_floor(other) - } - - #[inline] - fn div_floor(&self, other: &BigUint) -> BigUint { - let (d, _) = self.div_mod_floor(other); - return d; - } - - #[inline] - fn mod_floor(&self, other: &BigUint) -> BigUint { - let (_, m) = self.div_mod_floor(other); - return m; - } - - fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { - if other.is_zero() { panic!() } - if self.is_zero() { return (Zero::zero(), Zero::zero()); } - if *other == One::one() { return (self.clone(), Zero::zero()); } - - /* Required or the q_len calculation below can underflow: */ - match self.cmp(other) { - Less => return (Zero::zero(), self.clone()), - Equal => return (One::one(), Zero::zero()), - Greater => {} // Do nothing - } - - /* - * This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D: - * - * First, normalize the arguments so the highest bit in the highest digit of the divisor is - * set: the main loop uses the highest digit of the divisor for generating guesses, so we - * want it to be the largest number we can efficiently divide by. - */ - let shift = other.data.last().unwrap().leading_zeros() as usize; - let mut a = self << shift; - let b = other << shift; - - /* - * The algorithm works by incrementally calculating "guesses", q0, for part of the - * remainder. Once we have any number q0 such that q0 * b <= a, we can set - * - * q += q0 - * a -= q0 * b - * - * and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder. - * - * q0, our guess, is calculated by dividing the last few digits of a by the last digit of b - * - this should give us a guess that is "close" to the actual quotient, but is possibly - * greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction - * until we have a guess such that q0 & b <= a. - */ - - let bn = *b.data.last().unwrap(); - let q_len = a.data.len() - b.data.len() + 1; - let mut q = BigUint { data: vec![0; q_len] }; - - /* - * We reuse the same temporary to avoid hitting the allocator in our inner loop - this is - * sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0 - * can be bigger). - */ - let mut tmp = BigUint { data: Vec::with_capacity(2) }; - - for j in (0..q_len).rev() { - /* - * When calculating our next guess q0, we don't need to consider the digits below j - * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from - * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those - * two numbers will be zero in all digits up to (j + b.data.len() - 1). - */ - let offset = j + b.data.len() - 1; - if offset >= a.data.len() { - continue; - } - - /* just avoiding a heap allocation: */ - let mut a0 = tmp; - a0.data.truncate(0); - a0.data.extend(a.data[offset..].iter().cloned()); - - /* - * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts - * implicitly at the end, when adding and subtracting to a and q. Not only do we - * save the cost of the shifts, the rest of the arithmetic gets to work with - * smaller numbers. - */ - let (mut q0, _) = div_rem_digit(a0, bn); - let mut prod = &b * &q0; - - while cmp_slice(&prod.data[..], &a.data[j..]) == Greater { - let one: BigUint = One::one(); - q0 = q0 - one; - prod = prod - &b; - } - - add2(&mut q.data[j..], &q0.data[..]); - sub2(&mut a.data[j..], &prod.data[..]); - a = a.normalize(); - - tmp = q0; - } - - debug_assert!(a < b); - - (q.normalize(), a >> shift) - } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. - /// - /// The result is always positive. - #[inline] - fn gcd(&self, other: &BigUint) -> BigUint { - // Use Euclid's algorithm - let mut m = (*self).clone(); - let mut n = (*other).clone(); - while !m.is_zero() { - let temp = m; - m = n % &temp; - n = temp; - } - return n; - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. - #[inline] - fn lcm(&self, other: &BigUint) -> BigUint { ((self * other) / self.gcd(other)) } - - /// Deprecated, use `is_multiple_of` instead. - #[inline] - fn divides(&self, other: &BigUint) -> bool { self.is_multiple_of(other) } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &BigUint) -> bool { (self % other).is_zero() } - - /// Returns `true` if the number is divisible by `2`. - #[inline] - fn is_even(&self) -> bool { - // Considering only the last digit. - match self.data.first() { - Some(x) => x.is_even(), - None => true - } - } - - /// Returns `true` if the number is not divisible by `2`. - #[inline] - fn is_odd(&self) -> bool { !self.is_even() } -} - -impl ToPrimitive for BigUint { - #[inline] - fn to_i64(&self) -> Option { - self.to_u64().and_then(|n| { - // If top bit of u64 is set, it's too large to convert to i64. - if n >> 63 == 0 { - Some(n as i64) - } else { - None - } - }) - } - - // `DoubleBigDigit` size dependent - #[inline] - fn to_u64(&self) -> Option { - match self.data.len() { - 0 => Some(0), - 1 => Some(self.data[0] as u64), - 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) - as u64), - _ => None - } - } - - // `DoubleBigDigit` size dependent - #[inline] - fn to_f32(&self) -> Option { - match self.data.len() { - 0 => Some(f32::zero()), - 1 => Some(self.data[0] as f32), - len => { - // this will prevent any overflow of exponent - if len > (f32::MAX_EXP as usize) / big_digit::BITS { - None - } else { - let exponent = (len - 2) * big_digit::BITS; - // we need 25 significant digits, 24 to be stored and 1 for rounding - // this gives at least 33 significant digits - let mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]); - // this cast handles rounding - let ret = (mantissa as f32) * 2.0.powi(exponent as i32); - if ret.is_infinite() { - None - } else { - Some(ret) - } - } - } - } - } - - // `DoubleBigDigit` size dependent - #[inline] - fn to_f64(&self) -> Option { - match self.data.len() { - 0 => Some(f64::zero()), - 1 => Some(self.data[0] as f64), - 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) as f64), - len => { - // this will prevent any overflow of exponent - if len > (f64::MAX_EXP as usize) / big_digit::BITS { - None - } else { - let mut exponent = (len - 2) * big_digit::BITS; - let mut mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]); - // we need at least 54 significant bit digits, 53 to be stored and 1 for rounding - // so we take enough from the next BigDigit to make it up to 64 - let shift = mantissa.leading_zeros() as usize; - if shift > 0 { - mantissa <<= shift; - mantissa |= self.data[len - 3] as u64 >> (big_digit::BITS - shift); - exponent -= shift; - } - // this cast handles rounding - let ret = (mantissa as f64) * 2.0.powi(exponent as i32); - if ret.is_infinite() { - None - } else { - Some(ret) - } - } - } - } - } -} - -impl FromPrimitive for BigUint { - #[inline] - fn from_i64(n: i64) -> Option { - if n >= 0 { - Some(BigUint::from(n as u64)) - } else { - None - } - } - - #[inline] - fn from_u64(n: u64) -> Option { - Some(BigUint::from(n)) - } - - #[inline] - fn from_f64(mut n: f64) -> Option { - // handle NAN, INFINITY, NEG_INFINITY - if !n.is_finite() { - return None; - } - - // match the rounding of casting from float to int - n = n.trunc(); - - // handle 0.x, -0.x - if n.is_zero() { - return Some(BigUint::zero()); - } - - let (mantissa, exponent, sign) = Float::integer_decode(n); - - if sign == -1 { - return None; - } - - let mut ret = BigUint::from(mantissa); - if exponent > 0 { - ret = ret << exponent as usize; - } else if exponent < 0 { - ret = ret >> (-exponent) as usize; - } - Some(ret) - } -} - -impl From for BigUint { - // `DoubleBigDigit` size dependent - #[inline] - fn from(n: u64) -> Self { - match big_digit::from_doublebigdigit(n) { - (0, 0) => BigUint::zero(), - (0, n0) => BigUint { data: vec![n0] }, - (n1, n0) => BigUint { data: vec![n0, n1] }, - } - } -} - -macro_rules! impl_biguint_from_uint { - ($T:ty) => { - impl From<$T> for BigUint { - #[inline] - fn from(n: $T) -> Self { - BigUint::from(n as u64) - } - } - } -} - -impl_biguint_from_uint!(u8); -impl_biguint_from_uint!(u16); -impl_biguint_from_uint!(u32); -impl_biguint_from_uint!(usize); - -/// A generic trait for converting a value to a `BigUint`. -pub trait ToBigUint { - /// Converts the value of `self` to a `BigUint`. - fn to_biguint(&self) -> Option; -} - -impl ToBigUint for BigInt { - #[inline] - fn to_biguint(&self) -> Option { - if self.sign == Plus { - Some(self.data.clone()) - } else if self.sign == NoSign { - Some(Zero::zero()) - } else { - None - } - } -} - -impl ToBigUint for BigUint { - #[inline] - fn to_biguint(&self) -> Option { - Some(self.clone()) - } -} - -macro_rules! impl_to_biguint { - ($T:ty, $from_ty:path) => { - impl ToBigUint for $T { - #[inline] - fn to_biguint(&self) -> Option { - $from_ty(*self) - } - } - } -} - -impl_to_biguint!(isize, FromPrimitive::from_isize); -impl_to_biguint!(i8, FromPrimitive::from_i8); -impl_to_biguint!(i16, FromPrimitive::from_i16); -impl_to_biguint!(i32, FromPrimitive::from_i32); -impl_to_biguint!(i64, FromPrimitive::from_i64); -impl_to_biguint!(usize, FromPrimitive::from_usize); -impl_to_biguint!(u8, FromPrimitive::from_u8); -impl_to_biguint!(u16, FromPrimitive::from_u16); -impl_to_biguint!(u32, FromPrimitive::from_u32); -impl_to_biguint!(u64, FromPrimitive::from_u64); -impl_to_biguint!(f32, FromPrimitive::from_f32); -impl_to_biguint!(f64, FromPrimitive::from_f64); - -// Extract bitwise digits that evenly divide BigDigit -fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { - debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0); - - let last_i = u.data.len() - 1; - let mask: BigDigit = (1 << bits) - 1; - let digits_per_big_digit = big_digit::BITS / bits; - let digits = (u.bits() + bits - 1) / bits; - let mut res = Vec::with_capacity(digits); - - for mut r in u.data[..last_i].iter().cloned() { - for _ in 0..digits_per_big_digit { - res.push((r & mask) as u8); - r >>= bits; - } - } - - let mut r = u.data[last_i]; - while r != 0 { - res.push((r & mask) as u8); - r >>= bits; - } - - res -} - -// Extract bitwise digits that don't evenly divide BigDigit -fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec { - debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0); - - let last_i = u.data.len() - 1; - let mask: DoubleBigDigit = (1 << bits) - 1; - let digits = (u.bits() + bits - 1) / bits; - let mut res = Vec::with_capacity(digits); - - let mut r = 0; - let mut rbits = 0; - for hi in u.data[..last_i].iter().cloned() { - r |= (hi as DoubleBigDigit) << rbits; - rbits += big_digit::BITS; - - while rbits >= bits { - res.push((r & mask) as u8); - r >>= bits; - rbits -= bits; - } - } - - r |= (u.data[last_i] as DoubleBigDigit) << rbits; - while r != 0 { - res.push((r & mask) as u8); - r >>= bits; - } - - res -} - -// Extract little-endian radix digits -#[inline(always)] // forced inline to get const-prop for radix=10 -fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec { - debug_assert!(!u.is_zero() && !radix.is_power_of_two()); - - // Estimate how big the result will be, so we can pre-allocate it. - let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil(); - let mut res = Vec::with_capacity(radix_digits as usize); - let mut digits = u.clone(); - - let (base, power) = get_radix_base(radix); - debug_assert!(base < (1 << 32)); - let base = base as BigDigit; - - while digits.data.len() > 1 { - let (q, mut r) = div_rem_digit(digits, base); - for _ in 0..power { - res.push((r % radix) as u8); - r /= radix; - } - digits = q; - } - - let mut r = digits.data[0]; - while r != 0 { - res.push((r % radix) as u8); - r /= radix; - } - - res -} - -fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec { - assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); - - if u.is_zero() { - return vec![b'0'] - } - - let mut res = if radix.is_power_of_two() { - // Powers of two can use bitwise masks and shifting instead of division - let bits = radix.trailing_zeros() as usize; - if big_digit::BITS % bits == 0 { - to_bitwise_digits_le(u, bits) - } else { - to_inexact_bitwise_digits_le(u, bits) - } - } else if radix == 10 { - // 10 is so common that it's worth separating out for const-propagation. - // Optimizers can often turn constant division into a faster multiplication. - to_radix_digits_le(u, 10) - } else { - to_radix_digits_le(u, radix) - }; - - // Now convert everything to ASCII digits. - for r in &mut res { - debug_assert!((*r as u32) < radix); - if *r < 10 { - *r += b'0'; - } else { - *r += b'a' - 10; - } - } - res -} - -impl BigUint { - /// Creates and initializes a `BigUint`. - /// - /// The digits are in little-endian base 2^32. - #[inline] - pub fn new(digits: Vec) -> BigUint { - BigUint { data: digits }.normalize() - } - - /// Creates and initializes a `BigUint`. - /// - /// The digits are in little-endian base 2^32. - #[inline] - pub fn from_slice(slice: &[BigDigit]) -> BigUint { - BigUint::new(slice.to_vec()) - } - - /// Creates and initializes a `BigUint`. - /// - /// The bytes are in big-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::BigUint; - /// - /// assert_eq!(BigUint::from_bytes_be(b"A"), - /// BigUint::parse_bytes(b"65", 10).unwrap()); - /// assert_eq!(BigUint::from_bytes_be(b"AA"), - /// BigUint::parse_bytes(b"16705", 10).unwrap()); - /// assert_eq!(BigUint::from_bytes_be(b"AB"), - /// BigUint::parse_bytes(b"16706", 10).unwrap()); - /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"), - /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); - /// ``` - #[inline] - pub fn from_bytes_be(bytes: &[u8]) -> BigUint { - if bytes.is_empty() { - Zero::zero() - } else { - let mut v = bytes.to_vec(); - v.reverse(); - BigUint::from_bytes_le(&*v) - } - } - - /// Creates and initializes a `BigUint`. - /// - /// The bytes are in little-endian byte order. - #[inline] - pub fn from_bytes_le(bytes: &[u8]) -> BigUint { - if bytes.is_empty() { - Zero::zero() - } else { - from_bitwise_digits_le(bytes, 8) - } - } - - /// Returns the byte representation of the `BigUint` in little-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::BigUint; - /// - /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); - /// assert_eq!(i.to_bytes_le(), vec![101, 4]); - /// ``` - #[inline] - pub fn to_bytes_le(&self) -> Vec { - if self.is_zero() { - vec![0] - } else { - to_bitwise_digits_le(self, 8) - } - } - - /// Returns the byte representation of the `BigUint` in big-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::BigUint; - /// - /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); - /// assert_eq!(i.to_bytes_be(), vec![4, 101]); - /// ``` - #[inline] - pub fn to_bytes_be(&self) -> Vec { - let mut v = self.to_bytes_le(); - v.reverse(); - v - } - - /// Returns the integer formatted as a string in the given radix. - /// `radix` must be in the range `[2, 36]`. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::BigUint; - /// - /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); - /// assert_eq!(i.to_str_radix(16), "ff"); - /// ``` - #[inline] - pub fn to_str_radix(&self, radix: u32) -> String { - let mut v = to_str_radix_reversed(self, radix); - v.reverse(); - unsafe { String::from_utf8_unchecked(v) } - } - - /// Creates and initializes a `BigUint`. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{BigUint, ToBigUint}; - /// - /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234)); - /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); - /// assert_eq!(BigUint::parse_bytes(b"G", 16), None); - /// ``` - #[inline] - pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { - str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok()) - } - - /// Determines the fewest bits necessary to express the `BigUint`. - pub fn bits(&self) -> usize { - if self.is_zero() { return 0; } - let zeros = self.data.last().unwrap().leading_zeros(); - return self.data.len()*big_digit::BITS - zeros as usize; - } - - /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to - /// be nonzero. - #[inline] - fn normalize(mut self) -> BigUint { - while let Some(&0) = self.data.last() { - self.data.pop(); - } - self - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for BigUint { - fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where - S: serde::Serializer - { - self.data.serialize(serializer) - } -} - -#[cfg(feature = "serde")] -impl serde::Deserialize for BigUint { - fn deserialize(deserializer: &mut D) -> Result where - D: serde::Deserializer, - { - let data = try!(Vec::deserialize(deserializer)); - Ok(BigUint { - data: data, - }) - } -} - -// `DoubleBigDigit` size dependent -/// Returns the greatest power of the radix <= big_digit::BASE -#[inline] -fn get_radix_base(radix: u32) -> (DoubleBigDigit, usize) { - // To generate this table: - // let target = std::u32::max as u64 + 1; - // for radix in 2u64..37 { - // let power = (target as f64).log(radix as f64) as u32; - // let base = radix.pow(power); - // println!("({:10}, {:2}), // {:2}", base, power, radix); - // } - const BASES: [(DoubleBigDigit, usize); 37] = [ - (0, 0), (0, 0), - (4294967296, 32), // 2 - (3486784401, 20), // 3 - (4294967296, 16), // 4 - (1220703125, 13), // 5 - (2176782336, 12), // 6 - (1977326743, 11), // 7 - (1073741824, 10), // 8 - (3486784401, 10), // 9 - (1000000000, 9), // 10 - (2357947691, 9), // 11 - ( 429981696, 8), // 12 - ( 815730721, 8), // 13 - (1475789056, 8), // 14 - (2562890625, 8), // 15 - (4294967296, 8), // 16 - ( 410338673, 7), // 17 - ( 612220032, 7), // 18 - ( 893871739, 7), // 19 - (1280000000, 7), // 20 - (1801088541, 7), // 21 - (2494357888, 7), // 22 - (3404825447, 7), // 23 - ( 191102976, 6), // 24 - ( 244140625, 6), // 25 - ( 308915776, 6), // 26 - ( 387420489, 6), // 27 - ( 481890304, 6), // 28 - ( 594823321, 6), // 29 - ( 729000000, 6), // 30 - ( 887503681, 6), // 31 - (1073741824, 6), // 32 - (1291467969, 6), // 33 - (1544804416, 6), // 34 - (1838265625, 6), // 35 - (2176782336, 6), // 36 - ]; - - assert!(2 <= radix && radix <= 36, "The radix must be within 2...36"); - BASES[radix as usize] -} - -/// A Sign is a `BigInt`'s composing element. -#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)] -#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] -pub enum Sign { Minus, NoSign, Plus } - -impl Neg for Sign { - type Output = Sign; - - /// Negate Sign value. - #[inline] - fn neg(self) -> Sign { - match self { - Minus => Plus, - NoSign => NoSign, - Plus => Minus - } - } -} - -impl Mul for Sign { - type Output = Sign; - - #[inline] - fn mul(self, other: Sign) -> Sign { - match (self, other) { - (NoSign, _) | (_, NoSign) => NoSign, - (Plus, Plus) | (Minus, Minus) => Plus, - (Plus, Minus) | (Minus, Plus) => Minus, - } - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for Sign { - fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where - S: serde::Serializer - { - match *self { - Sign::Minus => (-1i8).serialize(serializer), - Sign::NoSign => 0i8.serialize(serializer), - Sign::Plus => 1i8.serialize(serializer), - } - } -} - -#[cfg(feature = "serde")] -impl serde::Deserialize for Sign { - fn deserialize(deserializer: &mut D) -> Result where - D: serde::Deserializer, - { - use serde::de::Error; - - let sign: i8 = try!(serde::Deserialize::deserialize(deserializer)); - match sign { - -1 => Ok(Sign::Minus), - 0 => Ok(Sign::NoSign), - 1 => Ok(Sign::Plus), - _ => Err(D::Error::invalid_value("sign must be -1, 0, or 1")), - } - } -} - -/// A big signed integer type. -#[derive(Clone, Debug, Hash)] -#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] -pub struct BigInt { - sign: Sign, - data: BigUint -} - -impl PartialEq for BigInt { - #[inline] - fn eq(&self, other: &BigInt) -> bool { - self.cmp(other) == Equal - } -} - -impl Eq for BigInt {} - -impl PartialOrd for BigInt { - #[inline] - fn partial_cmp(&self, other: &BigInt) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for BigInt { - #[inline] - fn cmp(&self, other: &BigInt) -> Ordering { - let scmp = self.sign.cmp(&other.sign); - if scmp != Equal { return scmp; } - - match self.sign { - NoSign => Equal, - Plus => self.data.cmp(&other.data), - Minus => other.data.cmp(&self.data), - } - } -} - -impl Default for BigInt { - #[inline] - fn default() -> BigInt { Zero::zero() } -} - -impl fmt::Display for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10)) - } -} - -impl fmt::Binary for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2)) - } -} - -impl fmt::Octal for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8)) - } -} - -impl fmt::LowerHex for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16)) - } -} - -impl fmt::UpperHex for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16).to_ascii_uppercase()) - } -} - -impl FromStr for BigInt { - type Err = ParseBigIntError; - - #[inline] - fn from_str(s: &str) -> Result { - BigInt::from_str_radix(s, 10) - } -} - -impl Num for BigInt { - type Error = ParseBigIntError; - - /// Creates and initializes a BigInt. - #[inline] - fn from_str_radix(mut s: &str, radix: u32) -> Result { - let sign = if s.starts_with('-') { - let tail = &s[1..]; - if !tail.starts_with('+') { s = tail } - Minus - } else { Plus }; - let bu = try!(BigUint::from_str_radix(s, radix)); - Ok(BigInt::from_biguint(sign, bu)) - } -} - -impl Shl for BigInt { - type Output = BigInt; - - #[inline] - fn shl(self, rhs: usize) -> BigInt { (&self) << rhs } -} - -impl<'a> Shl for &'a BigInt { - type Output = BigInt; - - #[inline] - fn shl(self, rhs: usize) -> BigInt { - BigInt::from_biguint(self.sign, &self.data << rhs) - } -} - -impl Shr for BigInt { - type Output = BigInt; - - #[inline] - fn shr(self, rhs: usize) -> BigInt { - BigInt::from_biguint(self.sign, self.data >> rhs) - } -} - -impl<'a> Shr for &'a BigInt { - type Output = BigInt; - - #[inline] - fn shr(self, rhs: usize) -> BigInt { - BigInt::from_biguint(self.sign, &self.data >> rhs) - } -} - -impl Zero for BigInt { - #[inline] - fn zero() -> BigInt { - BigInt::from_biguint(NoSign, Zero::zero()) - } - - #[inline] - fn is_zero(&self) -> bool { self.sign == NoSign } -} - -impl One for BigInt { - #[inline] - fn one() -> BigInt { - BigInt::from_biguint(Plus, One::one()) - } -} - -impl Signed for BigInt { - #[inline] - fn abs(&self) -> BigInt { - match self.sign { - Plus | NoSign => self.clone(), - Minus => BigInt::from_biguint(Plus, self.data.clone()) - } - } - - #[inline] - fn abs_sub(&self, other: &BigInt) -> BigInt { - if *self <= *other { Zero::zero() } else { self - other } - } - - #[inline] - fn signum(&self) -> BigInt { - match self.sign { - Plus => BigInt::from_biguint(Plus, One::one()), - Minus => BigInt::from_biguint(Minus, One::one()), - NoSign => Zero::zero(), - } - } - - #[inline] - fn is_positive(&self) -> bool { self.sign == Plus } - - #[inline] - fn is_negative(&self) -> bool { self.sign == Minus } -} - -// We want to forward to BigUint::add, but it's not clear how that will go until -// we compare both sign and magnitude. So we duplicate this body for every -// val/ref combination, deferring that decision to BigUint's own forwarding. -macro_rules! bigint_add { - ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { - match ($a.sign, $b.sign) { - (_, NoSign) => $a_owned, - (NoSign, _) => $b_owned, - // same sign => keep the sign with the sum of magnitudes - (Plus, Plus) | (Minus, Minus) => - BigInt::from_biguint($a.sign, $a_data + $b_data), - // opposite signs => keep the sign of the larger with the difference of magnitudes - (Plus, Minus) | (Minus, Plus) => - match $a.data.cmp(&$b.data) { - Less => BigInt::from_biguint($b.sign, $b_data - $a_data), - Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), - Equal => Zero::zero(), - }, - } - }; -} - -impl<'a, 'b> Add<&'b BigInt> for &'a BigInt { - type Output = BigInt; - - #[inline] - fn add(self, other: &BigInt) -> BigInt { - bigint_add!(self, self.clone(), &self.data, other, other.clone(), &other.data) - } -} - -impl<'a> Add for &'a BigInt { - type Output = BigInt; - - #[inline] - fn add(self, other: BigInt) -> BigInt { - bigint_add!(self, self.clone(), &self.data, other, other, other.data) - } -} - -impl<'a> Add<&'a BigInt> for BigInt { - type Output = BigInt; - - #[inline] - fn add(self, other: &BigInt) -> BigInt { - bigint_add!(self, self, self.data, other, other.clone(), &other.data) - } -} - -impl Add for BigInt { - type Output = BigInt; - - #[inline] - fn add(self, other: BigInt) -> BigInt { - bigint_add!(self, self, self.data, other, other, other.data) - } -} - -// We want to forward to BigUint::sub, but it's not clear how that will go until -// we compare both sign and magnitude. So we duplicate this body for every -// val/ref combination, deferring that decision to BigUint's own forwarding. -macro_rules! bigint_sub { - ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => { - match ($a.sign, $b.sign) { - (_, NoSign) => $a_owned, - (NoSign, _) => -$b_owned, - // opposite signs => keep the sign of the left with the sum of magnitudes - (Plus, Minus) | (Minus, Plus) => - BigInt::from_biguint($a.sign, $a_data + $b_data), - // same sign => keep or toggle the sign of the left with the difference of magnitudes - (Plus, Plus) | (Minus, Minus) => - match $a.data.cmp(&$b.data) { - Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data), - Greater => BigInt::from_biguint($a.sign, $a_data - $b_data), - Equal => Zero::zero(), - }, - } - }; -} - -impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt { - type Output = BigInt; - - #[inline] - fn sub(self, other: &BigInt) -> BigInt { - bigint_sub!(self, self.clone(), &self.data, other, other.clone(), &other.data) - } -} - -impl<'a> Sub for &'a BigInt { - type Output = BigInt; - - #[inline] - fn sub(self, other: BigInt) -> BigInt { - bigint_sub!(self, self.clone(), &self.data, other, other, other.data) - } -} - -impl<'a> Sub<&'a BigInt> for BigInt { - type Output = BigInt; - - #[inline] - fn sub(self, other: &BigInt) -> BigInt { - bigint_sub!(self, self, self.data, other, other.clone(), &other.data) - } -} - -impl Sub for BigInt { - type Output = BigInt; - - #[inline] - fn sub(self, other: BigInt) -> BigInt { - bigint_sub!(self, self, self.data, other, other, other.data) - } -} - -forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul); - -impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt { - type Output = BigInt; - - #[inline] - fn mul(self, other: &BigInt) -> BigInt { - BigInt::from_biguint(self.sign * other.sign, - &self.data * &other.data) - } -} - -forward_all_binop_to_ref_ref!(impl Div for BigInt, div); - -impl<'a, 'b> Div<&'b BigInt> for &'a BigInt { - type Output = BigInt; - - #[inline] - fn div(self, other: &BigInt) -> BigInt { - let (q, _) = self.div_rem(other); - q - } -} - -forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem); - -impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt { - type Output = BigInt; - - #[inline] - fn rem(self, other: &BigInt) -> BigInt { - let (_, r) = self.div_rem(other); - r - } -} - -impl Neg for BigInt { - type Output = BigInt; - - #[inline] - fn neg(mut self) -> BigInt { - self.sign = -self.sign; - self - } -} - -impl<'a> Neg for &'a BigInt { - type Output = BigInt; - - #[inline] - fn neg(self) -> BigInt { - -self.clone() - } -} - -impl CheckedAdd for BigInt { - #[inline] - fn checked_add(&self, v: &BigInt) -> Option { - return Some(self.add(v)); - } -} - -impl CheckedSub for BigInt { - #[inline] - fn checked_sub(&self, v: &BigInt) -> Option { - return Some(self.sub(v)); - } -} - -impl CheckedMul for BigInt { - #[inline] - fn checked_mul(&self, v: &BigInt) -> Option { - return Some(self.mul(v)); - } -} - -impl CheckedDiv for BigInt { - #[inline] - fn checked_div(&self, v: &BigInt) -> Option { - if v.is_zero() { - return None; - } - return Some(self.div(v)); - } -} - -impl Integer for BigInt { - #[inline] - fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { - // r.sign == self.sign - let (d_ui, r_ui) = self.data.div_mod_floor(&other.data); - let d = BigInt::from_biguint(self.sign, d_ui); - let r = BigInt::from_biguint(self.sign, r_ui); - if other.is_negative() { (-d, r) } else { (d, r) } - } - - #[inline] - fn div_floor(&self, other: &BigInt) -> BigInt { - let (d, _) = self.div_mod_floor(other); - d - } - - #[inline] - fn mod_floor(&self, other: &BigInt) -> BigInt { - let (_, m) = self.div_mod_floor(other); - m - } - - fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { - // m.sign == other.sign - let (d_ui, m_ui) = self.data.div_rem(&other.data); - let d = BigInt::from_biguint(Plus, d_ui); - let m = BigInt::from_biguint(Plus, m_ui); - let one: BigInt = One::one(); - match (self.sign, other.sign) { - (_, NoSign) => panic!(), - (Plus, Plus) | (NoSign, Plus) => (d, m), - (Plus, Minus) | (NoSign, Minus) => { - if m.is_zero() { - (-d, Zero::zero()) - } else { - (-d - one, m + other) - } - }, - (Minus, Plus) => { - if m.is_zero() { - (-d, Zero::zero()) - } else { - (-d - one, other - m) - } - } - (Minus, Minus) => (d, -m) - } - } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. - /// - /// The result is always positive. - #[inline] - fn gcd(&self, other: &BigInt) -> BigInt { - BigInt::from_biguint(Plus, self.data.gcd(&other.data)) - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. - #[inline] - fn lcm(&self, other: &BigInt) -> BigInt { - BigInt::from_biguint(Plus, self.data.lcm(&other.data)) - } - - /// Deprecated, use `is_multiple_of` instead. - #[inline] - fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) } - - /// Returns `true` if the number is divisible by `2`. - #[inline] - fn is_even(&self) -> bool { self.data.is_even() } - - /// Returns `true` if the number is not divisible by `2`. - #[inline] - fn is_odd(&self) -> bool { self.data.is_odd() } -} - -impl ToPrimitive for BigInt { - #[inline] - fn to_i64(&self) -> Option { - match self.sign { - Plus => self.data.to_i64(), - NoSign => Some(0), - Minus => { - self.data.to_u64().and_then(|n| { - let m: u64 = 1 << 63; - if n < m { - Some(-(n as i64)) - } else if n == m { - Some(i64::MIN) - } else { - None - } - }) - } - } - } - - #[inline] - fn to_u64(&self) -> Option { - match self.sign { - Plus => self.data.to_u64(), - NoSign => Some(0), - Minus => None - } - } - - #[inline] - fn to_f32(&self) -> Option { - self.data.to_f32().map(|n| if self.sign == Minus { -n } else { n }) - } - - #[inline] - fn to_f64(&self) -> Option { - self.data.to_f64().map(|n| if self.sign == Minus { -n } else { n }) - } -} - -impl FromPrimitive for BigInt { - #[inline] - fn from_i64(n: i64) -> Option { - Some(BigInt::from(n)) - } - - #[inline] - fn from_u64(n: u64) -> Option { - Some(BigInt::from(n)) - } - - #[inline] - fn from_f64(n: f64) -> Option { - if n >= 0.0 { - BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x)) - } else { - BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x)) - } - } -} - -impl From for BigInt { - #[inline] - fn from(n: i64) -> Self { - if n >= 0 { - BigInt::from(n as u64) - } else { - let u = u64::MAX - (n as u64) + 1; - BigInt { sign: Minus, data: BigUint::from(u) } - } - } -} - -macro_rules! impl_bigint_from_int { - ($T:ty) => { - impl From<$T> for BigInt { - #[inline] - fn from(n: $T) -> Self { - BigInt::from(n as i64) - } - } - } -} - -impl_bigint_from_int!(i8); -impl_bigint_from_int!(i16); -impl_bigint_from_int!(i32); -impl_bigint_from_int!(isize); - -impl From for BigInt { - #[inline] - fn from(n: u64) -> Self { - if n > 0 { - BigInt { sign: Plus, data: BigUint::from(n) } - } else { - BigInt::zero() - } - } -} - -macro_rules! impl_bigint_from_uint { - ($T:ty) => { - impl From<$T> for BigInt { - #[inline] - fn from(n: $T) -> Self { - BigInt::from(n as u64) - } - } - } -} - -impl_bigint_from_uint!(u8); -impl_bigint_from_uint!(u16); -impl_bigint_from_uint!(u32); -impl_bigint_from_uint!(usize); - -impl From for BigInt { - #[inline] - fn from(n: BigUint) -> Self { - if n.is_zero() { - BigInt::zero() - } else { - BigInt { sign: Plus, data: n } - } - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for BigInt { - fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where - S: serde::Serializer - { - (self.sign, &self.data).serialize(serializer) - } -} - -#[cfg(feature = "serde")] -impl serde::Deserialize for BigInt { - fn deserialize(deserializer: &mut D) -> Result where - D: serde::Deserializer, - { - let (sign, data) = try!(serde::Deserialize::deserialize(deserializer)); - Ok(BigInt { - sign: sign, - data: data, - }) - } -} - -/// A generic trait for converting a value to a `BigInt`. -pub trait ToBigInt { - /// Converts the value of `self` to a `BigInt`. - fn to_bigint(&self) -> Option; -} - -impl ToBigInt for BigInt { - #[inline] - fn to_bigint(&self) -> Option { - Some(self.clone()) - } -} - -impl ToBigInt for BigUint { - #[inline] - fn to_bigint(&self) -> Option { - if self.is_zero() { - Some(Zero::zero()) - } else { - Some(BigInt { sign: Plus, data: self.clone() }) - } - } -} - -macro_rules! impl_to_bigint { - ($T:ty, $from_ty:path) => { - impl ToBigInt for $T { - #[inline] - fn to_bigint(&self) -> Option { - $from_ty(*self) - } - } - } -} - -impl_to_bigint!(isize, FromPrimitive::from_isize); -impl_to_bigint!(i8, FromPrimitive::from_i8); -impl_to_bigint!(i16, FromPrimitive::from_i16); -impl_to_bigint!(i32, FromPrimitive::from_i32); -impl_to_bigint!(i64, FromPrimitive::from_i64); -impl_to_bigint!(usize, FromPrimitive::from_usize); -impl_to_bigint!(u8, FromPrimitive::from_u8); -impl_to_bigint!(u16, FromPrimitive::from_u16); -impl_to_bigint!(u32, FromPrimitive::from_u32); -impl_to_bigint!(u64, FromPrimitive::from_u64); -impl_to_bigint!(f32, FromPrimitive::from_f32); -impl_to_bigint!(f64, FromPrimitive::from_f64); - -pub trait RandBigInt { - /// Generate a random `BigUint` of the given bit size. - fn gen_biguint(&mut self, bit_size: usize) -> BigUint; - - /// Generate a random BigInt of the given bit size. - fn gen_bigint(&mut self, bit_size: usize) -> BigInt; - - /// Generate a random `BigUint` less than the given bound. Fails - /// when the bound is zero. - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; - - /// Generate a random `BigUint` within the given range. The lower - /// bound is inclusive; the upper bound is exclusive. Fails when - /// the upper bound is not greater than the lower bound. - fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; - - /// Generate a random `BigInt` within the given range. The lower - /// bound is inclusive; the upper bound is exclusive. Fails when - /// the upper bound is not greater than the lower bound. - fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; -} - -#[cfg(any(feature = "rand", test))] -impl RandBigInt for R { - fn gen_biguint(&mut self, bit_size: usize) -> BigUint { - let (digits, rem) = bit_size.div_rem(&big_digit::BITS); - let mut data = Vec::with_capacity(digits+1); - for _ in 0 .. digits { - data.push(self.gen()); - } - if rem > 0 { - let final_digit: BigDigit = self.gen(); - data.push(final_digit >> (big_digit::BITS - rem)); - } - BigUint::new(data) - } - - fn gen_bigint(&mut self, bit_size: usize) -> BigInt { - // Generate a random BigUint... - let biguint = self.gen_biguint(bit_size); - // ...and then randomly assign it a Sign... - let sign = if biguint.is_zero() { - // ...except that if the BigUint is zero, we need to try - // again with probability 0.5. This is because otherwise, - // the probability of generating a zero BigInt would be - // double that of any other number. - if self.gen() { - return self.gen_bigint(bit_size); - } else { - NoSign - } - } else if self.gen() { - Plus - } else { - Minus - }; - BigInt::from_biguint(sign, biguint) - } - - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { - assert!(!bound.is_zero()); - let bits = bound.bits(); - loop { - let n = self.gen_biguint(bits); - if n < *bound { return n; } - } - } - - fn gen_biguint_range(&mut self, - lbound: &BigUint, - ubound: &BigUint) - -> BigUint { - assert!(*lbound < *ubound); - return lbound + self.gen_biguint_below(&(ubound - lbound)); - } - - fn gen_bigint_range(&mut self, - lbound: &BigInt, - ubound: &BigInt) - -> BigInt { - assert!(*lbound < *ubound); - let delta = (ubound - lbound).to_biguint().unwrap(); - return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap(); - } -} - -impl BigInt { - /// Creates and initializes a BigInt. - /// - /// The digits are in little-endian base 2^32. - #[inline] - pub fn new(sign: Sign, digits: Vec) -> BigInt { - BigInt::from_biguint(sign, BigUint::new(digits)) - } - - /// Creates and initializes a `BigInt`. - /// - /// The digits are in little-endian base 2^32. - #[inline] - pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt { - if sign == NoSign || data.is_zero() { - return BigInt { sign: NoSign, data: Zero::zero() }; - } - BigInt { sign: sign, data: data } - } - - /// Creates and initializes a `BigInt`. - #[inline] - pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_slice(slice)) - } - - /// Creates and initializes a `BigInt`. - /// - /// The bytes are in big-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{BigInt, Sign}; - /// - /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"), - /// BigInt::parse_bytes(b"65", 10).unwrap()); - /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"), - /// BigInt::parse_bytes(b"16705", 10).unwrap()); - /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"), - /// BigInt::parse_bytes(b"16706", 10).unwrap()); - /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"), - /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); - /// ``` - #[inline] - pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes)) - } - - /// Creates and initializes a `BigInt`. - /// - /// The bytes are in little-endian byte order. - #[inline] - pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes)) - } - - /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{ToBigInt, Sign}; - /// - /// let i = -1125.to_bigint().unwrap(); - /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); - /// ``` - #[inline] - pub fn to_bytes_le(&self) -> (Sign, Vec) { - (self.sign, self.data.to_bytes_le()) - } - - /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{ToBigInt, Sign}; - /// - /// let i = -1125.to_bigint().unwrap(); - /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); - /// ``` - #[inline] - pub fn to_bytes_be(&self) -> (Sign, Vec) { - (self.sign, self.data.to_bytes_be()) - } - - /// Returns the integer formatted as a string in the given radix. - /// `radix` must be in the range `[2, 36]`. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::BigInt; - /// - /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); - /// assert_eq!(i.to_str_radix(16), "ff"); - /// ``` - #[inline] - pub fn to_str_radix(&self, radix: u32) -> String { - let mut v = to_str_radix_reversed(&self.data, radix); - - if self.is_negative() { - v.push(b'-'); - } - - v.reverse(); - unsafe { String::from_utf8_unchecked(v) } - } - - /// Returns the sign of the `BigInt` as a `Sign`. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{ToBigInt, Sign}; - /// - /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus); - /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus); - /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign); - /// ``` - #[inline] - pub fn sign(&self) -> Sign { - self.sign - } - - /// Creates and initializes a `BigInt`. - /// - /// # Examples - /// - /// ``` - /// use num::bigint::{BigInt, ToBigInt}; - /// - /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234)); - /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); - /// assert_eq!(BigInt::parse_bytes(b"G", 16), None); - /// ``` - #[inline] - pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { - str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok()) - } - - /// Determines the fewest bits necessary to express the `BigInt`, - /// not including the sign. - pub fn bits(&self) -> usize { - self.data.bits() - } - - /// Converts this `BigInt` into a `BigUint`, if it's not negative. - #[inline] - pub fn to_biguint(&self) -> Option { - match self.sign { - Plus => Some(self.data.clone()), - NoSign => Some(Zero::zero()), - Minus => None - } - } - - #[inline] - pub fn checked_add(&self, v: &BigInt) -> Option { - return Some(self.add(v)); - } - - #[inline] - pub fn checked_sub(&self, v: &BigInt) -> Option { - return Some(self.sub(v)); - } - - #[inline] - pub fn checked_mul(&self, v: &BigInt) -> Option { - return Some(self.mul(v)); - } - - #[inline] - pub fn checked_div(&self, v: &BigInt) -> Option { - if v.is_zero() { - return None; - } - return Some(self.div(v)); - } -} - -#[derive(Debug, PartialEq)] -pub enum ParseBigIntError { - ParseInt(ParseIntError), - Other, -} - -impl fmt::Display for ParseBigIntError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &ParseBigIntError::ParseInt(ref e) => e.fmt(f), - &ParseBigIntError::Other => "failed to parse provided string".fmt(f) - } - } -} - -impl Error for ParseBigIntError { - fn description(&self) -> &str { "failed to parse bigint/biguint" } -} - -impl From for ParseBigIntError { - fn from(err: ParseIntError) -> ParseBigIntError { - ParseBigIntError::ParseInt(err) - } -} - -#[cfg(test)] -mod biguint_tests { - use Integer; - use super::{BigDigit, BigUint, ToBigUint, big_digit}; - use super::{BigInt, RandBigInt, ToBigInt}; - use super::Sign::Plus; - - use std::cmp::Ordering::{Less, Equal, Greater}; - use std::{f32, f64}; - use std::i64; - use std::iter::repeat; - use std::str::FromStr; - use std::{u8, u16, u32, u64, usize}; - - use rand::thread_rng; - use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv}; - use {ToPrimitive, FromPrimitive}; - use Float; - - /// Assert that an op works for all val/ref combinations - macro_rules! assert_op { - ($left:ident $op:tt $right:ident == $expected:expr) => { - assert_eq!((&$left) $op (&$right), $expected); - assert_eq!((&$left) $op $right.clone(), $expected); - assert_eq!($left.clone() $op (&$right), $expected); - assert_eq!($left.clone() $op $right.clone(), $expected); - }; - } - - #[test] - fn test_from_slice() { - fn check(slice: &[BigDigit], data: &[BigDigit]) { - assert!(BigUint::from_slice(slice).data == data); - } - check(&[1], &[1]); - check(&[0, 0, 0], &[]); - check(&[1, 2, 0, 0], &[1, 2]); - check(&[0, 0, 1, 2], &[0, 0, 1, 2]); - check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]); - check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]); - } - - #[test] - fn test_from_bytes_be() { - fn check(s: &str, result: &str) { - assert_eq!(BigUint::from_bytes_be(s.as_bytes()), - BigUint::parse_bytes(result.as_bytes(), 10).unwrap()); - } - check("A", "65"); - check("AA", "16705"); - check("AB", "16706"); - check("Hello world!", "22405534230753963835153736737"); - assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero()); - } - - #[test] - fn test_to_bytes_be() { - fn check(s: &str, result: &str) { - let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); - assert_eq!(b.to_bytes_be(), s.as_bytes()); - } - check("A", "65"); - check("AA", "16705"); - check("AB", "16706"); - check("Hello world!", "22405534230753963835153736737"); - let b: BigUint = Zero::zero(); - assert_eq!(b.to_bytes_be(), [0]); - - // Test with leading/trailing zero bytes and a full BigDigit of value 0 - let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); - assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]); - } - - #[test] - fn test_from_bytes_le() { - fn check(s: &str, result: &str) { - assert_eq!(BigUint::from_bytes_le(s.as_bytes()), - BigUint::parse_bytes(result.as_bytes(), 10).unwrap()); - } - check("A", "65"); - check("AA", "16705"); - check("BA", "16706"); - check("!dlrow olleH", "22405534230753963835153736737"); - assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero()); - } - - #[test] - fn test_to_bytes_le() { - fn check(s: &str, result: &str) { - let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap(); - assert_eq!(b.to_bytes_le(), s.as_bytes()); - } - check("A", "65"); - check("AA", "16705"); - check("BA", "16706"); - check("!dlrow olleH", "22405534230753963835153736737"); - let b: BigUint = Zero::zero(); - assert_eq!(b.to_bytes_le(), [0]); - - // Test with leading/trailing zero bytes and a full BigDigit of value 0 - let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap(); - assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]); - } - - #[test] - fn test_cmp() { - let data: [&[_]; 7] = [ &[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1] ]; - let data: Vec = data.iter().map(|v| BigUint::from_slice(*v)).collect(); - for (i, ni) in data.iter().enumerate() { - for (j0, nj) in data[i..].iter().enumerate() { - let j = j0 + i; - if i == j { - assert_eq!(ni.cmp(nj), Equal); - assert_eq!(nj.cmp(ni), Equal); - assert_eq!(ni, nj); - assert!(!(ni != nj)); - assert!(ni <= nj); - assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); - } else { - assert_eq!(ni.cmp(nj), Less); - assert_eq!(nj.cmp(ni), Greater); - - assert!(!(ni == nj)); - assert!(ni != nj); - - assert!(ni <= nj); - assert!(!(ni >= nj)); - assert!(ni < nj); - assert!(!(ni > nj)); - - assert!(!(nj <= ni)); - assert!(nj >= ni); - assert!(!(nj < ni)); - assert!(nj > ni); - } - } - } - } - - #[test] - fn test_hash() { - let a = BigUint::new(vec!()); - let b = BigUint::new(vec!(0)); - let c = BigUint::new(vec!(1)); - let d = BigUint::new(vec!(1,0,0,0,0,0)); - let e = BigUint::new(vec!(0,0,0,0,0,1)); - assert!(::hash(&a) == ::hash(&b)); - assert!(::hash(&b) != ::hash(&c)); - assert!(::hash(&c) == ::hash(&d)); - assert!(::hash(&d) != ::hash(&e)); - } - - const BIT_TESTS: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - // LEFT RIGHT AND OR XOR - ( &[], &[], &[], &[], &[] ), - ( &[268, 482, 17], &[964, 54], &[260, 34], &[972, 502, 17], &[712, 468, 17] ), - ]; - - #[test] - fn test_bitand() { - for elm in BIT_TESTS { - let (a_vec, b_vec, c_vec, _, _) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(a & b == c); - assert_op!(b & a == c); - } - } - - #[test] - fn test_bitor() { - for elm in BIT_TESTS { - let (a_vec, b_vec, _, c_vec, _) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(a | b == c); - assert_op!(b | a == c); - } - } - - #[test] - fn test_bitxor() { - for elm in BIT_TESTS { - let (a_vec, b_vec, _, _, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(a ^ b == c); - assert_op!(b ^ a == c); - assert_op!(a ^ c == b); - assert_op!(c ^ a == b); - assert_op!(b ^ c == a); - assert_op!(c ^ b == a); - } - } - - #[test] - fn test_shl() { - fn check(s: &str, shift: usize, ans: &str) { - let opt_biguint = BigUint::from_str_radix(s, 16).ok(); - let bu = (opt_biguint.unwrap() << shift).to_str_radix(16); - assert_eq!(bu, ans); - } - - check("0", 3, "0"); - check("1", 3, "8"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 3, - "8\ - 0000\ - 0000\ - 0000\ - 0008\ - 0000\ - 0000\ - 0000\ - 0008"); - check("1\ - 0000\ - 0001\ - 0000\ - 0001", - 2, - "4\ - 0000\ - 0004\ - 0000\ - 0004"); - check("1\ - 0001\ - 0001", - 1, - "2\ - 0002\ - 0002"); - - check("\ - 4000\ - 0000\ - 0000\ - 0000", - 3, - "2\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000\ - 0000", - 2, - "1\ - 0000\ - 0000"); - check("4000", - 2, - "1\ - 0000"); - - check("4000\ - 0000\ - 0000\ - 0000", - 67, - "2\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000\ - 0000", - 35, - "2\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000", - 19, - "2\ - 0000\ - 0000"); - - check("fedc\ - ba98\ - 7654\ - 3210\ - fedc\ - ba98\ - 7654\ - 3210", - 4, - "f\ - edcb\ - a987\ - 6543\ - 210f\ - edcb\ - a987\ - 6543\ - 2100"); - check("88887777666655554444333322221111", 16, - "888877776666555544443333222211110000"); - } - - #[test] - fn test_shr() { - fn check(s: &str, shift: usize, ans: &str) { - let opt_biguint = BigUint::from_str_radix(s, 16).ok(); - let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16); - assert_eq!(bu, ans); - } - - check("0", 3, "0"); - check("f", 3, "1"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 3, - "2000\ - 0000\ - 0000\ - 0000\ - 2000\ - 0000\ - 0000\ - 0000"); - check("1\ - 0000\ - 0001\ - 0000\ - 0001", - 2, - "4000\ - 0000\ - 4000\ - 0000"); - check("1\ - 0001\ - 0001", - 1, - "8000\ - 8000"); - - check("2\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 67, - "4000\ - 0000\ - 0000\ - 0000"); - check("2\ - 0000\ - 0001\ - 0000\ - 0001", - 35, - "4000\ - 0000"); - check("2\ - 0001\ - 0001", - 19, - "4000"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0000", - 1, - "8000\ - 0000\ - 0000\ - 0000"); - check("1\ - 0000\ - 0000", - 1, - "8000\ - 0000"); - check("1\ - 0000", - 1, - "8000"); - check("f\ - edcb\ - a987\ - 6543\ - 210f\ - edcb\ - a987\ - 6543\ - 2100", - 4, - "fedc\ - ba98\ - 7654\ - 3210\ - fedc\ - ba98\ - 7654\ - 3210"); - - check("888877776666555544443333222211110000", 16, - "88887777666655554444333322221111"); - } - - const N1: BigDigit = -1i32 as BigDigit; - const N2: BigDigit = -2i32 as BigDigit; - - // `DoubleBigDigit` size dependent - #[test] - fn test_convert_i64() { - fn check(b1: BigUint, i: i64) { - let b2: BigUint = FromPrimitive::from_i64(i).unwrap(); - assert!(b1 == b2); - assert!(b1.to_i64().unwrap() == i); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(i64::MAX.to_biguint().unwrap(), i64::MAX); - - check(BigUint::new(vec!( )), 0); - check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS))); - check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1); - check(BigUint::new(vec!( 0, 1 )), (1 << (1*big_digit::BITS))); - check(BigUint::new(vec!(N1, N1 >> 1)), i64::MAX); - - assert_eq!(i64::MIN.to_biguint(), None); - assert_eq!(BigUint::new(vec!(N1, N1 )).to_i64(), None); - assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None); - assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_i64(), None); - } - - // `DoubleBigDigit` size dependent - #[test] - fn test_convert_u64() { - fn check(b1: BigUint, u: u64) { - let b2: BigUint = FromPrimitive::from_u64(u).unwrap(); - assert!(b1 == b2); - assert!(b1.to_u64().unwrap() == u); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(u64::MIN.to_biguint().unwrap(), u64::MIN); - check(u64::MAX.to_biguint().unwrap(), u64::MAX); - - check(BigUint::new(vec!( )), 0); - check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS))); - check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1); - check(BigUint::new(vec!( 0, 1)), (1 << (1*big_digit::BITS))); - check(BigUint::new(vec!(N1, N1)), u64::MAX); - - assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None); - assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_u64(), None); - } - - #[test] - fn test_convert_f32() { - fn check(b1: &BigUint, f: f32) { - let b2 = BigUint::from_f32(f).unwrap(); - assert_eq!(b1, &b2); - assert_eq!(b1.to_f32().unwrap(), f); - } - - check(&BigUint::zero(), 0.0); - check(&BigUint::one(), 1.0); - check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0); - check(&BigUint::from(1u64 << 32), 2.0.powi(32)); - check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); - check(&((BigUint::one() << 100) + (BigUint::one() << 123)), 2.0.powi(100) + 2.0.powi(123)); - check(&(BigUint::one() << 127), 2.0.powi(127)); - check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); - - // keeping all 24 digits with the bits at different offsets to the BigDigits - let x: u32 = 0b00000000101111011111011011011101; - let mut f = x as f32; - let mut b = BigUint::from(x); - for _ in 0..64 { - check(&b, f); - f *= 2.0; - b = b << 1; - } - - // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 - let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111; - assert!((n as f64) as f32 != n as f32); - assert_eq!(BigUint::from(n).to_f32(), Some(n as f32)); - - // test rounding up with the bits at different offsets to the BigDigits - let mut f = ((1u64 << 25) - 1) as f32; - let mut b = BigUint::from(1u64 << 25); - for _ in 0..64 { - assert_eq!(b.to_f32(), Some(f)); - f *= 2.0; - b = b << 1; - } - - // rounding - assert_eq!(BigUint::from_f32(-1.0), None); - assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero())); - assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32))); - assert_eq!(BigUint::from_f32(f32::consts::PI), Some(BigUint::from(3u32))); - - // special float values - assert_eq!(BigUint::from_f32(f32::NAN), None); - assert_eq!(BigUint::from_f32(f32::INFINITY), None); - assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None); - assert_eq!(BigUint::from_f32(f32::MIN), None); - - // largest BigUint that will round to a finite f32 value - let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25)); - assert_eq!(big_num.to_f32(), Some(f32::MAX)); - assert_eq!((big_num + BigUint::one()).to_f32(), None); - - assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None); - assert_eq!((BigUint::one() << 128).to_f32(), None); - } - - #[test] - fn test_convert_f64() { - fn check(b1: &BigUint, f: f64) { - let b2 = BigUint::from_f64(f).unwrap(); - assert_eq!(b1, &b2); - assert_eq!(b1.to_f64().unwrap(), f); - } - - check(&BigUint::zero(), 0.0); - check(&BigUint::one(), 1.0); - check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0); - check(&BigUint::from(1u64 << 32), 2.0.powi(32)); - check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64)); - check(&((BigUint::one() << 100) + (BigUint::one() << 152)), 2.0.powi(100) + 2.0.powi(152)); - check(&(BigUint::one() << 1023), 2.0.powi(1023)); - check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); - - // keeping all 53 digits with the bits at different offsets to the BigDigits - let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; - let mut f = x as f64; - let mut b = BigUint::from(x); - for _ in 0..128 { - check(&b, f); - f *= 2.0; - b = b << 1; - } - - // test rounding up with the bits at different offsets to the BigDigits - let mut f = ((1u64 << 54) - 1) as f64; - let mut b = BigUint::from(1u64 << 54); - for _ in 0..128 { - assert_eq!(b.to_f64(), Some(f)); - f *= 2.0; - b = b << 1; - } - - // rounding - assert_eq!(BigUint::from_f64(-1.0), None); - assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero())); - assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32))); - assert_eq!(BigUint::from_f64(f64::consts::PI), Some(BigUint::from(3u32))); - - // special float values - assert_eq!(BigUint::from_f64(f64::NAN), None); - assert_eq!(BigUint::from_f64(f64::INFINITY), None); - assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None); - assert_eq!(BigUint::from_f64(f64::MIN), None); - - // largest BigUint that will round to a finite f64 value - let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54)); - assert_eq!(big_num.to_f64(), Some(f64::MAX)); - assert_eq!((big_num + BigUint::one()).to_f64(), None); - - assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); - assert_eq!((BigUint::one() << 1024).to_f64(), None); - } - - #[test] - fn test_convert_to_bigint() { - fn check(n: BigUint, ans: BigInt) { - assert_eq!(n.to_bigint().unwrap(), ans); - assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n); - } - check(Zero::zero(), Zero::zero()); - check(BigUint::new(vec!(1,2,3)), - BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3)))); - } - - #[test] - fn test_convert_from_uint() { - macro_rules! check { - ($ty:ident, $max:expr) => { - assert_eq!(BigUint::from($ty::zero()), BigUint::zero()); - assert_eq!(BigUint::from($ty::one()), BigUint::one()); - assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one()); - assert_eq!(BigUint::from($ty::MAX), $max); - } - } - - check!(u8, BigUint::from_slice(&[u8::MAX as BigDigit])); - check!(u16, BigUint::from_slice(&[u16::MAX as BigDigit])); - check!(u32, BigUint::from_slice(&[u32::MAX])); - check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX])); - check!(usize, BigUint::from(usize::MAX as u64)); - } - - const SUM_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[ 1]), - (&[ 1], &[ 1], &[ 2]), - (&[ 1], &[ 1, 1], &[ 2, 1]), - (&[ 1], &[N1], &[ 0, 1]), - (&[ 1], &[N1, N1], &[ 0, 0, 1]), - (&[N1, N1], &[N1, N1], &[N2, N1, 1]), - (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]), - (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2]) - ]; - - #[test] - fn test_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(a + b == c); - assert_op!(b + a == c); - } - } - - #[test] - fn test_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(c - a == b); - assert_op!(c - b == a); - } - } - - #[test] - #[should_panic] - fn test_sub_fail_on_underflow() { - let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one()); - a - b; - } - - const M: u32 = ::std::u32::MAX; - const MUL_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[]), - (&[ 2], &[], &[]), - (&[ 1], &[ 1], &[1]), - (&[ 2], &[ 3], &[ 6]), - (&[ 1], &[ 1, 1, 1], &[1, 1, 1]), - (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]), - (&[ 1, 1, 1], &[N1], &[N1, N1, N1]), - (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]), - (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), - (&[N1], &[N1], &[ 1, N2]), - (&[N1, N1], &[N1], &[ 1, N1, N2]), - (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]), - (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]), - (&[ M/2 + 1], &[ 2], &[ 0, 1]), - (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]), - (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]), - (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), - (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]), - (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]), - (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]) - ]; - - const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] - = &[ - (&[ 1], &[ 2], &[], &[1]), - (&[ 1, 1], &[ 2], &[ M/2+1], &[1]), - (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]), - (&[ 0, 1], &[N1], &[1], &[1]), - (&[N1, N1], &[N2], &[2, 1], &[3]) - ]; - - #[test] - fn test_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert_op!(a * b == c); - assert_op!(b * a == c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - assert!(a == &b * &c + &d); - assert!(a == &c * &b + &d); - } - } - - #[test] - fn test_div_rem() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - if !a.is_zero() { - assert_op!(c / a == b); - assert_op!(c % a == Zero::zero()); - assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); - } - if !b.is_zero() { - assert_op!(c / b == a); - assert_op!(c % b == Zero::zero()); - assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); - } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - if !b.is_zero() { - assert_op!(a / b == c); - assert_op!(a % b == d); - assert!(a.div_rem(&b) == (c, d)); - } - } - } - - #[test] - fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a.checked_add(&b).unwrap() == c); - assert!(b.checked_add(&a).unwrap() == c); - } - } - - #[test] - fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(c.checked_sub(&a).unwrap() == b); - assert!(c.checked_sub(&b).unwrap() == a); - - if a > c { - assert!(a.checked_sub(&c).is_none()); - } - if b > c { - assert!(b.checked_sub(&c).is_none()); - } - } - } - - #[test] - fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a.checked_mul(&b).unwrap() == c); - assert!(b.checked_mul(&a).unwrap() == c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - assert!(a == b.checked_mul(&c).unwrap() + &d); - assert!(a == c.checked_mul(&b).unwrap() + &d); - } - } - - #[test] - fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - if !a.is_zero() { - assert!(c.checked_div(&a).unwrap() == b); - } - if !b.is_zero() { - assert!(c.checked_div(&b).unwrap() == a); - } - - assert!(c.checked_div(&Zero::zero()).is_none()); - } - } - - #[test] - fn test_gcd() { - fn check(a: usize, b: usize, c: usize) { - let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); - let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); - let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); - - assert_eq!(big_a.gcd(&big_b), big_c); - } - - check(10, 2, 2); - check(10, 3, 1); - check(0, 3, 3); - check(3, 3, 3); - check(56, 42, 14); - } - - #[test] - fn test_lcm() { - fn check(a: usize, b: usize, c: usize) { - let big_a: BigUint = FromPrimitive::from_usize(a).unwrap(); - let big_b: BigUint = FromPrimitive::from_usize(b).unwrap(); - let big_c: BigUint = FromPrimitive::from_usize(c).unwrap(); - - assert_eq!(big_a.lcm(&big_b), big_c); - } - - check(1, 0, 0); - check(0, 1, 0); - check(1, 1, 1); - check(8, 9, 72); - check(11, 5, 55); - check(99, 17, 1683); - } - - #[test] - fn test_is_even() { - let one: BigUint = FromStr::from_str("1").unwrap(); - let two: BigUint = FromStr::from_str("2").unwrap(); - let thousand: BigUint = FromStr::from_str("1000").unwrap(); - let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap(); - let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap(); - assert!(one.is_odd()); - assert!(two.is_even()); - assert!(thousand.is_even()); - assert!(big.is_even()); - assert!(bigger.is_odd()); - assert!((&one << 64).is_even()); - assert!(((&one << 64) + one).is_odd()); - } - - fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { - let bits = big_digit::BITS; - vec!(( Zero::zero(), vec!( - (2, "0".to_string()), (3, "0".to_string()) - )), ( BigUint::from_slice(&[ 0xff ]), vec!( - (2, "11111111".to_string()), - (3, "100110".to_string()), - (4, "3333".to_string()), - (5, "2010".to_string()), - (6, "1103".to_string()), - (7, "513".to_string()), - (8, "377".to_string()), - (9, "313".to_string()), - (10, "255".to_string()), - (11, "212".to_string()), - (12, "193".to_string()), - (13, "168".to_string()), - (14, "143".to_string()), - (15, "120".to_string()), - (16, "ff".to_string()) - )), ( BigUint::from_slice(&[ 0xfff ]), vec!( - (2, "111111111111".to_string()), - (4, "333333".to_string()), - (16, "fff".to_string()) - )), ( BigUint::from_slice(&[ 1, 2 ]), vec!( - (2, - format!("10{}1", repeat("0").take(bits - 1).collect::())), - (4, - format!("2{}1", repeat("0").take(bits / 2 - 1).collect::())), - (10, match bits { - 32 => "8589934593".to_string(), - 16 => "131073".to_string(), - _ => panic!() - }), - (16, - format!("2{}1", repeat("0").take(bits / 4 - 1).collect::())) - )), ( BigUint::from_slice(&[ 1, 2, 3 ]), vec!( - (2, - format!("11{}10{}1", - repeat("0").take(bits - 2).collect::(), - repeat("0").take(bits - 1).collect::())), - (4, - format!("3{}2{}1", - repeat("0").take(bits / 2 - 1).collect::(), - repeat("0").take(bits / 2 - 1).collect::())), - (8, match bits { - 32 => "6000000000100000000001".to_string(), - 16 => "140000400001".to_string(), - _ => panic!() - }), - (10, match bits { - 32 => "55340232229718589441".to_string(), - 16 => "12885032961".to_string(), - _ => panic!() - }), - (16, - format!("3{}2{}1", - repeat("0").take(bits / 4 - 1).collect::(), - repeat("0").take(bits / 4 - 1).collect::())) - )) ) - } - - #[test] - fn test_to_str_radix() { - let r = to_str_pairs(); - for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; - for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; - assert_eq!(n.to_str_radix(*radix), *str); - } - } - } - - #[test] - fn test_from_str_radix() { - let r = to_str_pairs(); - for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; - for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; - assert_eq!(n, - &BigUint::from_str_radix(str, *radix).unwrap()); - } - } - - let zed = BigUint::from_str_radix("Z", 10).ok(); - assert_eq!(zed, None); - let blank = BigUint::from_str_radix("_", 2).ok(); - assert_eq!(blank, None); - let plus_one = BigUint::from_str_radix("+1", 10).ok(); - assert_eq!(plus_one, Some(BigUint::from_slice(&[1]))); - let plus_plus_one = BigUint::from_str_radix("++1", 10).ok(); - assert_eq!(plus_plus_one, None); - let minus_one = BigUint::from_str_radix("-1", 10).ok(); - assert_eq!(minus_one, None); - } - - #[test] - fn test_all_str_radix() { - use std::ascii::AsciiExt; - - let n = BigUint::new((0..10).collect()); - for radix in 2..37 { - let s = n.to_str_radix(radix); - let x = BigUint::from_str_radix(&s, radix); - assert_eq!(x.unwrap(), n); - - let s = s.to_ascii_uppercase(); - let x = BigUint::from_str_radix(&s, radix); - assert_eq!(x.unwrap(), n); - } - } - - #[test] - fn test_lower_hex() { - let a = BigUint::parse_bytes(b"A", 16).unwrap(); - let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:x}", a), "a"); - assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421"); - assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); - } - - #[test] - fn test_upper_hex() { - let a = BigUint::parse_bytes(b"A", 16).unwrap(); - let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:X}", a), "A"); - assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421"); - assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); - } - - #[test] - fn test_binary() { - let a = BigUint::parse_bytes(b"A", 16).unwrap(); - let hello = BigUint::parse_bytes("224055342307539".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:b}", a), "1010"); - assert_eq!(format!("{:b}", hello), "110010111100011011110011000101101001100011010011"); - assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); - } - - #[test] - fn test_octal() { - let a = BigUint::parse_bytes(b"A", 16).unwrap(); - let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:o}", a), "12"); - assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041"); - assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); - } - - #[test] - fn test_display() { - let a = BigUint::parse_bytes(b"A", 16).unwrap(); - let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{}", a), "10"); - assert_eq!(format!("{}", hello), "22405534230753963835153736737"); - assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); - } - - #[test] - fn test_factor() { - fn factor(n: usize) -> BigUint { - let mut f: BigUint = One::one(); - for i in 2..n + 1 { - // FIXME(#5992): assignment operator overloads - // f *= FromPrimitive::from_usize(i); - let bu: BigUint = FromPrimitive::from_usize(i).unwrap(); - f = f * bu; - } - return f; - } - - fn check(n: usize, s: &str) { - let n = factor(n); - let ans = match BigUint::from_str_radix(s, 10) { - Ok(x) => x, Err(_) => panic!() - }; - assert_eq!(n, ans); - } - - check(3, "6"); - check(10, "3628800"); - check(20, "2432902008176640000"); - check(30, "265252859812191058636308480000000"); - } - - #[test] - fn test_bits() { - assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0); - let n: BigUint = FromPrimitive::from_usize(0).unwrap(); - assert_eq!(n.bits(), 0); - let n: BigUint = FromPrimitive::from_usize(1).unwrap(); - assert_eq!(n.bits(), 1); - let n: BigUint = FromPrimitive::from_usize(3).unwrap(); - assert_eq!(n.bits(), 2); - let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap(); - assert_eq!(n.bits(), 39); - let one: BigUint = One::one(); - assert_eq!((one << 426).bits(), 427); - } - - #[test] - fn test_rand() { - let mut rng = thread_rng(); - let _n: BigUint = rng.gen_biguint(137); - assert!(rng.gen_biguint(0).is_zero()); - } - - #[test] - fn test_rand_range() { - let mut rng = thread_rng(); - - for _ in 0..10 { - assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(), - &FromPrimitive::from_usize(237).unwrap()), - FromPrimitive::from_usize(236).unwrap()); - } - - let l = FromPrimitive::from_usize(403469000 + 2352).unwrap(); - let u = FromPrimitive::from_usize(403469000 + 3513).unwrap(); - for _ in 0..1000 { - let n: BigUint = rng.gen_biguint_below(&u); - assert!(n < u); - - let n: BigUint = rng.gen_biguint_range(&l, &u); - assert!(n >= l); - assert!(n < u); - } - } - - #[test] - #[should_panic] - fn test_zero_rand_range() { - thread_rng().gen_biguint_range(&FromPrimitive::from_usize(54).unwrap(), - &FromPrimitive::from_usize(54).unwrap()); - } - - #[test] - #[should_panic] - fn test_negative_rand_range() { - let mut rng = thread_rng(); - let l = FromPrimitive::from_usize(2352).unwrap(); - let u = FromPrimitive::from_usize(3513).unwrap(); - // Switching u and l should fail: - let _n: BigUint = rng.gen_biguint_range(&u, &l); - } - - #[test] - fn test_sub_sign() { - use super::sub_sign; - let a = BigInt::from_str_radix("265252859812191058636308480000000", 10).unwrap(); - let b = BigInt::from_str_radix("26525285981219105863630848000000", 10).unwrap(); - - assert_eq!(sub_sign(&a.data.data[..], &b.data.data[..]), &a - &b); - assert_eq!(sub_sign(&b.data.data[..], &a.data.data[..]), &b - &a); - } - - fn test_mul_divide_torture_count(count: usize) { - use rand::{SeedableRng, StdRng, Rng}; - - let bits_max = 1 << 12; - let seed: &[_] = &[1, 2, 3, 4]; - let mut rng: StdRng = SeedableRng::from_seed(seed); - - for _ in 0..count { - /* Test with numbers of random sizes: */ - let xbits = rng.gen_range(0, bits_max); - let ybits = rng.gen_range(0, bits_max); - - let x = rng.gen_biguint(xbits); - let y = rng.gen_biguint(ybits); - - if x.is_zero() || y.is_zero() { - continue; - } - - let prod = &x * &y; - assert_eq!(&prod / &x, y); - assert_eq!(&prod / &y, x); - } - } - - #[test] - fn test_mul_divide_torture() { - test_mul_divide_torture_count(1000); - } - - #[test] - #[ignore] - fn test_mul_divide_torture_long() { - test_mul_divide_torture_count(1000000); - } -} - -#[cfg(test)] -mod bigint_tests { - use Integer; - use super::{BigDigit, BigUint, ToBigUint}; - use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit}; - use super::Sign::{Minus, NoSign, Plus}; - - use std::cmp::Ordering::{Less, Equal, Greater}; - use std::{f32, f64}; - use std::{i8, i16, i32, i64, isize}; - use std::iter::repeat; - use std::{u8, u16, u32, u64, usize}; - use std::ops::{Neg}; - - use rand::thread_rng; - - use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num}; - use Float; - - /// Assert that an op works for all val/ref combinations - macro_rules! assert_op { - ($left:ident $op:tt $right:ident == $expected:expr) => { - assert_eq!((&$left) $op (&$right), $expected); - assert_eq!((&$left) $op $right.clone(), $expected); - assert_eq!($left.clone() $op (&$right), $expected); - assert_eq!($left.clone() $op $right.clone(), $expected); - }; - } - - #[test] - fn test_from_biguint() { - fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) { - let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap()); - let ans = BigInt { sign: ans_s, data: FromPrimitive::from_usize(ans_n).unwrap()}; - assert_eq!(inp, ans); - } - check(Plus, 1, Plus, 1); - check(Plus, 0, NoSign, 0); - check(Minus, 1, Minus, 1); - check(NoSign, 1, NoSign, 0); - } - - #[test] - fn test_from_bytes_be() { - fn check(s: &str, result: &str) { - assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()), - BigInt::parse_bytes(result.as_bytes(), 10).unwrap()); - } - check("A", "65"); - check("AA", "16705"); - check("AB", "16706"); - check("Hello world!", "22405534230753963835153736737"); - assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero()); - assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero()); - } - - #[test] - fn test_to_bytes_be() { - fn check(s: &str, result: &str) { - let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); - let (sign, v) = b.to_bytes_be(); - assert_eq!((Plus, s.as_bytes()), (sign, &*v)); - } - check("A", "65"); - check("AA", "16705"); - check("AB", "16706"); - check("Hello world!", "22405534230753963835153736737"); - let b: BigInt = Zero::zero(); - assert_eq!(b.to_bytes_be(), (NoSign, vec![0])); - - // Test with leading/trailing zero bytes and a full BigDigit of value 0 - let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); - assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0])); - } - - #[test] - fn test_from_bytes_le() { - fn check(s: &str, result: &str) { - assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()), - BigInt::parse_bytes(result.as_bytes(), 10).unwrap()); - } - check("A", "65"); - check("AA", "16705"); - check("BA", "16706"); - check("!dlrow olleH", "22405534230753963835153736737"); - assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero()); - assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero()); - } - - #[test] - fn test_to_bytes_le() { - fn check(s: &str, result: &str) { - let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap(); - let (sign, v) = b.to_bytes_le(); - assert_eq!((Plus, s.as_bytes()), (sign, &*v)); - } - check("A", "65"); - check("AA", "16705"); - check("BA", "16706"); - check("!dlrow olleH", "22405534230753963835153736737"); - let b: BigInt = Zero::zero(); - assert_eq!(b.to_bytes_le(), (NoSign, vec![0])); - - // Test with leading/trailing zero bytes and a full BigDigit of value 0 - let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap(); - assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1])); - } - - #[test] - fn test_cmp() { - let vs: [&[BigDigit]; 4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ]; - let mut nums = Vec::new(); - for s in vs.iter().rev() { - nums.push(BigInt::from_slice(Minus, *s)); - } - nums.push(Zero::zero()); - nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); - - for (i, ni) in nums.iter().enumerate() { - for (j0, nj) in nums[i..].iter().enumerate() { - let j = i + j0; - if i == j { - assert_eq!(ni.cmp(nj), Equal); - assert_eq!(nj.cmp(ni), Equal); - assert_eq!(ni, nj); - assert!(!(ni != nj)); - assert!(ni <= nj); - assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); - } else { - assert_eq!(ni.cmp(nj), Less); - assert_eq!(nj.cmp(ni), Greater); - - assert!(!(ni == nj)); - assert!(ni != nj); - - assert!(ni <= nj); - assert!(!(ni >= nj)); - assert!(ni < nj); - assert!(!(ni > nj)); - - assert!(!(nj <= ni)); - assert!(nj >= ni); - assert!(!(nj < ni)); - assert!(nj > ni); - } - } - } - } - - - #[test] - fn test_hash() { - let a = BigInt::new(NoSign, vec!()); - let b = BigInt::new(NoSign, vec!(0)); - let c = BigInt::new(Plus, vec!(1)); - let d = BigInt::new(Plus, vec!(1,0,0,0,0,0)); - let e = BigInt::new(Plus, vec!(0,0,0,0,0,1)); - let f = BigInt::new(Minus, vec!(1)); - assert!(::hash(&a) == ::hash(&b)); - assert!(::hash(&b) != ::hash(&c)); - assert!(::hash(&c) == ::hash(&d)); - assert!(::hash(&d) != ::hash(&e)); - assert!(::hash(&c) != ::hash(&f)); - } - - #[test] - fn test_convert_i64() { - fn check(b1: BigInt, i: i64) { - let b2: BigInt = FromPrimitive::from_i64(i).unwrap(); - assert!(b1 == b2); - assert!(b1.to_i64().unwrap() == i); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(i64::MIN.to_bigint().unwrap(), i64::MIN); - check(i64::MAX.to_bigint().unwrap(), i64::MAX); - - assert_eq!( - (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(big_digit::BITS-1)))).to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(), - None); - } - - #[test] - fn test_convert_u64() { - fn check(b1: BigInt, u: u64) { - let b2: BigInt = FromPrimitive::from_u64(u).unwrap(); - assert!(b1 == b2); - assert!(b1.to_u64().unwrap() == u); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(u64::MIN.to_bigint().unwrap(), u64::MIN); - check(u64::MAX.to_bigint().unwrap(), u64::MAX); - - assert_eq!( - BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), - None); - - let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap(); - assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None); - assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None); - } - - #[test] - fn test_convert_f32() { - fn check(b1: &BigInt, f: f32) { - let b2 = BigInt::from_f32(f).unwrap(); - assert_eq!(b1, &b2); - assert_eq!(b1.to_f32().unwrap(), f); - let neg_b1 = -b1; - let neg_b2 = BigInt::from_f32(-f).unwrap(); - assert_eq!(neg_b1, neg_b2); - assert_eq!(neg_b1.to_f32().unwrap(), -f); - } - - check(&BigInt::zero(), 0.0); - check(&BigInt::one(), 1.0); - check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0); - check(&BigInt::from(1u64 << 32), 2.0.powi(32)); - check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); - check(&((BigInt::one() << 100) + (BigInt::one() << 123)), 2.0.powi(100) + 2.0.powi(123)); - check(&(BigInt::one() << 127), 2.0.powi(127)); - check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); - - // keeping all 24 digits with the bits at different offsets to the BigDigits - let x: u32 = 0b00000000101111011111011011011101; - let mut f = x as f32; - let mut b = BigInt::from(x); - for _ in 0..64 { - check(&b, f); - f *= 2.0; - b = b << 1; - } - - // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 - let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111; - assert!((n as f64) as f32 != n as f32); - assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); - n = -n; - assert!((n as f64) as f32 != n as f32); - assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); - - // test rounding up with the bits at different offsets to the BigDigits - let mut f = ((1u64 << 25) - 1) as f32; - let mut b = BigInt::from(1u64 << 25); - for _ in 0..64 { - assert_eq!(b.to_f32(), Some(f)); - f *= 2.0; - b = b << 1; - } - - // rounding - assert_eq!(BigInt::from_f32(-f32::consts::PI), Some(BigInt::from(-3i32))); - assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32))); - assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero())); - assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32))); - assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32))); - - // special float values - assert_eq!(BigInt::from_f32(f32::NAN), None); - assert_eq!(BigInt::from_f32(f32::INFINITY), None); - assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None); - - // largest BigInt that will round to a finite f32 value - let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25)); - assert_eq!(big_num.to_f32(), Some(f32::MAX)); - assert_eq!((&big_num + BigInt::one()).to_f32(), None); - assert_eq!((-&big_num).to_f32(), Some(f32::MIN)); - assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None); - - assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None); - assert_eq!((BigInt::one() << 128).to_f32(), None); - assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None); - assert_eq!((-(BigInt::one() << 128)).to_f32(), None); - } - - #[test] - fn test_convert_f64() { - fn check(b1: &BigInt, f: f64) { - let b2 = BigInt::from_f64(f).unwrap(); - assert_eq!(b1, &b2); - assert_eq!(b1.to_f64().unwrap(), f); - let neg_b1 = -b1; - let neg_b2 = BigInt::from_f64(-f).unwrap(); - assert_eq!(neg_b1, neg_b2); - assert_eq!(neg_b1.to_f64().unwrap(), -f); - } - - check(&BigInt::zero(), 0.0); - check(&BigInt::one(), 1.0); - check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0); - check(&BigInt::from(1u64 << 32), 2.0.powi(32)); - check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64)); - check(&((BigInt::one() << 100) + (BigInt::one() << 152)), 2.0.powi(100) + 2.0.powi(152)); - check(&(BigInt::one() << 1023), 2.0.powi(1023)); - check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); - - // keeping all 53 digits with the bits at different offsets to the BigDigits - let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; - let mut f = x as f64; - let mut b = BigInt::from(x); - for _ in 0..128 { - check(&b, f); - f *= 2.0; - b = b << 1; - } - - // test rounding up with the bits at different offsets to the BigDigits - let mut f = ((1u64 << 54) - 1) as f64; - let mut b = BigInt::from(1u64 << 54); - for _ in 0..128 { - assert_eq!(b.to_f64(), Some(f)); - f *= 2.0; - b = b << 1; - } - - // rounding - assert_eq!(BigInt::from_f64(-f64::consts::PI), Some(BigInt::from(-3i32))); - assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32))); - assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero())); - assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32))); - assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32))); - - // special float values - assert_eq!(BigInt::from_f64(f64::NAN), None); - assert_eq!(BigInt::from_f64(f64::INFINITY), None); - assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None); - - // largest BigInt that will round to a finite f64 value - let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54)); - assert_eq!(big_num.to_f64(), Some(f64::MAX)); - assert_eq!((&big_num + BigInt::one()).to_f64(), None); - assert_eq!((-&big_num).to_f64(), Some(f64::MIN)); - assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None); - - assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None); - assert_eq!((BigInt::one() << 1024).to_f64(), None); - assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None); - assert_eq!((-(BigInt::one() << 1024)).to_f64(), None); - } - - #[test] - fn test_convert_to_biguint() { - fn check(n: BigInt, ans_1: BigUint) { - assert_eq!(n.to_biguint().unwrap(), ans_1); - assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n); - } - let zero: BigInt = Zero::zero(); - let unsigned_zero: BigUint = Zero::zero(); - let positive = BigInt::from_biguint( - Plus, BigUint::new(vec!(1,2,3))); - let negative = -&positive; - - check(zero, unsigned_zero); - check(positive, BigUint::new(vec!(1,2,3))); - - assert_eq!(negative.to_biguint(), None); - } - - #[test] - fn test_convert_from_uint() { - macro_rules! check { - ($ty:ident, $max:expr) => { - assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); - assert_eq!(BigInt::from($ty::one()), BigInt::one()); - assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); - assert_eq!(BigInt::from($ty::MAX), $max); - } - } - - check!(u8, BigInt::from_slice(Plus, &[u8::MAX as BigDigit])); - check!(u16, BigInt::from_slice(Plus, &[u16::MAX as BigDigit])); - check!(u32, BigInt::from_slice(Plus, &[u32::MAX as BigDigit])); - check!(u64, BigInt::from_slice(Plus, &[u32::MAX as BigDigit, u32::MAX as BigDigit])); - check!(usize, BigInt::from(usize::MAX as u64)); - } - - #[test] - fn test_convert_from_int() { - macro_rules! check { - ($ty:ident, $min:expr, $max:expr) => { - assert_eq!(BigInt::from($ty::MIN), $min); - assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one()); - assert_eq!(BigInt::from(-$ty::one()), -BigInt::one()); - assert_eq!(BigInt::from($ty::zero()), BigInt::zero()); - assert_eq!(BigInt::from($ty::one()), BigInt::one()); - assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one()); - assert_eq!(BigInt::from($ty::MAX), $max); - } - } - - check!(i8, BigInt::from_slice(Minus, &[1 << 7]), - BigInt::from_slice(Plus, &[i8::MAX as BigDigit])); - check!(i16, BigInt::from_slice(Minus, &[1 << 15]), - BigInt::from_slice(Plus, &[i16::MAX as BigDigit])); - check!(i32, BigInt::from_slice(Minus, &[1 << 31]), - BigInt::from_slice(Plus, &[i32::MAX as BigDigit])); - check!(i64, BigInt::from_slice(Minus, &[0, 1 << 31]), - BigInt::from_slice(Plus, &[u32::MAX as BigDigit, i32::MAX as BigDigit])); - check!(isize, BigInt::from(isize::MIN as i64), - BigInt::from(isize::MAX as i64)); - } - - #[test] - fn test_convert_from_biguint() { - assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero()); - assert_eq!(BigInt::from(BigUint::one()), BigInt::one()); - assert_eq!(BigInt::from(BigUint::from_slice(&[1, 2, 3])), BigInt::from_slice(Plus, &[1, 2, 3])); - } - - const N1: BigDigit = -1i32 as BigDigit; - const N2: BigDigit = -2i32 as BigDigit; - - const SUM_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[ 1]), - (&[ 1], &[ 1], &[ 2]), - (&[ 1], &[ 1, 1], &[ 2, 1]), - (&[ 1], &[N1], &[ 0, 1]), - (&[ 1], &[N1, N1], &[ 0, 0, 1]), - (&[N1, N1], &[N1, N1], &[N2, N1, 1]), - (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]), - (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2]) - ]; - - #[test] - fn test_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let (na, nb, nc) = (-&a, -&b, -&c); - - assert_op!(a + b == c); - assert_op!(b + a == c); - assert_op!(c + na == b); - assert_op!(c + nb == a); - assert_op!(a + nc == nb); - assert_op!(b + nc == na); - assert_op!(na + nb == nc); - assert_op!(a + na == Zero::zero()); - } - } - - #[test] - fn test_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let (na, nb, nc) = (-&a, -&b, -&c); - - assert_op!(c - a == b); - assert_op!(c - b == a); - assert_op!(nb - a == nc); - assert_op!(na - b == nc); - assert_op!(b - na == c); - assert_op!(a - nb == c); - assert_op!(nc - na == nb); - assert_op!(a - a == Zero::zero()); - } - } - - const M: u32 = ::std::u32::MAX; - static MUL_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[]), - (&[ 2], &[], &[]), - (&[ 1], &[ 1], &[1]), - (&[ 2], &[ 3], &[ 6]), - (&[ 1], &[ 1, 1, 1], &[1, 1, 1]), - (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]), - (&[ 1, 1, 1], &[N1], &[N1, N1, N1]), - (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]), - (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]), - (&[N1], &[N1], &[ 1, N2]), - (&[N1, N1], &[N1], &[ 1, N1, N2]), - (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]), - (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]), - (&[ M/2 + 1], &[ 2], &[ 0, 1]), - (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]), - (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]), - (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]), - (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]), - (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]), - (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]) - ]; - - static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] - = &[ - (&[ 1], &[ 2], &[], &[1]), - (&[ 1, 1], &[ 2], &[ M/2+1], &[1]), - (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]), - (&[ 0, 1], &[N1], &[1], &[1]), - (&[N1, N1], &[N2], &[2, 1], &[3]) - ]; - - #[test] - fn test_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let (na, nb, nc) = (-&a, -&b, -&c); - - assert_op!(a * b == c); - assert_op!(b * a == c); - assert_op!(na * nb == c); - - assert_op!(na * b == nc); - assert_op!(nb * a == nc); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - assert!(a == &b * &c + &d); - assert!(a == &c * &b + &d); - } - } - - #[test] - fn test_div_mod_floor() { - fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { - let (d, m) = a.div_mod_floor(b); - if !m.is_zero() { - assert_eq!(m.sign, b.sign); - } - assert!(m.abs() <= b.abs()); - assert!(*a == b * &d + &m); - assert!(d == *ans_d); - assert!(m == *ans_m); - } - - fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) { - if m.is_zero() { - check_sub(a, b, d, m); - check_sub(a, &b.neg(), &d.neg(), m); - check_sub(&a.neg(), b, &d.neg(), m); - check_sub(&a.neg(), &b.neg(), d, m); - } else { - let one: BigInt = One::one(); - check_sub(a, b, d, m); - check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b)); - check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m)); - check_sub(&a.neg(), &b.neg(), d, &m.neg()); - } - } - - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } - if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - if !b.is_zero() { - check(&a, &b, &c, &d); - } - } - } - - - #[test] - fn test_div_rem() { - fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { - let (q, r) = a.div_rem(b); - if !r.is_zero() { - assert_eq!(r.sign, a.sign); - } - assert!(r.abs() <= b.abs()); - assert!(*a == b * &q + &r); - assert!(q == *ans_q); - assert!(r == *ans_r); - - let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone()); - assert_op!(a / b == ans_q); - assert_op!(a % b == ans_r); - } - - fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) { - check_sub(a, b, q, r); - check_sub(a, &b.neg(), &q.neg(), r); - check_sub(&a.neg(), b, &q.neg(), &r.neg()); - check_sub(&a.neg(), &b.neg(), q, &r.neg()); - } - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } - if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - if !b.is_zero() { - check(&a, &b, &c, &d); - } - } - } - - #[test] - fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a.checked_add(&b).unwrap() == c); - assert!(b.checked_add(&a).unwrap() == c); - assert!(c.checked_add(&(-&a)).unwrap() == b); - assert!(c.checked_add(&(-&b)).unwrap() == a); - assert!(a.checked_add(&(-&c)).unwrap() == (-&b)); - assert!(b.checked_add(&(-&c)).unwrap() == (-&a)); - assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c)); - assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero()); - } - } - - #[test] - fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(c.checked_sub(&a).unwrap() == b); - assert!(c.checked_sub(&b).unwrap() == a); - assert!((-&b).checked_sub(&a).unwrap() == (-&c)); - assert!((-&a).checked_sub(&b).unwrap() == (-&c)); - assert!(b.checked_sub(&(-&a)).unwrap() == c); - assert!(a.checked_sub(&(-&b)).unwrap() == c); - assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b)); - assert!(a.checked_sub(&a).unwrap() == Zero::zero()); - } - } - - #[test] - fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a.checked_mul(&b).unwrap() == c); - assert!(b.checked_mul(&a).unwrap() == c); - - assert!((-&a).checked_mul(&b).unwrap() == -&c); - assert!((-&b).checked_mul(&a).unwrap() == -&c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - assert!(a == b.checked_mul(&c).unwrap() + &d); - assert!(a == c.checked_mul(&b).unwrap() + &d); - } - } - #[test] - fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { - assert!(c.checked_div(&a).unwrap() == b); - assert!((-&c).checked_div(&(-&a)).unwrap() == b); - assert!((-&c).checked_div(&a).unwrap() == -&b); - } - if !b.is_zero() { - assert!(c.checked_div(&b).unwrap() == a); - assert!((-&c).checked_div(&(-&b)).unwrap() == a); - assert!((-&c).checked_div(&b).unwrap() == -&a); - } - - assert!(c.checked_div(&Zero::zero()).is_none()); - assert!((-&c).checked_div(&Zero::zero()).is_none()); - } - } - - #[test] - fn test_gcd() { - fn check(a: isize, b: isize, c: isize) { - let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); - let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); - let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); - - assert_eq!(big_a.gcd(&big_b), big_c); - } - - check(10, 2, 2); - check(10, 3, 1); - check(0, 3, 3); - check(3, 3, 3); - check(56, 42, 14); - check(3, -3, 3); - check(-6, 3, 3); - check(-4, -2, 2); - } - - #[test] - fn test_lcm() { - fn check(a: isize, b: isize, c: isize) { - let big_a: BigInt = FromPrimitive::from_isize(a).unwrap(); - let big_b: BigInt = FromPrimitive::from_isize(b).unwrap(); - let big_c: BigInt = FromPrimitive::from_isize(c).unwrap(); - - assert_eq!(big_a.lcm(&big_b), big_c); - } - - check(1, 0, 0); - check(0, 1, 0); - check(1, 1, 1); - check(-1, 1, 1); - check(1, -1, 1); - check(-1, -1, 1); - check(8, 9, 72); - check(11, 5, 55); - } - - #[test] - fn test_abs_sub() { - let zero: BigInt = Zero::zero(); - let one: BigInt = One::one(); - assert_eq!((-&one).abs_sub(&one), zero); - let one: BigInt = One::one(); - let zero: BigInt = Zero::zero(); - assert_eq!(one.abs_sub(&one), zero); - let one: BigInt = One::one(); - let zero: BigInt = Zero::zero(); - assert_eq!(one.abs_sub(&zero), one); - let one: BigInt = One::one(); - let two: BigInt = FromPrimitive::from_isize(2).unwrap(); - assert_eq!(one.abs_sub(&-&one), two); - } - - #[test] - fn test_from_str_radix() { - fn check(s: &str, ans: Option) { - let ans = ans.map(|n| { - let x: BigInt = FromPrimitive::from_isize(n).unwrap(); - x - }); - assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans); - } - check("10", Some(10)); - check("1", Some(1)); - check("0", Some(0)); - check("-1", Some(-1)); - check("-10", Some(-10)); - check("+10", Some(10)); - check("--7", None); - check("++5", None); - check("+-9", None); - check("-+3", None); - check("Z", None); - check("_", None); - - // issue 10522, this hit an edge case that caused it to - // attempt to allocate a vector of size (-1u) == huge. - let x: BigInt = - format!("1{}", repeat("0").take(36).collect::()).parse().unwrap(); - let _y = x.to_string(); - } - - #[test] - fn test_lower_hex() { - let a = BigInt::parse_bytes(b"A", 16).unwrap(); - let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:x}", a), "a"); - assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421"); - assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); - } - - #[test] - fn test_upper_hex() { - let a = BigInt::parse_bytes(b"A", 16).unwrap(); - let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:X}", a), "A"); - assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421"); - assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); - } - - #[test] - fn test_binary() { - let a = BigInt::parse_bytes(b"A", 16).unwrap(); - let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:b}", a), "1010"); - assert_eq!(format!("{:b}", hello), "-110010111100011011110011000101101001100011010011"); - assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); - } - - #[test] - fn test_octal() { - let a = BigInt::parse_bytes(b"A", 16).unwrap(); - let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{:o}", a), "12"); - assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041"); - assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); - } - - #[test] - fn test_display() { - let a = BigInt::parse_bytes(b"A", 16).unwrap(); - let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap(); - - assert_eq!(format!("{}", a), "10"); - assert_eq!(format!("{}", hello), "-22405534230753963835153736737"); - assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); - } - - #[test] - fn test_neg() { - assert!(-BigInt::new(Plus, vec!(1, 1, 1)) == - BigInt::new(Minus, vec!(1, 1, 1))); - assert!(-BigInt::new(Minus, vec!(1, 1, 1)) == - BigInt::new(Plus, vec!(1, 1, 1))); - let zero: BigInt = Zero::zero(); - assert_eq!(-&zero, zero); - } - - #[test] - fn test_rand() { - let mut rng = thread_rng(); - let _n: BigInt = rng.gen_bigint(137); - assert!(rng.gen_bigint(0).is_zero()); - } - - #[test] - fn test_rand_range() { - let mut rng = thread_rng(); - - for _ in 0..10 { - assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(), - &FromPrimitive::from_usize(237).unwrap()), - FromPrimitive::from_usize(236).unwrap()); - } - - fn check(l: BigInt, u: BigInt) { - let mut rng = thread_rng(); - for _ in 0..1000 { - let n: BigInt = rng.gen_bigint_range(&l, &u); - assert!(n >= l); - assert!(n < u); - } - } - let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap(); - let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap(); - check( l.clone(), u.clone()); - check(-l.clone(), u.clone()); - check(-u.clone(), -l.clone()); - } - - #[test] - #[should_panic] - fn test_zero_rand_range() { - thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(), - &FromPrimitive::from_isize(54).unwrap()); - } - - #[test] - #[should_panic] - fn test_negative_rand_range() { - let mut rng = thread_rng(); - let l = FromPrimitive::from_usize(2352).unwrap(); - let u = FromPrimitive::from_usize(3513).unwrap(); - // Switching u and l should fail: - let _n: BigInt = rng.gen_bigint_range(&u, &l); - } -} diff --git a/src/iter.rs b/src/iter.rs deleted file mode 100644 index 33bc267..0000000 --- a/src/iter.rs +++ /dev/null @@ -1,372 +0,0 @@ -// Copyright 2013-2014 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. - -//! External iterators for generic mathematics - -use {Integer, Zero, One, CheckedAdd, ToPrimitive}; -use std::ops::{Add, Sub}; - -/// An iterator over the range [start, stop) -#[derive(Clone)] -pub struct Range { - state: A, - stop: A, - one: A -} - -/// Returns an iterator over the given range [start, stop) (that is, starting -/// at start (inclusive), and ending at stop (exclusive)). -/// -/// # Example -/// -/// ```rust -/// use num::iter; -/// -/// let array = [0, 1, 2, 3, 4]; -/// -/// for i in iter::range(0, 5) { -/// println!("{}", i); -/// assert_eq!(i, array[i]); -/// } -/// ``` -#[inline] -pub fn range(start: A, stop: A) -> Range - where A: Add + PartialOrd + Clone + One -{ - Range{state: start, stop: stop, one: One::one()} -} - -// FIXME: rust-lang/rust#10414: Unfortunate type bound -impl Iterator for Range - where A: Add + PartialOrd + Clone + ToPrimitive -{ - type Item = A; - - #[inline] - fn next(&mut self) -> Option { - if self.state < self.stop { - let result = self.state.clone(); - self.state = self.state.clone() + self.one.clone(); - Some(result) - } else { - None - } - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - // This first checks if the elements are representable as i64. If they aren't, try u64 (to - // handle cases like range(huge, huger)). We don't use usize/int because the difference of - // the i64/u64 might lie within their range. - let bound = match self.state.to_i64() { - Some(a) => { - let sz = self.stop.to_i64().map(|b| b.checked_sub(a)); - match sz { - Some(Some(bound)) => bound.to_usize(), - _ => None, - } - }, - None => match self.state.to_u64() { - Some(a) => { - let sz = self.stop.to_u64().map(|b| b.checked_sub(a)); - match sz { - Some(Some(bound)) => bound.to_usize(), - _ => None - } - }, - None => None - } - }; - - match bound { - Some(b) => (b, Some(b)), - // Standard fallback for unbounded/unrepresentable bounds - None => (0, None) - } - } -} - -/// `Integer` is required to ensure the range will be the same regardless of -/// the direction it is consumed. -impl DoubleEndedIterator for Range - where A: Integer + Clone + ToPrimitive -{ - #[inline] - fn next_back(&mut self) -> Option { - if self.stop > self.state { - self.stop = self.stop.clone() - self.one.clone(); - Some(self.stop.clone()) - } else { - None - } - } -} - -/// An iterator over the range [start, stop] -#[derive(Clone)] -pub struct RangeInclusive { - range: Range, - done: bool, -} - -/// Return an iterator over the range [start, stop] -#[inline] -pub fn range_inclusive(start: A, stop: A) -> RangeInclusive - where A: Add + PartialOrd + Clone + One -{ - RangeInclusive{range: range(start, stop), done: false} -} - -impl Iterator for RangeInclusive - where A: Add + PartialOrd + Clone + ToPrimitive -{ - type Item = A; - - #[inline] - fn next(&mut self) -> Option { - match self.range.next() { - Some(x) => Some(x), - None => { - if !self.done && self.range.state == self.range.stop { - self.done = true; - Some(self.range.stop.clone()) - } else { - None - } - } - } - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - let (lo, hi) = self.range.size_hint(); - if self.done { - (lo, hi) - } else { - let lo = lo.saturating_add(1); - let hi = match hi { - Some(x) => x.checked_add(1), - None => None - }; - (lo, hi) - } - } -} - -impl DoubleEndedIterator for RangeInclusive - where A: Sub + Integer + Clone + ToPrimitive -{ - #[inline] - fn next_back(&mut self) -> Option { - if self.range.stop > self.range.state { - let result = self.range.stop.clone(); - self.range.stop = self.range.stop.clone() - self.range.one.clone(); - Some(result) - } else if !self.done && self.range.state == self.range.stop { - self.done = true; - Some(self.range.stop.clone()) - } else { - None - } - } -} - -/// An iterator over the range [start, stop) by `step`. It handles overflow by stopping. -#[derive(Clone)] -pub struct RangeStep { - state: A, - stop: A, - step: A, - rev: bool, -} - -/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping. -#[inline] -pub fn range_step(start: A, stop: A, step: A) -> RangeStep - where A: CheckedAdd + PartialOrd + Clone + Zero -{ - let rev = step < Zero::zero(); - RangeStep{state: start, stop: stop, step: step, rev: rev} -} - -impl Iterator for RangeStep - where A: CheckedAdd + PartialOrd + Clone -{ - type Item = A; - - #[inline] - fn next(&mut self) -> Option { - if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) { - let result = self.state.clone(); - match self.state.checked_add(&self.step) { - Some(x) => self.state = x, - None => self.state = self.stop.clone() - } - Some(result) - } else { - None - } - } -} - -/// An iterator over the range [start, stop] by `step`. It handles overflow by stopping. -#[derive(Clone)] -pub struct RangeStepInclusive { - state: A, - stop: A, - step: A, - rev: bool, - done: bool, -} - -/// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping. -#[inline] -pub fn range_step_inclusive(start: A, stop: A, step: A) -> RangeStepInclusive - where A: CheckedAdd + PartialOrd + Clone + Zero -{ - let rev = step < Zero::zero(); - RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false} -} - -impl Iterator for RangeStepInclusive - where A: CheckedAdd + PartialOrd + Clone + PartialEq -{ - type Item = A; - - #[inline] - fn next(&mut self) -> Option { - if !self.done && ((self.rev && self.state >= self.stop) || - (!self.rev && self.state <= self.stop)) { - let result = self.state.clone(); - match self.state.checked_add(&self.step) { - Some(x) => self.state = x, - None => self.done = true - } - Some(result) - } else { - None - } - } -} - -#[cfg(test)] -mod tests { - use std::usize; - use std::ops::{Add, Mul}; - use std::cmp::Ordering; - use {One, ToPrimitive}; - - #[test] - fn test_range() { - /// A mock type to check Range when ToPrimitive returns None - struct Foo; - - impl ToPrimitive for Foo { - fn to_i64(&self) -> Option { None } - fn to_u64(&self) -> Option { None } - } - - impl Add for Foo { - type Output = Foo; - - fn add(self, _: Foo) -> Foo { - Foo - } - } - - impl PartialEq for Foo { - fn eq(&self, _: &Foo) -> bool { - true - } - } - - impl PartialOrd for Foo { - fn partial_cmp(&self, _: &Foo) -> Option { - None - } - } - - impl Clone for Foo { - fn clone(&self) -> Foo { - Foo - } - } - - impl Mul for Foo { - type Output = Foo; - - fn mul(self, _: Foo) -> Foo { - Foo - } - } - - impl One for Foo { - fn one() -> Foo { - Foo - } - } - - assert!(super::range(0, 5).collect::>() == vec![0, 1, 2, 3, 4]); - assert!(super::range(-10, -1).collect::>() == - vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); - assert!(super::range(0, 5).rev().collect::>() == vec![4, 3, 2, 1, 0]); - assert_eq!(super::range(200, -5).count(), 0); - assert_eq!(super::range(200, -5).rev().count(), 0); - assert_eq!(super::range(200, 200).count(), 0); - assert_eq!(super::range(200, 200).rev().count(), 0); - - assert_eq!(super::range(0, 100).size_hint(), (100, Some(100))); - // this test is only meaningful when sizeof usize < sizeof u64 - assert_eq!(super::range(usize::MAX - 1, usize::MAX).size_hint(), (1, Some(1))); - assert_eq!(super::range(-10, -1).size_hint(), (9, Some(9))); - } - - #[test] - fn test_range_inclusive() { - assert!(super::range_inclusive(0, 5).collect::>() == - vec![0, 1, 2, 3, 4, 5]); - assert!(super::range_inclusive(0, 5).rev().collect::>() == - vec![5, 4, 3, 2, 1, 0]); - assert_eq!(super::range_inclusive(200, -5).count(), 0); - assert_eq!(super::range_inclusive(200, -5).rev().count(), 0); - assert!(super::range_inclusive(200, 200).collect::>() == vec![200]); - assert!(super::range_inclusive(200, 200).rev().collect::>() == vec![200]); - } - - #[test] - fn test_range_step() { - assert!(super::range_step(0, 20, 5).collect::>() == - vec![0, 5, 10, 15]); - assert!(super::range_step(20, 0, -5).collect::>() == - vec![20, 15, 10, 5]); - assert!(super::range_step(20, 0, -6).collect::>() == - vec![20, 14, 8, 2]); - assert!(super::range_step(200u8, 255, 50).collect::>() == - vec![200u8, 250]); - assert!(super::range_step(200, -5, 1).collect::>() == vec![]); - assert!(super::range_step(200, 200, 1).collect::>() == vec![]); - } - - #[test] - fn test_range_step_inclusive() { - assert!(super::range_step_inclusive(0, 20, 5).collect::>() == - vec![0, 5, 10, 15, 20]); - assert!(super::range_step_inclusive(20, 0, -5).collect::>() == - vec![20, 15, 10, 5, 0]); - assert!(super::range_step_inclusive(20, 0, -6).collect::>() == - vec![20, 14, 8, 2]); - assert!(super::range_step_inclusive(200u8, 255, 50).collect::>() == - vec![200u8, 250]); - assert!(super::range_step_inclusive(200, -5, 1).collect::>() == - vec![]); - assert!(super::range_step_inclusive(200, 200, 1).collect::>() == - vec![200]); - } -} From 37325eec7375879887adf39f8e0207accb7fa82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Fri, 25 Mar 2016 12:53:34 +0100 Subject: [PATCH 13/31] Remove unknown test flag --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 74a3a93..117ad50 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ CARGO_CMD ?= cargo packages = bigint integer rational traits test: - $(MAKE) run-all TASK="test --no-fail-fast" + $(MAKE) run-all TASK="test" run-all: $(packages) $(CARGO_CMD) $(TASK) From b73cfa57bbd80f982f45153e696bc3f02eda5886 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:12:56 -0700 Subject: [PATCH 14/31] traits: use `cast` items before `int` For some reason, rustc 1.0.0 can't find `PrimInt` if it's before `cast`, but later versions are fine with this. That may have been a compiler bug that was fixed. Switching the order seems to work everywhere. --- traits/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 366b1db..d89abe6 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -18,16 +18,16 @@ pub use identities::{Zero, One}; pub use ops::checked::*; pub use ops::saturating::Saturating; pub use sign::{Signed, Unsigned}; -pub use int::PrimInt; pub use cast::*; +pub use int::PrimInt; pub mod identities; pub mod sign; pub mod ops; pub mod bounds; pub mod float; -pub mod int; pub mod cast; +pub mod int; /// The base trait for numeric types pub trait Num: PartialEq + Zero + One From 529d7634dd21417b022461834dbc0590ff1ad305 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:22:02 -0700 Subject: [PATCH 15/31] num: use original num_foo crate names for imports Rust 1.0.0 can't seem to find `foo::bar` imports from renamed crates like `pub use num_foo as foo`. Use `num_foo::bar` instead. --- src/lib.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 4ba0ead..cd25dbd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -80,18 +80,18 @@ extern crate rand; extern crate serde; #[cfg(feature = "num-bigint")] -pub use bigint::{BigInt, BigUint}; +pub use num_bigint::{BigInt, BigUint}; #[cfg(feature = "num-rational")] -pub use rational::Rational; +pub use num_rational::Rational; #[cfg(all(feature = "num-rational", feature="num-bigint"))] -pub use rational::BigRational; +pub use num_rational::BigRational; #[cfg(feature = "num-complex")] -pub use complex::Complex; -pub use integer::Integer; -pub use iter::{range, range_inclusive, range_step, range_step_inclusive}; -pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded, - Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, - PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast}; +pub use num_complex::Complex; +pub use num_integer::Integer; +pub use num_iter::{range, range_inclusive, range_step, range_step_inclusive}; +pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded, + Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, + PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast}; #[cfg(test)] use std::hash; From 21a328ad6d36e3c2a8d29976b2fc008e31c22e7c Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:29:19 -0700 Subject: [PATCH 16/31] bigint, rational: use std::hash only for testing --- bigint/src/lib.rs | 1 + rational/src/lib.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index 4f5b0a3..443e8a2 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -79,6 +79,7 @@ use std::num::ParseIntError; use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub}; use std::str::{self, FromStr}; use std::fmt; +#[cfg(test)] use std::hash; use std::cmp::Ordering::{self, Less, Greater, Equal}; use std::{f32, f64}; diff --git a/rational/src/lib.rs b/rational/src/lib.rs index 09ecafb..529ff74 100644 --- a/rational/src/lib.rs +++ b/rational/src/lib.rs @@ -21,6 +21,7 @@ extern crate num_integer as integer; use std::cmp; use std::error::Error; use std::fmt; +#[cfg(test)] use std::hash; use std::ops::{Add, Div, Mul, Neg, Rem, Sub}; use std::str::FromStr; From 9d439e7860e7501d922cb402207cca877ada208f Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:33:34 -0700 Subject: [PATCH 17/31] num: don't need std::hash even for testing --- src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cd25dbd..0d594f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -93,8 +93,6 @@ pub use num_traits::{Num, Zero, One, Signed, Unsigned, Bounded, Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, PrimInt, Float, ToPrimitive, FromPrimitive, NumCast, cast}; -#[cfg(test)] use std::hash; - use std::ops::{Mul}; #[cfg(feature = "num-bigint")] From dac48aa4da25a49824943c838809da0368cf5282 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:34:23 -0700 Subject: [PATCH 18/31] test_nightly.sh: update the macros path --- .travis/test_nightly.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis/test_nightly.sh b/.travis/test_nightly.sh index 475dfc1..43a0fec 100755 --- a/.travis/test_nightly.sh +++ b/.travis/test_nightly.sh @@ -4,4 +4,4 @@ set -ex cargo bench --verbose -cargo test --verbose --manifest-path=num-macros/Cargo.toml +cargo test --verbose --manifest-path=macros/Cargo.toml From e672d006a4a3167a7d1e98fcd1408e4f31fccbba Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:39:26 -0700 Subject: [PATCH 19/31] iter: update testing imports --- iter/src/lib.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/iter/src/lib.rs b/iter/src/lib.rs index 8f567d7..76fafbd 100644 --- a/iter/src/lib.rs +++ b/iter/src/lib.rs @@ -31,11 +31,9 @@ pub struct Range { /// # Example /// /// ```rust -/// use num::iter; -/// /// let array = [0, 1, 2, 3, 4]; /// -/// for i in iter::range(0, 5) { +/// for i in num_iter::range(0, 5) { /// println!("{}", i); /// assert_eq!(i, array[i]); /// } @@ -265,7 +263,7 @@ mod tests { use std::usize; use std::ops::{Add, Mul}; use std::cmp::Ordering; - use {One, ToPrimitive}; + use traits::{One, ToPrimitive}; #[test] fn test_range() { From 8cb026e273dcc953f9369858faedc41b293eb794 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:39:45 -0700 Subject: [PATCH 20/31] complex: update testing imports and hash --- complex/src/lib.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/complex/src/lib.rs b/complex/src/lib.rs index 854fb34..b1a0603 100644 --- a/complex/src/lib.rs +++ b/complex/src/lib.rs @@ -13,6 +13,8 @@ extern crate num_traits as traits; use std::fmt; +#[cfg(test)] +use std::hash; use std::ops::{Add, Div, Mul, Neg, Sub}; #[cfg(feature = "serde")] @@ -594,6 +596,14 @@ impl serde::Deserialize for Complex where } } +#[cfg(test)] +fn hash(x: &T) -> u64 { + use std::hash::Hasher; + let mut hasher = hash::SipHasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + #[cfg(test)] mod test { #![allow(non_upper_case_globals)] @@ -601,7 +611,7 @@ mod test { use super::{Complex64, Complex}; use std::f64; - use {Zero, One, Float}; + use traits::{Zero, One, Float}; pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; @@ -994,7 +1004,7 @@ mod test { mod complex_arithmetic { use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts}; - use Zero; + use traits::Zero; #[test] fn test_add() { From 0114559adfca770dd506ef38fcadc6d184097abc Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:40:55 -0700 Subject: [PATCH 21/31] Makefile: add complex and iter --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 117ad50..bce28aa 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ CARGO_CMD ?= cargo -packages = bigint integer rational traits +packages = bigint complex integer iter rational traits test: $(MAKE) run-all TASK="test" From 8845ee11ed00fa5bd63c8205765d24dbda16a3cf Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 16:45:50 -0700 Subject: [PATCH 22/31] integer: reapply the rest of #167 --- integer/src/lib.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/integer/src/lib.rs b/integer/src/lib.rs index 5fdaf10..9c7e8aa 100644 --- a/integer/src/lib.rs +++ b/integer/src/lib.rs @@ -532,7 +532,7 @@ macro_rules! impl_integer_for_usize { /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] fn lcm(&self, other: &Self) -> Self { - (*self * *other) / self.gcd(other) + *self * (*other / self.gcd(other)) } /// Deprecated, use `is_multiple_of` instead. @@ -660,3 +660,31 @@ impl_integer_for_usize!(u16, test_integer_u16); impl_integer_for_usize!(u32, test_integer_u32); impl_integer_for_usize!(u64, test_integer_u64); impl_integer_for_usize!(usize, test_integer_usize); + +#[test] +fn test_lcm_overflow() { + macro_rules! check { + ($t:ty, $x:expr, $y:expr, $r:expr) => { { + let x: $t = $x; + let y: $t = $y; + let o = x.checked_mul(y); + assert!(o.is_none(), + "sanity checking that {} input {} * {} overflows", + stringify!($t), x, y); + assert_eq!(x.lcm(&y), $r); + assert_eq!(y.lcm(&x), $r); + } } + } + + // Original bug (Issue #166) + check!(i64, 46656000000000000, 600, 46656000000000000); + + check!(i8, 0x40, 0x04, 0x40); + check!(u8, 0x80, 0x02, 0x80); + check!(i16, 0x40_00, 0x04, 0x40_00); + check!(u16, 0x80_00, 0x02, 0x80_00); + check!(i32, 0x4000_0000, 0x04, 0x4000_0000); + check!(u32, 0x8000_0000, 0x02, 0x8000_0000); + check!(i64, 0x4000_0000_0000_0000, 0x04, 0x4000_0000_0000_0000); + check!(u64, 0x8000_0000_0000_0000, 0x02, 0x8000_0000_0000_0000); +} From aebbc4fd379b1bd2c4dfcaecad3c209774091c01 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 17:00:08 -0700 Subject: [PATCH 23/31] bigint: fix and un-ignore the first doctest --- bigint/src/lib.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index 443e8a2..dcd8aca 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -18,7 +18,11 @@ //! //! ## Example //! -//! ```rust,ignore +//! ```rust +//! extern crate num_bigint; +//! extern crate num_traits; +//! +//! # fn main() { //! use num_bigint::BigUint; //! use num_traits::{Zero, One}; //! use std::mem::replace; @@ -37,6 +41,7 @@ //! //! // This is a very large number. //! println!("fib(1000) = {}", fib(1000)); +//! # } //! ``` //! //! It's easy to generate large random numbers: From 03884fdbcc8783b29f96dabb59f9f781f53012ef Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 17:02:31 -0700 Subject: [PATCH 24/31] bigint: reapply #176 --- bigint/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index dcd8aca..5257e3a 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -2884,6 +2884,11 @@ impl BigInt { str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok()) } + /// Determines the fewest bits necessary to express the `BigInt`, + /// not including the sign. + pub fn bits(&self) -> usize { + self.data.bits() + } /// Converts this `BigInt` into a `BigUint`, if it's not negative. #[inline] From c9d82acf00044138ae88fd3fde3dc9e6a96e693a Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 17:05:10 -0700 Subject: [PATCH 25/31] test_features.sh: re-enable as a simple build --- .travis.yml | 1 + .travis/test_features.sh | 2 +- src/lib.rs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index beadc77..f4900c3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,7 @@ rust: sudo: false script: - make test + - .travis/test_features.sh - | [ $TRAVIS_RUST_VERSION != nightly ] || .travis/test_nightly.sh - cargo doc diff --git a/.travis/test_features.sh b/.travis/test_features.sh index 5ff01c0..109fd50 100755 --- a/.travis/test_features.sh +++ b/.travis/test_features.sh @@ -3,5 +3,5 @@ set -ex for feature in '' bigint rational complex; do - cargo test --verbose --no-default-features --features="$feature" + cargo build --verbose --no-default-features --features="$feature" done diff --git a/src/lib.rs b/src/lib.rs index 0d594f1..b928e43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,6 +97,7 @@ use std::ops::{Mul}; #[cfg(feature = "num-bigint")] pub use num_bigint as bigint; +#[cfg(feature = "num-complex")] pub use num_complex as complex; pub use num_integer as integer; pub use num_iter as iter; From 015cd0be43af00430cb3246ffc70797f8f817010 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 17:11:04 -0700 Subject: [PATCH 26/31] .travis.yml: add a verbose build I like to have a verbose build log for automation like Travis CI, because it sometimes helps in diagnosing failures. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index f4900c3..80df3af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ rust: - nightly sudo: false script: + - cargo build --verbose - make test - .travis/test_features.sh - | From a423b398332090edc87fc2a01a70e2b5f56b8ee4 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 25 Mar 2016 17:15:15 -0700 Subject: [PATCH 27/31] .multirust.sh: use the subcrated "make test" --- .multirust.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.multirust.sh b/.multirust.sh index 06cfef2..0372bca 100755 --- a/.multirust.sh +++ b/.multirust.sh @@ -7,7 +7,7 @@ set -ex for toolchain in 1.0.0 beta nightly; do run="multirust run $toolchain" $run cargo build --verbose - $run cargo test --verbose + $run make test $run .travis/test_features.sh if [ $toolchain = nightly ]; then $run .travis/test_nightly.sh From 3d11940538fb81f94886a9f193c72a2b70d3221f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Sun, 10 Apr 2016 10:31:11 +0200 Subject: [PATCH 28/31] Better descriptions for subcrates --- Cargo.toml | 2 +- bigint/Cargo.toml | 2 +- complex/Cargo.toml | 2 +- integer/Cargo.toml | 2 +- iter/Cargo.toml | 2 +- macros/Cargo.toml | 4 +--- rational/Cargo.toml | 2 +- traits/Cargo.toml | 2 +- 8 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e35c26c..0727ba4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Metapackage exposing legacy interface of all `rust-num` crates" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/bigint/Cargo.toml b/bigint/Cargo.toml index 883fb50..56666af 100644 --- a/bigint/Cargo.toml +++ b/bigint/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Big integer implementation for Rust" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/complex/Cargo.toml b/complex/Cargo.toml index 3dc0a52..3b1f640 100644 --- a/complex/Cargo.toml +++ b/complex/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Complex numbers implementation for Rust" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/integer/Cargo.toml b/integer/Cargo.toml index 413a99b..e98b258 100644 --- a/integer/Cargo.toml +++ b/integer/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Integer traits and functions" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/iter/Cargo.toml b/iter/Cargo.toml index e36b457..4cb0561 100644 --- a/iter/Cargo.toml +++ b/iter/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "External iterators for generic mathematics" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/macros/Cargo.toml b/macros/Cargo.toml index c543038..427b6f2 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -7,9 +7,7 @@ homepage = "https://github.com/rust-num/num" repository = "https://github.com/rust-num/num" documentation = "http://rust-num.github.io/num" keywords = ["mathematics", "numerics"] -description = """ -Numeric syntax extensions. -""" +description = "Numeric syntax extensions" [lib] name = "num_macros" diff --git a/rational/Cargo.toml b/rational/Cargo.toml index 10b51f8..9ef95ae 100644 --- a/rational/Cargo.toml +++ b/rational/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Rational numbers implementation for Rust" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] diff --git a/traits/Cargo.toml b/traits/Cargo.toml index ab72a01..0bfa8ac 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" +description = "Numeric traits for generic mathematics" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] From 8450782413c901e87f4d4878d9cc9490ba8e900b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Mon, 11 Apr 2016 12:30:16 +0200 Subject: [PATCH 29/31] Revert old `num` crate description --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 0727ba4..e35c26c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] authors = ["The Rust Project Developers"] -description = "Metapackage exposing legacy interface of all `rust-num` crates" +description = "A collection of numeric types and traits for Rust, including bigint,\ncomplex, rational, range iterators, generic integers, and more!\n" documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] From e59ead7b3a44d33ce07ab89c2d749f02dd6e15cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Mon, 11 Apr 2016 12:32:10 +0200 Subject: [PATCH 30/31] Add Serde crate to `num_bigint` --- bigint/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index 5257e3a..74d7576 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -72,6 +72,8 @@ #[cfg(any(feature = "rand", test))] extern crate rand; +#[cfg(feature = "serde")] +extern crate serde; extern crate num_integer as integer; extern crate num_traits as traits; From 58b5fe58833ba9e97ec69241bec4ee4473bf7a17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Jan=20Niemier?= Date: Mon, 11 Apr 2016 20:43:07 +0200 Subject: [PATCH 31/31] Serializers dependencies --- Cargo.toml | 25 ++++++++++++------------- bigint/Cargo.toml | 8 ++++++-- bigint/src/lib.rs | 2 ++ complex/Cargo.toml | 14 +++++++++++++- complex/src/lib.rs | 6 ++++++ rational/Cargo.toml | 8 ++++++-- rational/src/lib.rs | 2 ++ src/lib.rs | 12 ------------ 8 files changed, 47 insertions(+), 30 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e35c26c..fdb939a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,18 +40,6 @@ path = "rational" [dependencies.num-traits] path = "./traits" -[dependencies.rand] -optional = true -version = "0.3.8" - -[dependencies.rustc-serialize] -optional = true -version = "0.3.13" - -[dependencies.serde] -optional = true -version = "^0.7.0" - [dev-dependencies] [dev-dependencies.rand] @@ -61,4 +49,15 @@ version = "0.3.8" bigint = ["num-bigint"] complex = ["num-complex"] rational = ["num-rational"] -default = ["bigint", "complex", "rand", "rational", "rustc-serialize"] +default = ["bigint", "complex", "rational", "rustc-serialize"] + +serde = [ + "num-bigint/serde", + "num-complex/serde", + "num-rational/serde" +] +rustc-serialize = [ + "num-bigint/rustc-serialize", + "num-complex/rustc-serialize", + "num-rational/rustc-serialize" +] diff --git a/bigint/Cargo.toml b/bigint/Cargo.toml index 56666af..2d2dda0 100644 --- a/bigint/Cargo.toml +++ b/bigint/Cargo.toml @@ -5,8 +5,8 @@ documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num" name = "num-bigint" +repository = "https://github.com/rust-num/num" version = "0.1.0" [dependencies] @@ -21,9 +21,13 @@ path = "../traits" optional = true version = "0.3.14" +[dependencies.rustc-serialize] +optional = true +version = "0.3.19" + [dependencies.serde] optional = true version = "0.7.0" [features] -default = ["rand"] +default = ["rand", "rustc-serialize"] diff --git a/bigint/src/lib.rs b/bigint/src/lib.rs index 74d7576..effb3ab 100644 --- a/bigint/src/lib.rs +++ b/bigint/src/lib.rs @@ -72,6 +72,8 @@ #[cfg(any(feature = "rand", test))] extern crate rand; +#[cfg(feature = "rustc-serialize")] +extern crate rustc_serialize; #[cfg(feature = "serde")] extern crate serde; diff --git a/complex/Cargo.toml b/complex/Cargo.toml index 3b1f640..854128e 100644 --- a/complex/Cargo.toml +++ b/complex/Cargo.toml @@ -5,8 +5,8 @@ documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num" name = "num-complex" +repository = "https://github.com/rust-num/num" version = "0.1.0" [dependencies] @@ -14,3 +14,15 @@ version = "0.1.0" [dependencies.num-traits] optional = false path = "../traits" + +[dependencies.rustc-serialize] +optional = true +version = "0.3.19" + +[dependencies.serde] +optional = true +version = "^0.7.0" + +[features] +default = ["rustc-serialize"] +unstable = [] diff --git a/complex/src/lib.rs b/complex/src/lib.rs index b1a0603..333e552 100644 --- a/complex/src/lib.rs +++ b/complex/src/lib.rs @@ -12,6 +12,12 @@ extern crate num_traits as traits; +#[cfg(feature = "rustc-serialize")] +extern crate rustc_serialize; + +#[cfg(feature = "serde")] +extern crate serde; + use std::fmt; #[cfg(test)] use std::hash; diff --git a/rational/Cargo.toml b/rational/Cargo.toml index 9ef95ae..1fa46e3 100644 --- a/rational/Cargo.toml +++ b/rational/Cargo.toml @@ -5,8 +5,8 @@ documentation = "http://rust-num.github.io/num" homepage = "https://github.com/rust-num/num" keywords = ["mathematics", "numerics"] license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num" name = "num-rational" +repository = "https://github.com/rust-num/num" version = "0.1.0" [dependencies] @@ -21,10 +21,14 @@ path = "../integer" [dependencies.num-traits] path = "../traits" +[dependencies.rustc-serialize] +optional = true +version = "0.3.19" + [dependencies.serde] optional = true version = "0.7.0" [features] -default = ["bigint"] +default = ["bigint", "rustc-serialize"] bigint = ["num-bigint"] diff --git a/rational/src/lib.rs b/rational/src/lib.rs index 529ff74..f6e2cbd 100644 --- a/rational/src/lib.rs +++ b/rational/src/lib.rs @@ -10,6 +10,8 @@ //! Rational numbers +#[cfg(feature = "rustc-serialize")] +extern crate rustc_serialize; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "num-bigint")] diff --git a/src/lib.rs b/src/lib.rs index b928e43..97d0fc1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,18 +67,6 @@ pub extern crate num_bigint; #[cfg(feature = "num-rational")] pub extern crate num_rational; -#[cfg(feature = "rustc-serialize")] -extern crate rustc_serialize; - -// Some of the tests of non-RNG-based functionality are randomized using the -// RNG-based functionality, so the RNG-based functionality needs to be enabled -// for tests. -#[cfg(any(feature = "rand", all(feature = "bigint", test)))] -extern crate rand; - -#[cfg(feature = "serde")] -extern crate serde; - #[cfg(feature = "num-bigint")] pub use num_bigint::{BigInt, BigUint}; #[cfg(feature = "num-rational")]