@@ -56,19 +56,24 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
56
56
#[ inline]
57
57
#[ must_use]
58
58
pub const fn overflowing_add ( mut self , rhs : Self ) -> ( Self , bool ) {
59
+ // TODO: Replace with `u64::carrying_add` once stable.
60
+ #[ inline]
61
+ const fn u64_carrying_add ( lhs : u64 , rhs : u64 , carry : bool ) -> ( u64 , bool ) {
62
+ let ( a, b) = lhs. overflowing_add ( rhs) ;
63
+ let ( c, d) = a. overflowing_add ( carry as u64 ) ;
64
+ ( c, b || d)
65
+ }
66
+
59
67
if BITS == 0 {
60
68
return ( Self :: ZERO , false ) ;
61
69
}
62
- let mut carry = 0_u128 ;
70
+ let mut carry = false ;
63
71
let mut i = 0 ;
64
- #[ allow( clippy:: cast_possible_truncation) ] // Intentional
65
72
while i < LIMBS {
66
- carry += self . limbs [ i] as u128 + rhs. limbs [ i] as u128 ;
67
- self . limbs [ i] = carry as u64 ;
68
- carry >>= 64 ;
73
+ ( self . limbs [ i] , carry) = u64_carrying_add ( self . limbs [ i] , rhs. limbs [ i] , carry) ;
69
74
i += 1 ;
70
75
}
71
- let overflow = carry != 0 || self . limbs [ LIMBS - 1 ] > Self :: MASK ;
76
+ let overflow = carry || self . limbs [ LIMBS - 1 ] > Self :: MASK ;
72
77
self . limbs [ LIMBS - 1 ] &= Self :: MASK ;
73
78
( self , overflow)
74
79
}
@@ -93,20 +98,24 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
93
98
#[ inline]
94
99
#[ must_use]
95
100
pub const fn overflowing_sub ( mut self , rhs : Self ) -> ( Self , bool ) {
101
+ // TODO: Replace with `u64::borrowing_sub` once stable.
102
+ #[ inline]
103
+ const fn u64_borrowing_sub ( lhs : u64 , rhs : u64 , borrow : bool ) -> ( u64 , bool ) {
104
+ let ( a, b) = lhs. overflowing_sub ( rhs) ;
105
+ let ( c, d) = a. overflowing_sub ( borrow as u64 ) ;
106
+ ( c, b || d)
107
+ }
108
+
96
109
if BITS == 0 {
97
110
return ( Self :: ZERO , false ) ;
98
111
}
99
- let mut carry = 0_i128 ;
112
+ let mut borrow = false ;
100
113
let mut i = 0 ;
101
- #[ allow( clippy:: cast_possible_truncation) ] // Intentional
102
- #[ allow( clippy:: cast_sign_loss) ] // Intentional
103
114
while i < LIMBS {
104
- carry += self . limbs [ i] as i128 - rhs. limbs [ i] as i128 ;
105
- self . limbs [ i] = carry as u64 ;
106
- carry >>= 64 ;
115
+ ( self . limbs [ i] , borrow) = u64_borrowing_sub ( self . limbs [ i] , rhs. limbs [ i] , borrow) ;
107
116
i += 1 ;
108
117
}
109
- let overflow = carry != 0 || self . limbs [ LIMBS - 1 ] > Self :: MASK ;
118
+ let overflow = borrow || self . limbs [ LIMBS - 1 ] > Self :: MASK ;
110
119
self . limbs [ LIMBS - 1 ] &= Self :: MASK ;
111
120
( self , overflow)
112
121
}
0 commit comments