malachite_base/num/arithmetic/
saturating_square.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::{
10    SaturatingMulAssign, SaturatingSquare, SaturatingSquareAssign,
11};
12
13macro_rules! impl_saturating_square {
14    ($t:ident) => {
15        impl SaturatingSquare for $t {
16            type Output = $t;
17
18            /// Squares a number, saturating at the numeric bounds instead of overflowing.
19            ///
20            /// $$
21            /// f(x) = \\begin{cases}
22            ///     x^2 & \text{if} \\quad x^2 \leq M, \\\\
23            ///     M & \text{if} \\quad x^2 > M,
24            /// \\end{cases}
25            /// $$
26            /// where $M$ is `Self::MAX`.
27            ///
28            /// # Worst-case complexity
29            /// Constant time and additional memory.
30            ///
31            /// # Examples
32            /// See [here](super::saturating_square#saturating_square).
33            #[inline]
34            fn saturating_square(self) -> $t {
35                self.saturating_mul(self)
36            }
37        }
38
39        impl SaturatingSquareAssign for $t {
40            /// Squares a number in place, saturating at the numeric bounds instead of overflowing.
41            ///
42            /// $$
43            /// x \gets \\begin{cases}
44            ///     x^2 & \text{if} \\quad x^2 \leq M, \\\\
45            ///     M & \text{if} \\quad x^2 > M,
46            /// \\end{cases}
47            /// $$
48            /// where $M$ is `Self::MAX`.
49            ///
50            /// # Worst-case complexity
51            /// Constant time and additional memory.
52            ///
53            /// # Examples
54            /// See [here](super::saturating_square#saturating_square_assign).
55            #[inline]
56            fn saturating_square_assign(&mut self) {
57                self.saturating_mul_assign(*self);
58            }
59        }
60    };
61}
62apply_to_primitive_ints!(impl_saturating_square);