rational: small additional tweaks

Move `new` to top to make it more visible in the docs.

Replace instances of $x == Zero::zero()$ with $x.is_zero()$,
partially addressing #11.
This commit is contained in:
Michael Lamparski 2016-07-24 14:58:43 -04:00
parent 8c75506f22
commit 32dee9a0c8
1 changed files with 12 additions and 12 deletions

View File

@ -56,6 +56,17 @@ pub type Rational64 = Ratio<i64>;
pub type BigRational = Ratio<BigInt>; pub type BigRational = Ratio<BigInt>;
impl<T: Clone + Integer> Ratio<T> { impl<T: Clone + Integer> Ratio<T> {
/// Creates a new `Ratio`. Fails if `denom` is zero.
#[inline]
pub fn new(numer: T, denom: T) -> Ratio<T> {
if denom.is_zero() {
panic!("denominator == 0");
}
let mut ret = Ratio::new_raw(numer, denom);
ret.reduce();
ret
}
/// Creates a `Ratio` representing the integer `t`. /// Creates a `Ratio` representing the integer `t`.
#[inline] #[inline]
pub fn from_integer(t: T) -> Ratio<T> { pub fn from_integer(t: T) -> Ratio<T> {
@ -71,17 +82,6 @@ impl<T: Clone + Integer> Ratio<T> {
} }
} }
/// Creates a new `Ratio`. Fails if `denom == 0`.
#[inline]
pub fn new(numer: T, denom: T) -> Ratio<T> {
if denom == Zero::zero() {
panic!("denominator == 0");
}
let mut ret = Ratio::new_raw(numer, denom);
ret.reduce();
ret
}
/// Converts to an integer, rounding towards zero. /// Converts to an integer, rounding towards zero.
#[inline] #[inline]
pub fn to_integer(&self) -> T { pub fn to_integer(&self) -> T {
@ -605,7 +605,7 @@ impl<T> serde::Deserialize for Ratio<T>
where D: serde::Deserializer where D: serde::Deserializer
{ {
let (numer, denom) = try!(serde::Deserialize::deserialize(deserializer)); let (numer, denom) = try!(serde::Deserialize::deserialize(deserializer));
if denom == Zero::zero() { if denom.is_zero() {
Err(serde::de::Error::invalid_value("denominator is zero")) Err(serde::de::Error::invalid_value("denominator is zero"))
} else { } else {
Ok(Ratio::new_raw(numer, denom)) Ok(Ratio::new_raw(numer, denom))