malachite_base/num/arithmetic/
abs.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::arithmetic::traits::{Abs, AbsAssign, UnsignedAbs};
10
11macro_rules! impl_abs_primitive_int {
12    ($u:ident, $s:ident) => {
13        impl Abs for $s {
14            type Output = $s;
15
16            /// This is a wrapper over the `abs` functions in the standard library, for example
17            /// [this one](i32::abs).
18            #[inline]
19            fn abs(self) -> $s {
20                $s::abs(self)
21            }
22        }
23
24        impl AbsAssign for $s {
25            /// Replaces a number with its absolute value.
26            ///
27            /// $x \gets |x|$.
28            ///
29            /// # Worst-case complexity
30            /// Constant time and additional memory.
31            ///
32            /// # Examples
33            /// See [here](super::abs#abs_assign).
34            #[inline]
35            fn abs_assign(&mut self) {
36                *self = self.abs();
37            }
38        }
39
40        impl UnsignedAbs for $s {
41            type Output = $u;
42
43            /// This is a wrapper over the `unsigned_abs` functions in the standard library, for
44            /// example [this one](i32::unsigned_abs).
45            #[inline]
46            fn unsigned_abs(self) -> $u {
47                self.unsigned_abs()
48            }
49        }
50    };
51}
52apply_to_unsigned_signed_pairs!(impl_abs_primitive_int);
53
54macro_rules! impl_abs_primitive_float {
55    ($f:ident) => {
56        impl Abs for $f {
57            type Output = $f;
58
59            /// This is a wrapper over the `fabs` functions from [`libm`].
60            #[inline]
61            fn abs(self) -> $f {
62                libm::Libm::<$f>::fabs(self)
63            }
64        }
65
66        impl AbsAssign for $f {
67            /// Replaces a number with its absolute value.
68            ///
69            /// $x \gets |x|$.
70            ///
71            /// # Worst-case complexity
72            /// Constant time and additional memory.
73            ///
74            /// # Examples
75            /// See [here](super::abs#abs_assign).
76            #[inline]
77            fn abs_assign(&mut self) {
78                *self = self.abs();
79            }
80        }
81    };
82}
83apply_to_primitive_floats!(impl_abs_primitive_float);