malachite_base/num/arithmetic/
saturating_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::{SaturatingAbs, SaturatingAbsAssign};
10
11macro_rules! impl_saturating_abs {
12    ($t:ident) => {
13        impl SaturatingAbs for $t {
14            type Output = $t;
15
16            /// This is a wrapper over the `saturating_abs` functions in the standard library, for
17            /// example [this one](i32::saturating_abs).
18            #[inline]
19            fn saturating_abs(self) -> $t {
20                $t::saturating_abs(self)
21            }
22        }
23
24        impl SaturatingAbsAssign for $t {
25            /// Replaces a number with its absolute value, saturating at the numeric bounds instead
26            /// of overflowing.
27            ///
28            /// $$
29            /// x \gets \\begin{cases}
30            ///     |x| & \text{if} \\quad x > -2^{W-1}, \\\\
31            ///     2^{W-1} - 1 & \text{if} \\quad x = -2^{W-1},
32            /// \\end{cases}
33            /// $$
34            /// where $W$ is `Self::WIDTH`.
35            ///
36            /// # Worst-case complexity
37            /// Constant time and additional memory.
38            ///
39            /// # Examples
40            /// See [here](super::saturating_abs#saturating_abs_assign).
41            #[inline]
42            fn saturating_abs_assign(&mut self) {
43                *self = self.saturating_abs();
44            }
45        }
46    };
47}
48apply_to_signeds!(impl_saturating_abs);