malachite_base/num/arithmetic/checked_mul_add_mul.rs
1// Copyright © 2026 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::mul_add_mul::{
10 Wide, mul_add_mul_wide_signed, mul_add_mul_wide_unsigned,
11};
12use crate::num::arithmetic::traits::CheckedMulAddMul;
13
14macro_rules! impl_checked_mul_add_mul_unsigned {
15 ($t:ident) => {
16 impl CheckedMulAddMul for $t {
17 type Output = $t;
18
19 /// Adds the products of two pairs of numbers, returning `None` if the result cannot be
20 /// represented.
21 ///
22 /// $$
23 /// f(x, y, z, w) = \\begin{cases}
24 /// xy + zw & \\text{if} \\quad xy + zw \\ \\text{is representable} \\\\
25 /// \\operatorname{None} & \\text{otherwise}
26 /// \\end{cases}
27 /// $$
28 ///
29 /// The products are formed at double width, so a product that does not fit does not by
30 /// itself make the result unrepresentable.
31 ///
32 /// # Worst-case complexity
33 /// Constant time and additional memory.
34 ///
35 /// # Examples
36 /// See [here](super::checked_mul_add_mul#checked_mul_add_mul).
37 #[inline]
38 fn checked_mul_add_mul(self, y: $t, z: $t, w: $t) -> Option<$t> {
39 match mul_add_mul_wide_unsigned(self, y, z, w, false) {
40 Wide::Fits(v) => Some(v),
41 _ => None,
42 }
43 }
44 }
45 };
46}
47apply_to_unsigneds!(impl_checked_mul_add_mul_unsigned);
48
49macro_rules! impl_checked_mul_add_mul_signed {
50 ($t:ident) => {
51 impl CheckedMulAddMul for $t {
52 type Output = $t;
53
54 /// Adds the products of two pairs of numbers, returning `None` if the result cannot be
55 /// represented.
56 ///
57 /// $$
58 /// f(x, y, z, w) = \\begin{cases}
59 /// xy + zw & \\text{if} \\quad xy + zw \\ \\text{is representable} \\\\
60 /// \\operatorname{None} & \\text{otherwise}
61 /// \\end{cases}
62 /// $$
63 ///
64 /// The products are formed at double width, so a product that does not fit does not by
65 /// itself make the result unrepresentable.
66 ///
67 /// # Worst-case complexity
68 /// Constant time and additional memory.
69 ///
70 /// # Examples
71 /// See [here](super::checked_mul_add_mul#checked_mul_add_mul).
72 #[inline]
73 fn checked_mul_add_mul(self, y: $t, z: $t, w: $t) -> Option<$t> {
74 match mul_add_mul_wide_signed(self, y, z, w, false) {
75 Wide::Fits(v) => Some(v),
76 _ => None,
77 }
78 }
79 }
80 };
81}
82apply_to_signeds!(impl_checked_mul_add_mul_signed);