malachite_base/num/arithmetic/wrapping_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::{WrappingAbs, WrappingAbsAssign};
10
11macro_rules! impl_wrapping_abs {
12 ($t:ident) => {
13 impl WrappingAbs for $t {
14 type Output = $t;
15
16 /// This is a wrapper over the `wrapping_abs` functions in the standard library, for
17 /// example [this one](i32::wrapping_abs).
18 #[inline]
19 fn wrapping_abs(self) -> $t {
20 $t::wrapping_abs(self)
21 }
22 }
23
24 impl WrappingAbsAssign for $t {
25 /// Replaces a number with its absolute value, wrapping around at the boundary of the
26 /// type.
27 ///
28 /// $$
29 /// x \gets \\begin{cases}
30 /// |x| & \text{if} \\quad x > -2^{W-1}, \\\\
31 /// -2^{W-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::wrapping_abs#wrapping_abs_assign).
41 #[inline]
42 fn wrapping_abs_assign(&mut self) {
43 *self = self.wrapping_abs();
44 }
45 }
46 };
47}
48apply_to_signeds!(impl_wrapping_abs);