From ed19ebc3605ec7e50166adf45f162dcf5540c42e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20L=C3=BChmann?= Date: Fri, 29 Sep 2023 07:09:47 +0200 Subject: [PATCH] std.math.big.int.Const.order 0 == -0 (#17299) --- lib/std/math/big/int.zig | 6 +++++- lib/std/math/big/int_test.zig | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 3e6d52e9f7d4..93c21f021699 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -2452,7 +2452,11 @@ pub const Const = struct { /// Returns `math.Order.lt`, `math.Order.eq`, `math.Order.gt` if `a < b`, `a == b` or `a > b` respectively. pub fn order(a: Const, b: Const) math.Order { if (a.positive != b.positive) { - return if (a.positive) .gt else .lt; + if (eqlZero(a) and eqlZero(b)) { + return .eq; + } else { + return if (a.positive) .gt else .lt; + } } else { const r = orderAbs(a, b); return if (a.positive) r else switch (r) { diff --git a/lib/std/math/big/int_test.zig b/lib/std/math/big/int_test.zig index 8215cea4d25e..668f07b32d98 100644 --- a/lib/std/math/big/int_test.zig +++ b/lib/std/math/big/int_test.zig @@ -3105,3 +3105,36 @@ test "big.int sqr multi alias r with a" { try testing.expectEqual(@as(usize, 5), a.limbs.len); } } + +test "big.int eql zeroes #17296" { + var zero = try Managed.init(testing.allocator); + defer zero.deinit(); + try zero.setString(10, "0"); + try std.testing.expect(zero.eql(zero)); + + { + var sum = try Managed.init(testing.allocator); + defer sum.deinit(); + try sum.add(&zero, &zero); + try std.testing.expect(zero.eql(sum)); + } + + { + var diff = try Managed.init(testing.allocator); + defer diff.deinit(); + try diff.sub(&zero, &zero); + try std.testing.expect(zero.eql(diff)); + } +} + +test "big.int.Const.order 0 == -0" { + const a = std.math.big.int.Const{ + .limbs = &.{0}, + .positive = true, + }; + const b = std.math.big.int.Const{ + .limbs = &.{0}, + .positive = false, + }; + try std.testing.expectEqual(std.math.Order.eq, a.order(b)); +}