authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2025-03-12 22:04:41-04:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2025-03-21 21:51:08-04:00
logaff2be01c95516489ba8355f4de6218c92608b8e
tree9d121cb6abfd8eb276aa785c361ce56e2845a32c
parent8e15321c7cd2386dd63533fd3cbc31ec32873d83

big.int: fix negative multi-limb shift right adjust crash


2 files changed, 13 insertions(+), 10 deletions(-)

lib/std/math/big/int.zig+4-10
......@@ -1096,7 +1096,7 @@ pub const Mutable = struct {
10961096 /// Asserts there is enough memory to fit the result. The upper bound Limb count is
10971097 /// `a.limbs.len + (shift / (@sizeOf(Limb) * 8))`.
10981098 pub fn shiftLeft(r: *Mutable, a: Const, shift: usize) void {
1099 llshl(r.limbs[0..], a.limbs[0..a.limbs.len], shift);
1099 llshl(r.limbs, a.limbs, shift);
11001100 r.normalize(a.limbs.len + (shift / limb_bits) + 1);
11011101 r.positive = a.positive;
11021102 }
......@@ -1165,7 +1165,7 @@ pub const Mutable = struct {
11651165
11661166 // This shift should not be able to overflow, so invoke llshl and normalize manually
11671167 // to avoid the extra required limb.
1168 llshl(r.limbs[0..], a.limbs[0..a.limbs.len], shift);
1168 llshl(r.limbs, a.limbs, shift);
11691169 r.normalize(a.limbs.len + (shift / limb_bits));
11701170 r.positive = a.positive;
11711171 }
......@@ -1202,17 +1202,11 @@ pub const Mutable = struct {
12021202 break :nonzero a.limbs[full_limbs_shifted_out] << not_covered != 0;
12031203 };
12041204
1205 llshr(r.limbs[0..], a.limbs[0..a.limbs.len], shift);
1205 llshr(r.limbs, a.limbs, shift);
12061206
12071207 r.len = a.limbs.len - full_limbs_shifted_out;
12081208 r.positive = a.positive;
1209 if (nonzero_negative_shiftout) {
1210 if (full_limbs_shifted_out > 0) {
1211 r.limbs[a.limbs.len - full_limbs_shifted_out] = 0;
1212 r.len += 1;
1213 }
1214 r.addScalar(r.toConst(), -1);
1215 }
1209 if (nonzero_negative_shiftout) r.addScalar(r.toConst(), -1);
12161210 r.normalize(r.len);
12171211 }
12181212
lib/std/math/big/int_test.zig+9
......@@ -2191,6 +2191,15 @@ test "shift-right negative" {
21912191 a.setSign(true);
21922192 try a.shiftRight(&arg7, 4);
21932193 try testing.expect(try a.toInt(i16) == -2048);
2194
2195 var arg8_limbs: [1]Limb = undefined;
2196 var arg8: Mutable = .{
2197 .limbs = &arg8_limbs,
2198 .len = undefined,
2199 .positive = undefined,
2200 };
2201 arg8.shiftRight(.{ .limbs = &.{ 1, 1 }, .positive = false }, @bitSizeOf(Limb));
2202 try testing.expect(arg8.toConst().orderAgainstScalar(-2).compare(.eq));
21942203}
21952204
21962205test "sat shift-left simple unsigned" {