Commit ed19ebc360

Philipp Lühmann <philipp@luehmann.dev>
2023-09-29 07:09:47
std.math.big.int.Const.order 0 == -0 (#17299)
1 parent acac685
Changed files (2)
lib
std
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) {
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));
+}