1/// Absolute value (magnitude) (f32)
2/// Calculates the absolute value (magnitude) of the argument `x`,
3/// by direct manipulation of the bit representation of `x`.
4#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
5pub fn fabsf(x: f32) -> f32 {
6// On wasm32 we know that LLVM's intrinsic will compile to an optimized
7 // `f32.abs` native instruction, so we can leverage this for both code size
8 // and speed.
9llvm_intrinsically_optimized! {
10#[cfg(target_arch = "wasm32")] {
11return unsafe { ::core::intrinsics::fabsf32(x) }
12 }
13 }
14 f32::from_bits(x.to_bits() & 0x7fffffff)
15}
1617// PowerPC tests are failing on LLVM 13: https://github.com/rust-lang/rust/issues/88520
18#[cfg(not(target_arch = "powerpc64"))]
19#[cfg(test)]
20mod tests {
21use core::f32::*;
2223use super::*;
2425#[test]
26fn sanity_check() {
27assert_eq!(fabsf(-1.0), 1.0);
28assert_eq!(fabsf(2.8), 2.8);
29 }
3031/// The spec: https://en.cppreference.com/w/cpp/numeric/math/fabs
32#[test]
33fn spec_tests() {
34assert!(fabsf(NAN).is_nan());
35for f in [0.0, -0.0].iter().copied() {
36assert_eq!(fabsf(f), 0.0);
37 }
38for f in [INFINITY, NEG_INFINITY].iter().copied() {
39assert_eq!(fabsf(f), INFINITY);
40 }
41 }
42}