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