1#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
2pub fn rintf(x: f32) -> f32 {
3 let one_over_e = 1.0 / f32::EPSILON;
4 let as_u32: u32 = x.to_bits();
5 let exponent: u32 = as_u32 >> 23 & 0xff;
6 let is_positive = (as_u32 >> 31) == 0;
7 if exponent >= 0x7f + 23 {
8 x
9 } else {
10 let ans = if is_positive {
11 x + one_over_e - one_over_e
12 } else {
13 x - one_over_e + one_over_e
14 };
15
16 if ans == 0.0 {
17 if is_positive {
18 0.0
19 } else {
20 -0.0
21 }
22 } else {
23 ans
24 }
25 }
26}
27
28// PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520
29#[cfg(not(target_arch = "powerpc64"))]
30#[cfg(test)]
31mod tests {
32 use super::rintf;
33
34 #[test]
35 fn negative_zero() {
36 assert_eq!(rintf(-0.0_f32).to_bits(), (-0.0_f32).to_bits());
37 }
38
39 #[test]
40 fn sanity_check() {
41 assert_eq!(rintf(-1.0), -1.0);
42 assert_eq!(rintf(2.8), 3.0);
43 assert_eq!(rintf(-0.5), -0.0);
44 assert_eq!(rintf(0.5), 0.0);
45 assert_eq!(rintf(-1.5), -2.0);
46 assert_eq!(rintf(1.5), 2.0);
47 }
48}
49