authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2022-11-28 04:37:47-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-11-28 07:40:09-05:00
logd9a51648e6b1f1765089e0a50570d86b95b819e9
tree5fef7aa3ee822d7d8a2b80ac37a368fbb25c1af9
parentf98aac9db4ddc4790684e5411798087ec18b011a

std.big.int.Mutable: fix set(@as(DoubleLimb, 0))

Previously, this would set len to 1 but fail to initialize any limbs.

2 files changed, 14 insertions(+), 2 deletions(-)

lib/std/math/big/int.zig+6-2
...@@ -238,12 +238,14 @@ pub const Mutable = struct {...@@ -238,12 +238,14 @@ pub const Mutable = struct {
238 self.limbs[0] = w_value;238 self.limbs[0] = w_value;
239 } else {239 } else {
240 var i: usize = 0;240 var i: usize = 0;
241 while (w_value != 0) : (i += 1) {241 while (true) : (i += 1) {
242 self.limbs[i] = @truncate(Limb, w_value);242 self.limbs[i] = @truncate(Limb, w_value);
243243
244 // TODO: shift == 64 at compile-time fails. Fails on u128 limbs.244 // TODO: shift == 64 at compile-time fails. Fails on u128 limbs.
245 w_value >>= limb_bits / 2;245 w_value >>= limb_bits / 2;
246 w_value >>= limb_bits / 2;246 w_value >>= limb_bits / 2;
247
248 if (w_value == 0) break;
247 }249 }
248 }250 }
249 },251 },
...@@ -256,11 +258,13 @@ pub const Mutable = struct {...@@ -256,11 +258,13 @@ pub const Mutable = struct {
256 const mask = (1 << limb_bits) - 1;258 const mask = (1 << limb_bits) - 1;
257259
258 comptime var i = 0;260 comptime var i = 0;
259 inline while (w_value != 0) : (i += 1) {261 inline while (true) : (i += 1) {
260 self.limbs[i] = w_value & mask;262 self.limbs[i] = w_value & mask;
261263
262 w_value >>= limb_bits / 2;264 w_value >>= limb_bits / 2;
263 w_value >>= limb_bits / 2;265 w_value >>= limb_bits / 2;
266
267 if (w_value == 0) break;
264 }268 }
265 }269 }
266 },270 },
lib/std/math/big/int_test.zig+8
...@@ -69,6 +69,14 @@ test "big.int set negative minimum" {...@@ -69,6 +69,14 @@ test "big.int set negative minimum" {
69 try testing.expect((try a.to(i64)) == minInt(i64));69 try testing.expect((try a.to(i64)) == minInt(i64));
70}70}
7171
72test "big.int set double-width maximum then zero" {
73 var a = try Managed.initSet(testing.allocator, maxInt(DoubleLimb));
74 defer a.deinit();
75 try a.set(@as(DoubleLimb, 0));
76
77 try testing.expectEqual(@as(DoubleLimb, 0), try a.to(DoubleLimb));
78}
79
72test "big.int to target too small error" {80test "big.int to target too small error" {
73 var a = try Managed.initSet(testing.allocator, 0xffffffff);81 var a = try Managed.initSet(testing.allocator, 0xffffffff);
74 defer a.deinit();82 defer a.deinit();