From bc94c70687c467d7fa4c655b90033de99d27211c Mon Sep 17 00:00:00 2001 From: Joseph Ryan Date: Fri, 13 Jul 2018 20:46:09 -0500 Subject: [PATCH] implement roundf --- library/compiler-builtins/libm/src/lib.rs | 2 -- .../compiler-builtins/libm/src/math/mod.rs | 8 +++-- .../compiler-builtins/libm/src/math/roundf.rs | 33 +++++++++++++++++++ .../libm/test-generator/src/main.rs | 2 +- 4 files changed, 40 insertions(+), 5 deletions(-) create mode 100644 library/compiler-builtins/libm/src/math/roundf.rs diff --git a/library/compiler-builtins/libm/src/lib.rs b/library/compiler-builtins/libm/src/lib.rs index 0d13590c7ecc..b87e82b2ac6a 100644 --- a/library/compiler-builtins/libm/src/lib.rs +++ b/library/compiler-builtins/libm/src/lib.rs @@ -41,7 +41,6 @@ pub trait F32Ext { #[cfg(todo)] fn ceil(self) -> Self; - #[cfg(todo)] fn round(self) -> Self; #[cfg(todo)] @@ -160,7 +159,6 @@ impl F32Ext for f32 { ceilf(self) } - #[cfg(todo)] #[inline] fn round(self) -> Self { roundf(self) diff --git a/library/compiler-builtins/libm/src/math/mod.rs b/library/compiler-builtins/libm/src/math/mod.rs index 41359bf8c059..8032bdabf9ac 100644 --- a/library/compiler-builtins/libm/src/math/mod.rs +++ b/library/compiler-builtins/libm/src/math/mod.rs @@ -1,7 +1,9 @@ macro_rules! force_eval { ($e:expr) => { - unsafe { ::core::ptr::read_volatile(&$e); } - } + unsafe { + ::core::ptr::read_volatile(&$e); + } + }; } mod fabs; @@ -9,6 +11,7 @@ mod fabsf; mod fmodf; mod powf; mod round; +mod roundf; mod scalbnf; mod sqrtf; @@ -17,6 +20,7 @@ pub use self::fabsf::fabsf; pub use self::fmodf::fmodf; pub use self::powf::powf; pub use self::round::round; +pub use self::roundf::roundf; pub use self::scalbnf::scalbnf; pub use self::sqrtf::sqrtf; diff --git a/library/compiler-builtins/libm/src/math/roundf.rs b/library/compiler-builtins/libm/src/math/roundf.rs new file mode 100644 index 000000000000..bd2488fa99c8 --- /dev/null +++ b/library/compiler-builtins/libm/src/math/roundf.rs @@ -0,0 +1,33 @@ +use core::f32; + +const TOINT: f32 = 1.0 / f32::EPSILON; + +pub fn roundf(mut x: f32) -> f32 { + let i = x.to_bits(); + let e: u32 = i >> 23 & 0xff; + let mut y: f32; + + if e >= 0x7f + 23 { + return x; + } + if i >> 31 != 0 { + x = -x; + } + if e < 0x7f - 1 { + force_eval!(x + TOINT); + return 0.0 * x; + } + y = x + TOINT - TOINT - x; + if y > 0.5f32 { + y = y + x - 1.0; + } else if y <= -0.5f32 { + y = y + x + 1.0; + } else { + y = y + x; + } + if i >> 31 != 0 { + -y + } else { + y + } +} diff --git a/library/compiler-builtins/libm/test-generator/src/main.rs b/library/compiler-builtins/libm/test-generator/src/main.rs index 5ff78ffc8b37..2f78a8ed38da 100644 --- a/library/compiler-builtins/libm/test-generator/src/main.rs +++ b/library/compiler-builtins/libm/test-generator/src/main.rs @@ -574,7 +574,7 @@ f32_f32! { // fdimf, // log10f, // log2f, - // roundf, + roundf, // sinf, // sinhf, // tanf,