Deprecate Zero and One traits

This commit is contained in:
Brendan Zabarauskas 2014-11-10 09:35:53 +11:00
parent 0da49dcf13
commit 46333d527b
28 changed files with 233 additions and 230 deletions

View File

@ -228,7 +228,7 @@ impl Iterator<(uint, uint)> for ElementSwaps {
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// For a vector of size n, there are exactly n! permutations.
let n = range(2, self.sdir.len() + 1).product();
let n = range(2, self.sdir.len() + 1).product(1);
(n - self.swaps_made, Some(n - self.swaps_made))
}
}

View File

@ -116,7 +116,7 @@ impl<S: Str> StrVector for [S] {
}
// `len` calculation may overflow but push_str will check boundaries
let len = self.iter().map(|s| s.as_slice().len()).sum();
let len = self.iter().map(|s| s.as_slice().len()).sum(0);
let mut result = String::with_capacity(len);
@ -140,7 +140,7 @@ impl<S: Str> StrVector for [S] {
// this is wrong without the guarantee that `self` is non-empty
// `len` calculation may overflow but push_str but will check boundaries
let len = sep.len() * (self.len() - 1)
+ self.iter().map(|s| s.as_slice().len()).sum();
+ self.iter().map(|s| s.as_slice().len()).sum(0);
let mut result = String::with_capacity(len);
let mut first = true;
@ -2151,7 +2151,7 @@ mod tests {
#[test]
fn test_str_container() {
fn sum_len(v: &[&str]) -> uint {
v.iter().map(|x| x.len()).sum()
v.iter().map(|x| x.len()).sum(0)
}
let s = String::from_str("01234");

View File

@ -14,7 +14,7 @@ use char;
use fmt;
use iter::{range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use num::cast;
use result::Ok;
use slice::{mod, SlicePrelude};
use str::StrPrelude;
@ -97,8 +97,8 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
_ => ()
}
let _0: T = Zero::zero();
let _1: T = One::one();
let _0: T = Float::zero();
let _1: T = Float::one();
match num.classify() {
FPNaN => return f("NaN".as_bytes()),

View File

@ -16,7 +16,7 @@
use fmt;
use iter::DoubleEndedIterator;
use num::{Int, cast, zero};
use num::{Int, cast};
use slice::SlicePrelude;
/// A type that represents a specific radix
@ -38,7 +38,7 @@ trait GenericRadix {
let mut buf = [0u8, ..64];
let base = cast(self.base()).unwrap();
let mut curr = buf.len();
let is_positive = x >= zero();
let is_positive = x >= Int::zero();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
@ -47,7 +47,7 @@ trait GenericRadix {
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero() { break; } // No more digits left to accumulate.
if x == Int::zero() { break; } // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
@ -56,7 +56,7 @@ trait GenericRadix {
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero() { break; } // No more digits left to accumulate.
if x == Int::zero() { break; } // No more digits left to accumulate.
}
}
f.pad_integral(is_positive, self.prefix(), buf[curr..])

View File

@ -60,10 +60,10 @@ This `for` loop syntax can be applied to any iterator over any type.
use clone::Clone;
use cmp;
use cmp::{PartialOrd, Ord};
use cmp::Ord;
use mem;
use num::{Zero, One, ToPrimitive, Int};
use ops::{Add, Mul, Sub};
use num::{ToPrimitive, Int};
use ops::{Add, Mul};
use option::{Option, Some, None};
use uint;
#[deprecated = "renamed to Extend"] pub use self::Extend as Extendable;
@ -402,7 +402,7 @@ pub trait Iterator<A> {
/// .inspect(|&x| println!("filtering {}", x))
/// .filter(|&x| x % 2 == 0)
/// .inspect(|&x| println!("{} made it through", x))
/// .sum();
/// .sum(0);
/// println!("{}", sum);
/// ```
#[inline]
@ -780,16 +780,15 @@ pub trait AdditiveIterator<A> {
///
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15);
/// assert!(it.sum(0) == 15);
/// ```
fn sum(&mut self) -> A;
fn sum(&mut self, init: A) -> A;
}
impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
impl<A: Add<A, A>, T: Iterator<A>> AdditiveIterator<A> for T {
#[inline]
fn sum(&mut self) -> A {
let zero: A = Zero::zero();
self.fold(zero, |s, x| s + x)
fn sum(&mut self, init: A) -> A {
self.fold(init, |s, x| s + x)
}
}
@ -803,20 +802,19 @@ pub trait MultiplicativeIterator<A> {
/// use std::iter::{count, MultiplicativeIterator};
///
/// fn factorial(n: uint) -> uint {
/// count(1u, 1).take_while(|&i| i <= n).product()
/// count(1u, 1).take_while(|&i| i <= n).product(1)
/// }
/// assert!(factorial(0) == 1);
/// assert!(factorial(1) == 1);
/// assert!(factorial(5) == 120);
/// ```
fn product(&mut self) -> A;
fn product(&mut self, init: A) -> A;
}
impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
impl<A: Mul<A, A>, T: Iterator<A>> MultiplicativeIterator<A> for T {
#[inline]
fn product(&mut self) -> A {
let one: A = One::one();
self.fold(one, |p, x| p * x)
fn product(&mut self, init: A) -> A {
self.fold(init, |p, x| p * x)
}
}
@ -1905,7 +1903,7 @@ impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
pub struct Range<A> {
state: A,
stop: A,
one: A
one: A,
}
/// Returns an iterator over the given range [start, stop) (that is, starting
@ -1922,12 +1920,16 @@ pub struct Range<A> {
/// }
/// ```
#[inline]
pub fn range<A: Add<A, A> + PartialOrd + Clone + One>(start: A, stop: A) -> Range<A> {
Range{state: start, stop: stop, one: One::one()}
pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
Range {
state: start,
stop: stop,
one: Int::one(),
}
}
// FIXME: #10414: Unfortunate type bound
impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for Range<A> {
impl<A: Int + ToPrimitive> Iterator<A> for Range<A> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.state < self.stop {
@ -1974,7 +1976,7 @@ impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for Range<A> {
/// `Int` is required to ensure the range will be the same regardless of
/// the direction it is consumed.
impl<A: Int + PartialOrd + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.stop > self.state {
@ -1995,12 +1997,14 @@ pub struct RangeInclusive<A> {
/// Return an iterator over the range [start, stop]
#[inline]
pub fn range_inclusive<A: Add<A, A> + PartialOrd + Clone + One>(start: A, stop: A)
-> RangeInclusive<A> {
RangeInclusive{range: range(start, stop), done: false}
pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
RangeInclusive {
range: range(start, stop),
done: false,
}
}
impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> {
impl<A: Int + ToPrimitive> Iterator<A> for RangeInclusive<A> {
#[inline]
fn next(&mut self) -> Option<A> {
match self.range.next() {
@ -2032,8 +2036,7 @@ impl<A: Add<A, A> + PartialOrd + Clone + ToPrimitive> Iterator<A> for RangeInclu
}
}
impl<A: Sub<A, A> + Int + PartialOrd + Clone + ToPrimitive> DoubleEndedIterator<A>
for RangeInclusive<A> {
impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for RangeInclusive<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.range.stop > self.range.state {
@ -2061,7 +2064,7 @@ pub struct RangeStep<A> {
/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
let rev = step < Zero::zero();
let rev = step < Int::zero();
RangeStep{state: start, stop: stop, step: step, rev: rev}
}
@ -2094,8 +2097,14 @@ pub struct RangeStepInclusive<A> {
/// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
let rev = step < Zero::zero();
RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
let rev = step < Int::zero();
RangeStepInclusive {
state: start,
stop: stop,
step: step,
rev: rev,
done: false,
}
}
impl<A: Int> Iterator<A> for RangeStepInclusive<A> {

View File

@ -114,9 +114,15 @@ impl Float for f32 {
#[inline]
fn neg_infinity() -> f32 { NEG_INFINITY }
#[inline]
fn zero() -> f32 { 0.0 }
#[inline]
fn neg_zero() -> f32 { -0.0 }
#[inline]
fn one() -> f32 { 1.0 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self != self }

View File

@ -120,9 +120,15 @@ impl Float for f64 {
#[inline]
fn neg_infinity() -> f64 { NEG_INFINITY }
#[inline]
fn zero() -> f64 { 0.0 }
#[inline]
fn neg_zero() -> f64 { -0.0 }
#[inline]
fn one() -> f64 { 1.0 }
/// Returns `true` if the number is NaN.
#[inline]
fn is_nan(self) -> bool { self != self }

View File

@ -27,6 +27,7 @@ use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
use option::{Option, Some, None};
/// The base trait for numeric types
#[allow(deprecated)]
pub trait Num: PartialEq + Zero + One
+ Neg<Self>
+ Add<Self,Self>
@ -49,112 +50,6 @@ pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
(x / y, x % y)
}
/// Defines an additive identity element for `Self`.
///
/// # Deriving
///
/// This trait can be automatically be derived using `#[deriving(Zero)]`
/// attribute. If you choose to use this, make sure that the laws outlined in
/// the documentation for `Zero::zero` still hold.
pub trait Zero: Add<Self, Self> {
/// 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!(uint, 0u)
zero_impl!(u8, 0u8)
zero_impl!(u16, 0u16)
zero_impl!(u32, 0u32)
zero_impl!(u64, 0u64)
zero_impl!(int, 0i)
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)
/// Returns the additive identity, `0`.
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
/// Defines a multiplicative identity element for `Self`.
pub trait One: Mul<Self, Self> {
/// 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!(uint, 1u)
one_impl!(u8, 1u8)
one_impl!(u16, 1u16)
one_impl!(u32, 1u32)
one_impl!(u64, 1u64)
one_impl!(int, 1i)
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)
/// Returns the multiplicative identity, `1`.
#[inline(always)] pub fn one<T: One>() -> T { One::one() }
/// Useful functions for signed numbers (i.e. numbers that can be negative).
pub trait Signed: Num + Neg<Self> {
/// Computes the absolute value.
@ -281,10 +176,10 @@ trait_impl!(Unsigned for uint u8 u16 u32 u64)
/// assert_eq!(num::pow(2i, 4), 16);
/// ```
#[inline]
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
pub fn pow<T: Int>(mut base: T, mut exp: uint) -> T {
if exp == 1 { base }
else {
let mut acc = one::<T>();
let mut acc: T = Int::one();
while exp > 0 {
if (exp & 1) == 1 {
acc = acc * base;
@ -317,6 +212,14 @@ pub trait Int: Primitive
+ BitXor<Self,Self>
+ Shl<uint,Self>
+ Shr<uint,Self> {
/// Returns the `0` value of this integer.
// FIXME (#5527): Should be an associated constant
fn zero() -> Self;
/// Returns the `1` value of this integer.
// FIXME (#5527): Should be an associated constant
fn one() -> Self;
/// Returns the smallest value that can be represented by this integer.
// FIXME (#5527): Should be and associated constant
fn min_value() -> Self;
@ -551,9 +454,9 @@ pub trait Int: Primitive
#[inline]
fn saturating_add(self, other: Self) -> Self {
match self.checked_add(other) {
Some(x) => x,
None if other >= Zero::zero() => Int::max_value(),
None => Int::min_value(),
Some(x) => x,
None if other >= Int::zero() => Int::max_value(),
None => Int::min_value(),
}
}
@ -562,9 +465,9 @@ pub trait Int: Primitive
#[inline]
fn saturating_sub(self, other: Self) -> Self {
match self.checked_sub(other) {
Some(x) => x,
None if other >= Zero::zero() => Int::min_value(),
None => Int::max_value(),
Some(x) => x,
None if other >= Int::zero() => Int::min_value(),
None => Int::max_value(),
}
}
}
@ -586,6 +489,12 @@ macro_rules! uint_impl {
$sub_with_overflow:path,
$mul_with_overflow:path) => {
impl Int for $T {
#[inline]
fn zero() -> $T { 0 }
#[inline]
fn one() -> $T { 1 }
#[inline]
fn min_value() -> $T { 0 }
@ -710,6 +619,12 @@ macro_rules! int_impl {
$sub_with_overflow:path,
$mul_with_overflow:path) => {
impl Int for $T {
#[inline]
fn zero() -> $T { 0 }
#[inline]
fn one() -> $T { 1 }
#[inline]
fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
@ -798,20 +713,20 @@ int_impl!(int = i64, u64, 64,
pub trait UnsignedInt: Int {
/// Returns `true` iff `self == 2^k` for some `k`.
fn is_power_of_two(self) -> bool {
(self - one()) & self == zero()
(self - Int::one()) & self == Int::zero()
}
/// Returns the smallest power of two greater than or equal to `self`.
#[inline]
fn next_power_of_two(self) -> Self {
let halfbits = size_of::<Self>() * 4;
let mut tmp = self - one();
let mut tmp = self - Int::one();
let mut shift = 1u;
while shift <= halfbits {
tmp = tmp | (tmp >> shift);
shift = shift << 1u;
}
tmp + one()
tmp + Int::one()
}
/// Returns the smallest power of two greater than or equal to `n`. If the
@ -819,13 +734,13 @@ pub trait UnsignedInt: Int {
/// returned, otherwise the power of two is wrapped in `Some`.
fn checked_next_power_of_two(self) -> Option<Self> {
let halfbits = size_of::<Self>() * 4;
let mut tmp = self - one();
let mut tmp = self - Int::one();
let mut shift = 1u;
while shift <= halfbits {
tmp = tmp | (tmp >> shift);
shift = shift << 1u;
}
tmp.checked_add(one())
tmp.checked_add(Int::one())
}
}
@ -927,7 +842,7 @@ macro_rules! impl_to_primitive_int_to_int(
macro_rules! impl_to_primitive_int_to_uint(
($SrcT:ty, $DstT:ty, $slf:expr) => (
{
let zero: $SrcT = Zero::zero();
let zero: $SrcT = Int::zero();
let max_value: $DstT = Int::max_value();
if zero <= $slf && $slf as u64 <= max_value as u64 {
Some($slf as $DstT)
@ -996,7 +911,7 @@ macro_rules! impl_to_primitive_uint_to_uint(
if size_of::<$SrcT>() <= size_of::<$DstT>() {
Some($slf as $DstT)
} else {
let zero: $SrcT = Zero::zero();
let zero: $SrcT = Int::zero();
let max_value: $DstT = Int::max_value();
if zero <= $slf && $slf as u64 <= max_value as u64 {
Some($slf as $DstT)
@ -1351,8 +1266,12 @@ pub trait Float: Signed + Primitive {
fn infinity() -> Self;
/// Returns the negative infinite value.
fn neg_infinity() -> Self;
/// Returns the `0` value.
fn zero() -> Self;
/// Returns -0.0.
fn neg_zero() -> Self;
/// Returns the `1` value.
fn one() -> Self;
/// Returns true if this value is NaN and false otherwise.
fn is_nan(self) -> bool;
@ -1485,6 +1404,65 @@ pub trait Float: Signed + Primitive {
// DEPRECATED
#[deprecated = "The generic `Zero` trait will be removed soon."]
pub trait Zero: Add<Self, Self> {
#[deprecated = "Use `Int::zero()` or `Float::zero()`."]
fn zero() -> Self;
#[deprecated = "Use `x == Int::zero()` or `x == Float::zero()`."]
fn is_zero(&self) -> bool;
}
#[deprecated = "Use `Int::zero()` or `Float::zero()`."]
#[allow(deprecated)]
pub fn zero<T: Zero>() -> T { Zero::zero() }
macro_rules! zero_impl {
($t:ty, $v:expr) => {
impl Zero for $t {
fn zero() -> $t { $v }
fn is_zero(&self) -> bool { *self == $v }
}
}
}
zero_impl!(uint, 0u)
zero_impl!(u8, 0u8)
zero_impl!(u16, 0u16)
zero_impl!(u32, 0u32)
zero_impl!(u64, 0u64)
zero_impl!(int, 0i)
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)
#[deprecated = "The generic `One` trait will be removed soon."]
pub trait One: Mul<Self, Self> {
#[deprecated = "Use `Int::one()` or `Float::one()`."]
fn one() -> Self;
}
#[deprecated = "Use `Int::one()` or `Float::one()`."]
#[allow(deprecated)]
pub fn one<T: One>() -> T { One::one() }
macro_rules! one_impl {
($t:ty, $v:expr) => {
impl One for $t {
fn one() -> $t { $v }
}
}
}
one_impl!(uint, 1u)
one_impl!(u8, 1u8)
one_impl!(u16, 1u16)
one_impl!(u32, 1u32)
one_impl!(u64, 1u64)
one_impl!(int, 1i)
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)
#[deprecated = "Use `Signed::abs`"]
pub fn abs<T: Signed>(value: T) -> T {
value.abs()

View File

@ -294,17 +294,17 @@ fn test_iterator_len() {
#[test]
fn test_iterator_sum() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[0..4].iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v[0..0].iter().map(|&x| x).sum(), 0);
assert_eq!(v[0..4].iter().map(|&x| x).sum(0), 6);
assert_eq!(v.iter().map(|&x| x).sum(0), 55);
assert_eq!(v[0..0].iter().map(|&x| x).sum(0), 0);
}
#[test]
fn test_iterator_product() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v[0..4].iter().map(|&x| x).product(), 0);
assert_eq!(v[1..5].iter().map(|&x| x).product(), 24);
assert_eq!(v[0..0].iter().map(|&x| x).product(), 1);
assert_eq!(v[0..4].iter().map(|&x| x).product(1), 0);
assert_eq!(v[1..5].iter().map(|&x| x).product(1), 24);
assert_eq!(v[0..0].iter().map(|&x| x).product(1), 1);
}
#[test]

View File

@ -69,7 +69,7 @@ impl<'a> fmt::Show for Matrix<'a> {
pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0u)
}).collect();
let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
let total_width = column_widths.iter().map(|n| *n).sum(0) + column_count * 3 + 1;
let br = String::from_char(total_width, '+');
try!(write!(f, "{}\n", br));
for row in pretty_printed_matrix.into_iter() {

View File

@ -756,7 +756,7 @@ fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<uint> {
let total_score = m.iter()
.map(|row| row.pats[col])
.map(|pat| pat_score(def_map, pat))
.sum();
.sum(0);
// Irrefutable columns always go first, they'd only be duplicated in the branches.
if total_score == 0 {

View File

@ -1194,7 +1194,7 @@ fn ty_of_method_or_bare_fn<'tcx, AC: AstConv<'tcx>>(
lifetimes_for_params.push((input_pat, accumulator));
}
if lifetimes_for_params.iter().map(|&(_, ref x)| x.len()).sum() == 1 {
if lifetimes_for_params.iter().map(|&(_, ref x)| x.len()).sum(0) == 1 {
implied_output_region =
Some(lifetimes_for_params.iter()
.filter_map(|&(_, ref x)|

View File

@ -15,7 +15,6 @@
#![allow(deprecated)] // to_be32
use std::iter::range_step;
use std::num::Zero;
use std::slice::bytes::{MutableByteVector, copy_memory};
use serialize::hex::ToHex;
@ -64,7 +63,7 @@ impl ToBits for u64 {
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Zero::zero() {
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}

View File

@ -55,6 +55,18 @@ impl Add<Counts, Counts> for Counts {
}
impl Counts {
fn zero() -> Counts {
Counts {
deprecated: 0,
experimental: 0,
unstable: 0,
stable: 0,
frozen: 0,
locked: 0,
unmarked: 0,
}
}
pub fn total(&self) -> uint {
self.deprecated + self.experimental + self.unstable + self.stable +
self.frozen + self.locked + self.unmarked
@ -92,14 +104,14 @@ fn visible(item: &Item) -> bool {
fn count_stability(stab: Option<&Stability>) -> Counts {
match stab {
None => Counts { unmarked: 1, .. Zero::zero() },
None => Counts { unmarked: 1, .. Counts::zero() },
Some(ref stab) => match stab.level {
Deprecated => Counts { deprecated: 1, .. Zero::zero() },
Experimental => Counts { experimental: 1, .. Zero::zero() },
Unstable => Counts { unstable: 1, .. Zero::zero() },
Stable => Counts { stable: 1, .. Zero::zero() },
Frozen => Counts { frozen: 1, .. Zero::zero() },
Locked => Counts { locked: 1, .. Zero::zero() },
Deprecated => Counts { deprecated: 1, .. Counts::zero() },
Experimental => Counts { experimental: 1, .. Counts::zero() },
Unstable => Counts { unstable: 1, .. Counts::zero() },
Stable => Counts { stable: 1, .. Counts::zero() },
Frozen => Counts { frozen: 1, .. Counts::zero() },
Locked => Counts { locked: 1, .. Counts::zero() },
}
}
}
@ -136,14 +148,14 @@ fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) {
let subcounts = subitems.iter().filter(|i| visible(*i))
.map(summarize_item)
.map(|s| s.val0())
.sum();
.sum(Counts::zero());
(item_counts + subcounts, None)
}
// `pub` automatically
EnumItem(Enum { variants: ref subitems, .. }) => {
let subcounts = subitems.iter().map(summarize_item)
.map(|s| s.val0())
.sum();
.sum(Counts::zero());
(item_counts + subcounts, None)
}
TraitItem(Trait {
@ -161,7 +173,7 @@ fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) {
.map(extract_item)
.map(summarize_item)
.map(|s| s.val0())
.sum();
.sum(Counts::zero());
(item_counts + subcounts, None)
}
ModuleItem(Module { ref items, .. }) => {
@ -182,7 +194,7 @@ fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) {
}))
}
// no stability information for the following items:
ViewItemItem(_) | PrimitiveItem(_) => (Zero::zero(), None),
ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None),
_ => (item_counts, None)
}
}
@ -192,7 +204,7 @@ pub fn build(krate: &Crate) -> ModuleSummary {
match krate.module {
None => ModuleSummary {
name: krate.name.clone(),
counts: Zero::zero(),
counts: Counts::zero(),
submodules: Vec::new(),
},
Some(ref item) => ModuleSummary {

View File

@ -1522,7 +1522,7 @@ impl<T: Iterator<char>> Parser<T> {
}
}
let exp = num::pow(10_f64, exp);
let exp = 10_f64.powi(exp as i32);
if neg_exp {
res /= exp;
} else {

View File

@ -655,7 +655,7 @@ mod tests {
let nan: f32 = Float::nan();
let inf: f32 = Float::infinity();
let neg_inf: f32 = Float::neg_infinity();
let zero: f32 = Zero::zero();
let zero: f32 = Float::zero();
let neg_zero: f32 = Float::neg_zero();
assert!(!nan.is_normal());
assert!(!inf.is_normal());
@ -672,7 +672,7 @@ mod tests {
let nan: f32 = Float::nan();
let inf: f32 = Float::infinity();
let neg_inf: f32 = Float::neg_infinity();
let zero: f32 = Zero::zero();
let zero: f32 = Float::zero();
let neg_zero: f32 = Float::neg_zero();
assert_eq!(nan.classify(), FPNaN);
assert_eq!(inf.classify(), FPInfinite);

View File

@ -653,7 +653,7 @@ mod tests {
let nan: f64 = Float::nan();
let inf: f64 = Float::infinity();
let neg_inf: f64 = Float::neg_infinity();
let zero: f64 = Zero::zero();
let zero: f64 = Float::zero();
let neg_zero: f64 = Float::neg_zero();
assert!(!nan.is_normal());
assert!(!inf.is_normal());
@ -670,7 +670,7 @@ mod tests {
let nan: f64 = Float::nan();
let inf: f64 = Float::infinity();
let neg_inf: f64 = Float::neg_infinity();
let zero: f64 = Zero::zero();
let zero: f64 = Float::zero();
let neg_zero: f64 = Float::neg_zero();
assert_eq!(nan.classify(), FPNaN);
assert_eq!(inf.classify(), FPInfinite);

View File

@ -771,10 +771,7 @@ mod tests {
assert_pow!((3i, 0 ) => 1);
assert_pow!((5i, 1 ) => 5);
assert_pow!((-4i, 2 ) => 16);
assert_pow!((0.5f64, 5 ) => 0.03125);
assert_pow!((8i, 3 ) => 512);
assert_pow!((8.0f64, 5 ) => 32768.0);
assert_pow!((8.5f64, 5 ) => 44370.53125);
assert_pow!((2u64, 50) => 1125899906842624);
}
}

View File

@ -94,7 +94,7 @@ pub enum SignFormat {
fn int_to_str_bytes_common<T: Int>(num: T, radix: uint, sign: SignFormat, f: |u8|) {
assert!(2 <= radix && radix <= 36);
let _0: T = num::zero();
let _0: T = Int::zero();
let neg = num < _0;
let radix_gen: T = num::cast(radix).unwrap();
@ -194,8 +194,8 @@ pub fn float_to_str_bytes_common<T: Float>(
_ => ()
}
let _0: T = num::zero();
let _1: T = num::one();
let _0: T = Float::zero();
let _1: T = Float::one();
match num.classify() {
FPNaN => { return (b"NaN".to_vec(), true); }
@ -430,8 +430,8 @@ pub fn from_str_radix_float<T: Float>(src: &str, radix: uint) -> Option<T> {
"from_str_radix_float: must lie in the range `[2, 36]` - found {}",
radix);
let _0: T = num::zero();
let _1: T = num::one();
let _0: T = Float::zero();
let _1: T = Float::one();
let radix_t: T = num::cast(radix as int).unwrap();
// Special values
@ -558,8 +558,8 @@ pub fn from_str_radix_float<T: Float>(src: &str, radix: uint) -> Option<T> {
};
match (is_positive, exp) {
(true, Some(exp)) => num::pow(base, exp),
(false, Some(exp)) => _1 / num::pow(base, exp),
(true, Some(exp)) => base.powi(exp as i32),
(false, Some(exp)) => _1 / base.powi(exp as i32),
(_, None) => return None,
}
},
@ -578,8 +578,8 @@ pub fn from_str_radix_int<T: Int>(src: &str, radix: uint) -> Option<T> {
num::cast(x).unwrap()
}
let _0: T = num::zero();
let _1: T = num::one();
let _0: T = Int::zero();
let _1: T = Int::one();
let is_signed = _0 > Int::min_value();
let (is_positive, src) = match src.slice_shift_char() {

View File

@ -356,7 +356,7 @@ impl Path {
Some(vec![SEP_BYTE])
} else {
let n = if is_abs { comps.len() } else { comps.len() - 1} +
comps.iter().map(|v| v.len()).sum();
comps.iter().map(|v| v.len()).sum(0);
let mut v = Vec::with_capacity(n);
let mut it = comps.into_iter();
if !is_abs {

View File

@ -781,7 +781,7 @@ impl Path {
let prefix_ = s.slice_to(prefix_len(prefix));
let n = prefix_.len() +
if is_abs { comps.len() } else { comps.len() - 1} +
comps.iter().map(|v| v.len()).sum();
comps.iter().map(|v| v.len()).sum(0);
let mut s = String::with_capacity(n);
match prefix {
Some(DiskPrefix) => {

View File

@ -13,7 +13,6 @@
use io::{mod, IoError, IoResult};
use prelude::*;
use num;
use sys::{last_error, retry, fs};
use c_str::CString;
use path::BytesContainer;
@ -57,8 +56,8 @@ pub fn unimpl() -> IoError {
}
// unix has nonzero values as errors
pub fn mkerr_libc<Int: num::Zero>(ret: Int) -> IoResult<()> {
if !ret.is_zero() {
pub fn mkerr_libc<T: Int>(ret: T) -> IoResult<()> {
if ret != Int::zero() {
Err(last_error())
} else {
Ok(())

View File

@ -116,11 +116,11 @@ pub fn decode_error_detailed(errno: i32) -> IoError {
}
#[inline]
pub fn retry<I: PartialEq + num::One + Neg<I>> (f: || -> I) -> I {
let minus_one = -num::one::<I>();
pub fn retry<T: Signed + Int> (f: || -> T) -> T {
let one: T = Int::one();
loop {
let n = f();
if n == minus_one && os::errno() == libc::EINTR as int { }
if n == -one && os::errno() == libc::EINTR as int { }
else { return n }
}
}

View File

@ -19,7 +19,6 @@ use parse::token;
use ptr::P;
use std::fmt;
use std::num::Zero;
use std::fmt::Show;
use std::rc::Rc;
use serialize::{Encodable, Decodable, Encoder, Decoder};
@ -857,9 +856,9 @@ pub enum Sign {
Plus
}
impl<T: PartialOrd+Zero> Sign {
impl<T: Int> Sign {
pub fn new(n: T) -> Sign {
if n < Zero::zero() {
if n < Int::zero() {
Minus
} else {
Plus

View File

@ -16,7 +16,6 @@ use std::fmt::Show;
use std::hash::Hash;
use std::io;
use std::mem;
use std::num::Zero;
fn local_cmp<T:Float>(x: T, y: T) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
@ -144,7 +143,6 @@ pub struct Summary<T> {
}
impl<T: FloatMath + FromPrimitive> Summary<T> {
/// Construct a new summary of a sample set.
pub fn new(samples: &[T]) -> Summary<T> {
Summary {
@ -182,7 +180,7 @@ impl<'a, T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
// `lo`. Together `hi+lo` are exactly equal to `x+y`.
let hi = x + y;
let lo = y - (hi - x);
if !lo.is_zero() {
if lo != Float::zero() {
partials[j] = lo;
j += 1;
}
@ -195,7 +193,7 @@ impl<'a, T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
partials.truncate(j+1);
}
}
let zero: T = Zero::zero();
let zero: T = Float::zero();
partials.iter().fold(zero, |p, q| p + *q)
}
@ -220,10 +218,10 @@ impl<'a, T: FloatMath + FromPrimitive> Stats<T> for &'a [T] {
fn var(self) -> T {
if self.len() < 2 {
Zero::zero()
Float::zero()
} else {
let mean = self.mean();
let mut v: T = Zero::zero();
let mut v: T = Float::zero();
for s in self.iter() {
let x = *s - mean;
v = v + x*x;
@ -292,7 +290,7 @@ fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T],
if sorted_samples.len() == 1 {
return sorted_samples[0];
}
let zero: T = Zero::zero();
let zero: T = Float::zero();
assert!(zero <= pct);
let hundred = FromPrimitive::from_uint(100).unwrap();
assert!(pct <= hundred);
@ -368,14 +366,14 @@ pub fn write_boxplot<T: Float + Show + FromPrimitive>(
let himag = ten.powf(s.max.abs().log10().floor());
// need to consider when the limit is zero
let zero: T = Zero::zero();
let lo = if lomag.is_zero() {
let zero: T = Float::zero();
let lo = if lomag == Float::zero() {
zero
} else {
(s.min / lomag).floor() * lomag
};
let hi = if himag.is_zero() {
let hi = if himag == Float::zero() {
zero
} else {
(s.max / himag).ceil() * himag
@ -1044,11 +1042,11 @@ mod tests {
}
#[test]
fn test_sum_f64s() {
assert_eq!([0.5f64, 3.2321f64, 1.5678f64].sum(), 5.2999);
assert_eq!([0.5f64, 3.2321f64, 1.5678f64].sum(0.0), 5.2999);
}
#[test]
fn test_sum_f64_between_ints_that_sum_to_0() {
assert_eq!([1e30f64, 1.2f64, -1e30f64].sum(), 1.2);
assert_eq!([1e30f64, 1.2f64, -1e30f64].sum(0.0), 1.2);
}
}
@ -1060,7 +1058,7 @@ mod bench {
#[bench]
pub fn sum_three_items(b: &mut Bencher) {
b.iter(|| {
[1e20f64, 1.5f64, -1e20f64].sum();
[1e20f64, 1.5f64, -1e20f64].sum(0.0);
})
}
#[bench]
@ -1069,7 +1067,7 @@ mod bench {
let v = Vec::from_fn(500, |i| nums[i%5]);
b.iter(|| {
v.as_slice().sum();
v.as_slice().sum(0.0);
})
}
}

View File

@ -153,7 +153,7 @@ impl UnicodeStrPrelude for str {
#[inline]
fn width(&self, is_cjk: bool) -> uint {
self.chars().map(|c| c.width(is_cjk).unwrap_or(0)).sum()
self.chars().map(|c| c.width(is_cjk).unwrap_or(0)).sum(0)
}
#[inline]

View File

@ -104,7 +104,7 @@ fn A(i: uint, j: uint) -> f64 {
}
fn dot(v: &[f64], u: &[f64]) -> f64 {
v.iter().zip(u.iter()).map(|(a, b)| *a * *b).sum()
v.iter().zip(u.iter()).map(|(a, b)| *a * *b).sum(0.0)
}
// Executes a closure in parallel over the given mutable slice. The closure `f`

View File

@ -11,5 +11,5 @@
use std::iter::AdditiveIterator;
fn main() {
let x: [u64, ..3] = [1, 2, 3];
assert_eq!(6, range(0, 3).map(|i| x[i]).sum());
assert_eq!(6, range(0, 3).map(|i| x[i]).sum(0));
}