From 471b163ddf72cbe8991eb2b25bd06c57b8e966a5 Mon Sep 17 00:00:00 2001 From: Erik Date: Fri, 13 Jul 2018 16:04:30 -0400 Subject: [PATCH] implement trunc and truncf --- src/lib.rs | 4 ---- src/math/mod.rs | 4 ++++ src/math/trunc.rs | 24 ++++++++++++++++++++++++ src/math/truncf.rs | 24 ++++++++++++++++++++++++ test-generator/src/main.rs | 4 ++-- 5 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 src/math/trunc.rs create mode 100644 src/math/truncf.rs diff --git a/src/lib.rs b/src/lib.rs index ed163ff98..fa709ad75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,7 +44,6 @@ pub trait F32Ext { #[cfg(todo)] fn round(self) -> Self; - #[cfg(todo)] fn trunc(self) -> Self; #[cfg(todo)] @@ -163,7 +162,6 @@ impl F32Ext for f32 { roundf(self) } - #[cfg(todo)] #[inline] fn trunc(self) -> Self { truncf(self) @@ -372,7 +370,6 @@ pub trait F64Ext { fn round(self) -> Self; - #[cfg(todo)] fn trunc(self) -> Self; #[cfg(todo)] @@ -494,7 +491,6 @@ impl F64Ext for f64 { round(self) } - #[cfg(todo)] #[inline] fn trunc(self) -> Self { trunc(self) diff --git a/src/math/mod.rs b/src/math/mod.rs index e400badd1..71b58dda8 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -15,6 +15,8 @@ mod sqrtf; mod logf; mod expf; mod floor; +mod trunc; +mod truncf; //mod service; @@ -30,6 +32,8 @@ pub use self::{ logf::logf, expf::expf, floor::floor, + trunc::trunc, + truncf::truncf, }; fn isnanf(x: f32) -> bool { diff --git a/src/math/trunc.rs b/src/math/trunc.rs new file mode 100644 index 000000000..b50ffd771 --- /dev/null +++ b/src/math/trunc.rs @@ -0,0 +1,24 @@ +use core::f64; + +#[inline] +pub fn trunc(x: f64) -> f64 { + let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120 + + let mut i: u64 = x.to_bits(); + let mut e: i64 = (i >> 52 & 0x7ff) as i64 - 0x3ff + 12; + let m: u64; + + if e >= 52 + 12 { + return x; + } + if e < 12 { + e = 1; + } + m = -1i64 as u64 >> e; + if (i & m) == 0 { + return x; + } + force_eval!(x + x1p120); + i &= !m; + f64::from_bits(i) +} diff --git a/src/math/truncf.rs b/src/math/truncf.rs new file mode 100644 index 000000000..f7d7249e3 --- /dev/null +++ b/src/math/truncf.rs @@ -0,0 +1,24 @@ +use core::f32; + +#[inline] +pub fn truncf(x: f32) -> f32 { + let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120 + + let mut i: u32 = x.to_bits(); + let mut e: i32 = (i >> 23 & 0xff) as i32 - 0x7f + 9; + let m: u32; + + if e >= 23 + 9 { + return x; + } + if e < 9 { + e = 1; + } + m = -1i32 as u32 >> e; + if (i & m) == 0 { + return x; + } + force_eval!(x + x1p120); + i &= !m; + f32::from_bits(i) +} diff --git a/test-generator/src/main.rs b/test-generator/src/main.rs index 42e157ad8..6353b257d 100644 --- a/test-generator/src/main.rs +++ b/test-generator/src/main.rs @@ -562,7 +562,7 @@ fn main() -> Result<(), Box> { f32_f32! { // acosf, // floorf, - // truncf + truncf, // asinf, // atanf, // cbrtf, @@ -625,7 +625,7 @@ f64_f64! { // sqrt, // tan, // tanh, - // trunc, + trunc, fabs, }