1 | use core::f32; |
2 | |
3 | #[cfg_attr (all(test, assert_no_panic), no_panic::no_panic)] |
4 | pub fn truncf(x: f32) -> f32 { |
5 | // On wasm32 we know that LLVM's intrinsic will compile to an optimized |
6 | // `f32.trunc` native instruction, so we can leverage this for both code size |
7 | // and speed. |
8 | llvm_intrinsically_optimized! { |
9 | #[cfg(target_arch = "wasm32" )] { |
10 | return unsafe { ::core::intrinsics::truncf32(x) } |
11 | } |
12 | } |
13 | let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120 |
14 | |
15 | let mut i: u32 = x.to_bits(); |
16 | let mut e: i32 = (i >> 23 & 0xff) as i32 - 0x7f + 9; |
17 | let m: u32; |
18 | |
19 | if e >= 23 + 9 { |
20 | return x; |
21 | } |
22 | if e < 9 { |
23 | e = 1; |
24 | } |
25 | m = -1i32 as u32 >> e; |
26 | if (i & m) == 0 { |
27 | return x; |
28 | } |
29 | force_eval!(x + x1p120); |
30 | i &= !m; |
31 | f32::from_bits(i) |
32 | } |
33 | |
34 | // PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520 |
35 | #[cfg (not(target_arch = "powerpc64" ))] |
36 | #[cfg (test)] |
37 | mod tests { |
38 | #[test ] |
39 | fn sanity_check() { |
40 | assert_eq!(super::truncf(1.1), 1.0); |
41 | } |
42 | } |
43 | |