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