Auto merge of #220 - IvanUkhov:constant, r=cuviper

Add a trait for floating-point constants

The pull request is to address issue #194. In order to keep the library organized, I’ve introduced a new trait for the new functionality. The trait is supposed to closely follows the [`consts`](https://doc.rust-lang.org/std/f64/consts/index.html) module from the standard library. There are at least the following three open questions:

1. What should the name of the trait be? Currently, it’s `Constant`; an alternative is `Consts`.
2. What should the names of the getters be? Currently, they are lower-case versions of the constants defined in the `consts` module. Note that `Float` provides `log2` and `log10`, whereas `LOG_2` and `LOG_10` get translated into `log_2` and `log_10`, respectively.
3. Should `Float` require the new trait? Or should it be left up to the user?

Please let me know what you think. Thank you!

Regards,
Ivan
This commit is contained in:
Homu 2016-08-16 10:29:20 +09:00
commit ccdf307cee
2 changed files with 56 additions and 1 deletions

View File

@ -1233,6 +1233,61 @@ fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
float_impl!(f32 integer_decode_f32);
float_impl!(f64 integer_decode_f64);
macro_rules! float_const_impl {
($(#[$doc:meta] $constant:ident,)+) => (
#[allow(non_snake_case)]
pub trait FloatConst {
$(#[$doc] fn $constant() -> Self;)+
}
float_const_impl! { @float f32, $($constant,)+ }
float_const_impl! { @float f64, $($constant,)+ }
);
(@float $T:ident, $($constant:ident,)+) => (
impl FloatConst for $T {
$(
#[inline]
fn $constant() -> Self {
::std::$T::consts::$constant
}
)+
}
);
}
float_const_impl! {
#[doc = "Return Eulers number."]
E,
#[doc = "Return `1.0 / π`."]
FRAC_1_PI,
#[doc = "Return `1.0 / sqrt(2.0)`."]
FRAC_1_SQRT_2,
#[doc = "Return `2.0 / π`."]
FRAC_2_PI,
#[doc = "Return `2.0 / sqrt(π)`."]
FRAC_2_SQRT_PI,
#[doc = "Return `π / 2.0`."]
FRAC_PI_2,
#[doc = "Return `π / 3.0`."]
FRAC_PI_3,
#[doc = "Return `π / 4.0`."]
FRAC_PI_4,
#[doc = "Return `π / 6.0`."]
FRAC_PI_6,
#[doc = "Return `π / 8.0`."]
FRAC_PI_8,
#[doc = "Return `ln(10.0)`."]
LN_10,
#[doc = "Return `ln(2.0)`."]
LN_2,
#[doc = "Return `log10(e)`."]
LOG10_E,
#[doc = "Return `log2(e)`."]
LOG2_E,
#[doc = "Return Archimedes constant."]
PI,
#[doc = "Return `sqrt(2.0)`."]
SQRT_2,
}
#[cfg(test)]
mod tests {

View File

@ -13,7 +13,7 @@
use std::ops::{Add, Sub, Mul, Div, Rem};
pub use bounds::Bounded;
pub use float::Float;
pub use float::{Float, FloatConst};
pub use identities::{Zero, One, zero, one};
pub use ops::checked::*;
pub use ops::saturating::Saturating;