malachite_base/num/arithmetic/checked_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::CheckedSquare;
10
11macro_rules! impl_checked_square {
12 ($t:ident) => {
13 impl CheckedSquare for $t {
14 type Output = $t;
15
16 /// Squares a number, returning `None` if the result cannot be represented.
17 ///
18 /// $$
19 /// f(x) = \\begin{cases}
20 /// \operatorname{Some}(x^2) & \text{if} \\quad x^2 < 2^W, \\\\
21 /// \operatorname{None} & \text{if} \\quad x^2 \geq 2^W,
22 /// \\end{cases}
23 /// $$
24 /// where $W$ is `Self::WIDTH`.
25 ///
26 /// # Worst-case complexity
27 /// Constant time and additional memory.
28 ///
29 /// # Examples
30 /// See [here](super::checked_square#checked_square).
31 #[inline]
32 fn checked_square(self) -> Option<$t> {
33 self.checked_mul(self)
34 }
35 }
36 };
37}
38apply_to_primitive_ints!(impl_checked_square);