• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![allow(unreachable_code)]
2 use core::f64;
3 
4 const TOINT: f64 = 1. / f64::EPSILON;
5 
6 /// Floor (f64)
7 ///
8 /// Finds the nearest integer less than or equal to `x`.
9 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
floor(x: f64) -> f6410 pub fn floor(x: f64) -> f64 {
11     // On wasm32 we know that LLVM's intrinsic will compile to an optimized
12     // `f64.floor` native instruction, so we can leverage this for both code size
13     // and speed.
14     llvm_intrinsically_optimized! {
15         #[cfg(target_arch = "wasm32")] {
16             return unsafe { ::core::intrinsics::floorf64(x) }
17         }
18     }
19     #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
20     {
21         //use an alternative implementation on x86, because the
22         //main implementation fails with the x87 FPU used by
23         //debian i386, probably due to excess precision issues.
24         //basic implementation taken from https://github.com/rust-lang/libm/issues/219
25         use super::fabs;
26         if fabs(x).to_bits() < 4503599627370496.0_f64.to_bits() {
27             let truncated = x as i64 as f64;
28             if truncated > x {
29                 return truncated - 1.0;
30             } else {
31                 return truncated;
32             }
33         } else {
34             return x;
35         }
36     }
37     let ui = x.to_bits();
38     let e = ((ui >> 52) & 0x7ff) as i32;
39 
40     if (e >= 0x3ff + 52) || (x == 0.) {
41         return x;
42     }
43     /* y = int(x) - x, where int(x) is an integer neighbor of x */
44     let y = if (ui >> 63) != 0 { x - TOINT + TOINT - x } else { x + TOINT - TOINT - x };
45     /* special case because of non-nearest rounding modes */
46     if e < 0x3ff {
47         force_eval!(y);
48         return if (ui >> 63) != 0 { -1. } else { 0. };
49     }
50     if y > 0. { x + y - 1. } else { x + y }
51 }
52 
53 #[cfg(test)]
54 mod tests {
55     use core::f64::*;
56 
57     use super::*;
58 
59     #[test]
sanity_check()60     fn sanity_check() {
61         assert_eq!(floor(1.1), 1.0);
62         assert_eq!(floor(2.9), 2.0);
63     }
64 
65     /// The spec: https://en.cppreference.com/w/cpp/numeric/math/floor
66     #[test]
spec_tests()67     fn spec_tests() {
68         // Not Asserted: that the current rounding mode has no effect.
69         assert!(floor(NAN).is_nan());
70         for f in [0.0, -0.0, INFINITY, NEG_INFINITY].iter().copied() {
71             assert_eq!(floor(f), f);
72         }
73     }
74 }
75