/rust/registry/src/index.crates.io-6f17d22bba15001f/libm-0.2.11/src/math/fabs.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use 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)] |
7 | 0 | pub fn fabs(x: f64) -> f64 { |
8 | 0 | // On wasm32 we know that LLVM's intrinsic will compile to an optimized |
9 | 0 | // `f64.abs` native instruction, so we can leverage this for both code size |
10 | 0 | // and speed. |
11 | 0 | llvm_intrinsically_optimized! { |
12 | 0 | #[cfg(target_arch = "wasm32")] { |
13 | 0 | return unsafe { ::core::intrinsics::fabsf64(x) } |
14 | 0 | } |
15 | 0 | } |
16 | 0 | f64::from_bits(x.to_bits() & (u64::MAX / 2)) |
17 | 0 | } |
18 | | |
19 | | #[cfg(test)] |
20 | | mod 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 | | } |