1use core::u64;
23/// 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.
11llvm_intrinsically_optimized! {
12#[cfg(target_arch = "wasm32")] {
13return unsafe { ::core::intrinsics::fabsf64(x) }
14 }
15 }
16 f64::from_bits(x.to_bits() & (u64::MAX / 2))
17}
1819#[cfg(test)]
20mod tests {
21use core::f64::*;
2223use super::*;
2425#[test]
26fn sanity_check() {
27assert_eq!(fabs(-1.0), 1.0);
28assert_eq!(fabs(2.8), 2.8);
29 }
3031/// The spec: https://en.cppreference.com/w/cpp/numeric/math/fabs
32#[test]
33fn spec_tests() {
34assert!(fabs(NAN).is_nan());
35for f in [0.0, -0.0].iter().copied() {
36assert_eq!(fabs(f), 0.0);
37 }
38for f in [INFINITY, NEG_INFINITY].iter().copied() {
39assert_eq!(fabs(f), INFINITY);
40 }
41 }
42}