crypto_bigint/limb/
sub.rs1use super::{Inner, Limb, Wide};
4use crate::{Encoding, Wrapping};
5use core::ops::{Sub, SubAssign};
6use subtle::CtOption;
7
8impl Limb {
9 #[inline(always)]
11 pub const fn sbb(self, rhs: Limb, borrow: Limb) -> (Limb, Limb) {
12 let a = self.0 as Wide;
13 let b = rhs.0 as Wide;
14 let borrow = (borrow.0 >> (Self::BIT_SIZE - 1)) as Wide;
15 let ret = a.wrapping_sub(b + borrow);
16 (Limb(ret as Inner), Limb((ret >> Self::BIT_SIZE) as Inner))
17 }
18
19 #[inline(always)]
22 pub const fn wrapping_sub(&self, rhs: Self) -> Self {
23 Limb(self.0.wrapping_sub(rhs.0))
24 }
25
26 #[inline]
29 pub fn checked_sub(&self, rhs: Self) -> CtOption<Self> {
30 let (result, underflow) = self.sbb(rhs, Limb::ZERO);
31 CtOption::new(result, underflow.is_zero())
32 }
33}
34
35impl Sub for Wrapping<Limb> {
36 type Output = Self;
37
38 fn sub(self, rhs: Self) -> Wrapping<Limb> {
39 Wrapping(self.0.wrapping_sub(rhs.0))
40 }
41}
42
43impl Sub<&Wrapping<Limb>> for Wrapping<Limb> {
44 type Output = Wrapping<Limb>;
45
46 fn sub(self, rhs: &Wrapping<Limb>) -> Wrapping<Limb> {
47 Wrapping(self.0.wrapping_sub(rhs.0))
48 }
49}
50
51impl Sub<Wrapping<Limb>> for &Wrapping<Limb> {
52 type Output = Wrapping<Limb>;
53
54 fn sub(self, rhs: Wrapping<Limb>) -> Wrapping<Limb> {
55 Wrapping(self.0.wrapping_sub(rhs.0))
56 }
57}
58
59impl Sub<&Wrapping<Limb>> for &Wrapping<Limb> {
60 type Output = Wrapping<Limb>;
61
62 fn sub(self, rhs: &Wrapping<Limb>) -> Wrapping<Limb> {
63 Wrapping(self.0.wrapping_sub(rhs.0))
64 }
65}
66
67impl SubAssign for Wrapping<Limb> {
68 fn sub_assign(&mut self, other: Self) {
69 *self = *self - other;
70 }
71}
72
73impl SubAssign<&Wrapping<Limb>> for Wrapping<Limb> {
74 fn sub_assign(&mut self, other: &Self) {
75 *self = *self - other;
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use crate::Limb;
82
83 #[test]
84 fn sbb_no_borrow() {
85 let (res, borrow) = Limb::ONE.sbb(Limb::ONE, Limb::ZERO);
86 assert_eq!(res, Limb::ZERO);
87 assert_eq!(borrow, Limb::ZERO);
88 }
89
90 #[test]
91 fn sbb_with_borrow() {
92 let (res, borrow) = Limb::ZERO.sbb(Limb::ONE, Limb::ZERO);
93
94 assert_eq!(res, Limb::MAX);
95 assert_eq!(borrow, Limb::MAX);
96 }
97
98 #[test]
99 fn wrapping_sub_no_borrow() {
100 assert_eq!(Limb::ONE.wrapping_sub(Limb::ONE), Limb::ZERO);
101 }
102
103 #[test]
104 fn wrapping_sub_with_borrow() {
105 assert_eq!(Limb::ZERO.wrapping_sub(Limb::ONE), Limb::MAX);
106 }
107
108 #[test]
109 fn checked_sub_ok() {
110 let result = Limb::ONE.checked_sub(Limb::ONE);
111 assert_eq!(result.unwrap(), Limb::ZERO);
112 }
113
114 #[test]
115 fn checked_sub_overflow() {
116 let result = Limb::ZERO.checked_sub(Limb::ONE);
117 assert!(!bool::from(result.is_some()));
118 }
119}