Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.math.big.int: fix shiftRight sign handling #21320

Merged
merged 1 commit into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/std/math/big/int.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,7 @@ pub const Mutable = struct {
llshr(r.limbs[0..], a.limbs[0..a.limbs.len], shift);

r.len = a.limbs.len - full_limbs_shifted_out;
r.positive = a.positive;
if (nonzero_negative_shiftout) {
if (full_limbs_shifted_out > 0) {
r.limbs[a.limbs.len - full_limbs_shifted_out] = 0;
Expand All @@ -1210,7 +1211,6 @@ pub const Mutable = struct {
r.addScalar(r.toConst(), -1);
}
r.normalize(r.len);
r.positive = a.positive;
}

/// r = ~a under 2s complement wrapping semantics.
Expand Down
9 changes: 9 additions & 0 deletions lib/std/math/big/int_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2083,6 +2083,15 @@ test "shift-right negative" {
try a.shiftRight(&a, 1);
a.setSign(true);
try testing.expect(try a.to(u64) == 0x8000000000000000);

var arg7 = try Managed.initSet(testing.allocator, -32767);
defer arg7.deinit();
a.setSign(false);
try a.shiftRight(&arg7, 4);
try testing.expect(try a.to(i16) == -2048);
a.setSign(true);
try a.shiftRight(&arg7, 4);
try testing.expect(try a.to(i16) == -2048);
}

test "sat shift-left simple unsigned" {
Expand Down