malachite_base/num/arithmetic/saturating_add.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::{SaturatingAdd, SaturatingAddAssign};
10
11macro_rules! impl_saturating_add {
12 ($t:ident) => {
13 impl SaturatingAdd<$t> for $t {
14 type Output = $t;
15
16 /// This is a wrapper over the `saturating_add` functions in the standard library, for
17 /// example [this one](i32::saturating_add).
18 #[inline]
19 fn saturating_add(self, other: $t) -> $t {
20 $t::saturating_add(self, other)
21 }
22 }
23
24 impl SaturatingAddAssign<$t> for $t {
25 /// Adds a number to another number, in place, saturating at the numeric bounds instead
26 /// of overflowing.
27 ///
28 /// $$
29 /// x \gets \\begin{cases}
30 /// x + y & \text{if} \\quad m \leq x + y \leq M, \\\\
31 /// M & \text{if} \\quad x + y > M, \\\\
32 /// m & \text{if} \\quad x + y < 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_add#saturating_add_assign).
42 #[inline]
43 fn saturating_add_assign(&mut self, other: $t) {
44 *self = self.saturating_add(other);
45 }
46 }
47 };
48}
49apply_to_primitive_ints!(impl_saturating_add);