malachite_base/num/arithmetic/saturating_sub.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::{SaturatingSub, SaturatingSubAssign};
10
11macro_rules! impl_saturating_sub {
12 ($t:ident) => {
13 impl SaturatingSub<$t> for $t {
14 type Output = $t;
15
16 /// This is a wrapper over the `saturating_sub` functions in the standard library, for
17 /// example [this one](i32::saturating_sub).
18 #[inline]
19 fn saturating_sub(self, other: $t) -> $t {
20 $t::saturating_sub(self, other)
21 }
22 }
23
24 impl SaturatingSubAssign<$t> for $t {
25 /// Subtracts a number by another number in place, saturating at the numeric bounds
26 /// instead 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_sub#saturating_sub_assign).
42 #[inline]
43 fn saturating_sub_assign(&mut self, other: $t) {
44 *self = self.saturating_sub(other);
45 }
46 }
47 };
48}
49apply_to_primitive_ints!(impl_saturating_sub);