1 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
rint(x: f64) -> f642 pub fn rint(x: f64) -> f64 {
3     let one_over_e = 1.0 / f64::EPSILON;
4     let as_u64: u64 = x.to_bits();
5     let exponent: u64 = as_u64 >> 52 & 0x7ff;
6     let is_positive = (as_u64 >> 63) == 0;
7     if exponent >= 0x3ff + 52 {
8         x
9     } else {
10         let ans = if is_positive {
11             #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
12             let x = force_eval!(x);
13             let xplusoneovere = x + one_over_e;
14             #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
15             let xplusoneovere = force_eval!(xplusoneovere);
16             xplusoneovere - one_over_e
17         } else {
18             #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
19             let x = force_eval!(x);
20             let xminusoneovere = x - one_over_e;
21             #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
22             let xminusoneovere = force_eval!(xminusoneovere);
23             xminusoneovere + one_over_e
24         };
25 
26         if ans == 0.0 {
27             if is_positive {
28                 0.0
29             } else {
30                 -0.0
31             }
32         } else {
33             ans
34         }
35     }
36 }
37 
38 // PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520
39 #[cfg(not(target_arch = "powerpc64"))]
40 #[cfg(test)]
41 mod tests {
42     use super::rint;
43 
44     #[test]
negative_zero()45     fn negative_zero() {
46         assert_eq!(rint(-0.0_f64).to_bits(), (-0.0_f64).to_bits());
47     }
48 
49     #[test]
sanity_check()50     fn sanity_check() {
51         assert_eq!(rint(-1.0), -1.0);
52         assert_eq!(rint(2.8), 3.0);
53         assert_eq!(rint(-0.5), -0.0);
54         assert_eq!(rint(0.5), 0.0);
55         assert_eq!(rint(-1.5), -2.0);
56         assert_eq!(rint(1.5), 2.0);
57     }
58 }
59