1#![allow(unreachable_code)]
2use core::f64;
34const TOINT: f64 = 1. / f64::EPSILON;
56/// Ceil (f64)
7///
8/// Finds the nearest integer greater than or equal to `x`.
9#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
10pub fn ceil(x: f64) -> f64 {
11// On wasm32 we know that LLVM's intrinsic will compile to an optimized
12 // `f64.ceil` native instruction, so we can leverage this for both code size
13 // and speed.
14llvm_intrinsically_optimized! {
15#[cfg(target_arch = "wasm32")] {
16return unsafe { ::core::intrinsics::ceilf64(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, probablly due to excess precision issues.
24 //basic implementation taken from https://github.com/rust-lang/libm/issues/219
25use super::fabs;
26if fabs(x).to_bits() < 4503599627370496.0_f64.to_bits() {
27let truncated = x as i64 as f64;
28if truncated < x {
29return truncated + 1.0;
30 } else {
31return truncated;
32 }
33 } else {
34return x;
35 }
36 }
37let u: u64 = x.to_bits();
38let e: i64 = (u >> 52 & 0x7ff) as i64;
39let y: f64;
4041if e >= 0x3ff + 52 || x == 0. {
42return x;
43 }
44// y = int(x) - x, where int(x) is an integer neighbor of x
45y = if (u >> 63) != 0 {
46 x - TOINT + TOINT - x
47 } else {
48 x + TOINT - TOINT - x
49 };
50// special case because of non-nearest rounding modes
51if e < 0x3ff {
52force_eval!(y);
53return if (u >> 63) != 0 { -0. } else { 1. };
54 }
55if y < 0. {
56 x + y + 1.
57} else {
58 x + y
59 }
60}
6162#[cfg(test)]
63mod tests {
64use super::*;
65use core::f64::*;
6667#[test]
68fn sanity_check() {
69assert_eq!(ceil(1.1), 2.0);
70assert_eq!(ceil(2.9), 3.0);
71 }
7273/// The spec: https://en.cppreference.com/w/cpp/numeric/math/ceil
74#[test]
75fn spec_tests() {
76// Not Asserted: that the current rounding mode has no effect.
77assert!(ceil(NAN).is_nan());
78for f in [0.0, -0.0, INFINITY, NEG_INFINITY].iter().copied() {
79assert_eq!(ceil(f), f);
80 }
81 }
82}