Coverage Report

Created: 2025-07-18 06:22

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