Skip to content

Commit aff2be0

Browse files
committed
big.int: fix negative multi-limb shift right adjust crash
1 parent 8e15321 commit aff2be0

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

lib/std/math/big/int.zig

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

21962205
test "sat shift-left simple unsigned" {

0 commit comments

Comments
 (0)