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