Skip to content

Commit 3472e2f

Browse files
committed
Merge #81: Avoid overflowing shift by special casing inverse of 1
653d8b2 Avoid overflowing shift by special casing inverse of 1 (Pieter Wuille) Pull request description: When `x=1`, then `rlen = BITS+1` and `newrlen = 1`, and thus in the first loop iteration `q = BITS`, leading to a shift by `BITS` bits, which may overflow the integer type. Avoid this situation by special casing `x=1`. The inverse of `1` is always `1` anyway. ACKs for top commit: theuni: Trivial ACK 653d8b2. This does that :) Tree-SHA512: 32b1bc859c5d934b11ab3f6bc388d59a07c1155184135fee47e1f73c0d5b2bd1b325b9b111b7fe552c1d8bb0cb3214f214fa72b1024b5fadad0dd363f65559eb
2 parents 33b7c20 + 653d8b2 commit 3472e2f

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

src/int_utils.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ class BitsInt {
194194
}
195195

196196
static constexpr inline bool IsZero(I a) { return a == 0; }
197+
static constexpr inline bool IsOne(I a) { return a == 1; }
197198
static constexpr inline I Mask(I val) { return val & MASK; }
198199
static constexpr inline I Shift(I val, int bits) { return ((val << bits) & MASK); }
199200
static constexpr inline I UnsafeShift(I val, int bits) { return (val << bits); }
@@ -252,7 +253,7 @@ template<typename I, int N, typename L, typename F> inline constexpr I GFMul(con
252253
template<typename I, typename F, int BITS, uint32_t MOD>
253254
inline I InvExtGCD(I x)
254255
{
255-
if (F::IsZero(x)) return x;
256+
if (F::IsZero(x) || F::IsOne(x)) return x;
256257
I t(0), newt(1);
257258
I r(MOD), newr = x;
258259
int rlen = BITS + 1, newrlen = F::Bits(newr, BITS);

0 commit comments

Comments
 (0)