Commit a3342cea18

Andrew Kelley <andrew@ziglang.org>
2024-11-23 00:10:34
std.mem.eql: make comparisons for zero-sized and non-sized types work
The `if (@sizeOf(T) == 0) return true;` check simply doesn't work for a number of cases so that is removed and changed into `@sizeOf(T) != 0` and then used in the `eqlBytes` check chain to make comparing `enum{}`s possible. The rest special-cases for comptime-only types and undefined to make those comparisons possible as well. Fixes #19929
1 parent 73dcd19
Changed files (1)
lib
lib/std/mem.zig
@@ -656,7 +656,18 @@ const eqlBytes_allowed = switch (builtin.zig_backend) {
 
 /// Compares two slices and returns whether they are equal.
 pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
-    if (@sizeOf(T) == 0) return true;
+    switch (@typeInfo(T)) {
+        .Type, .ComptimeInt, .ComptimeFloat => {
+            if (a.len != b.len) return false;
+            inline for (a, b) |a_elem, b_elem| {
+                if (a_elem != b_elem) return false;
+            }
+            return true;
+        },
+        .Null, .Undefined => return a.len == b.len,
+        else => {},
+    }
+    if (@sizeOf(T) == 0) return a.len == b.len;
     if (!@inComptime() and std.meta.hasUniqueRepresentation(T) and eqlBytes_allowed) return eqlBytes(sliceAsBytes(a), sliceAsBytes(b));
 
     if (a.len != b.len) return false;
@@ -3296,6 +3307,26 @@ test eql {
     try testing.expect(eql(u8, "abcd", "abcd"));
     try testing.expect(!eql(u8, "abcdef", "abZdef"));
     try testing.expect(!eql(u8, "abcdefg", "abcdef"));
+
+    try testing.expect(eql(type, &.{ bool, f32 }, &.{ bool, f32 }));
+    try testing.expect(!eql(type, &.{ bool, f32 }, &.{ f32, bool }));
+    try testing.expect(!eql(type, &.{ bool, f32 }, &.{bool}));
+
+    try testing.expect(eql(comptime_int, &.{ 1, 2, 3 }, &.{ 1, 2, 3 }));
+    try testing.expect(!eql(comptime_int, &.{ 1, 2, 3 }, &.{ 3, 2, 1 }));
+    try testing.expect(!eql(comptime_int, &.{1}, &.{ 1, 2 }));
+
+    try testing.expect(eql(@TypeOf(undefined), &.{ undefined, undefined }, &.{ undefined, undefined }));
+    try testing.expect(!eql(@TypeOf(undefined), &.{undefined}, &.{ undefined, undefined }));
+
+    try testing.expect(eql(enum {}, &.{ undefined, undefined }, &.{ undefined, undefined }));
+    try testing.expect(!eql(enum {}, &.{undefined}, &.{ undefined, undefined }));
+
+    try testing.expect(eql(void, &.{ {}, {} }, &.{ {}, {} }));
+    try testing.expect(!eql(void, &.{{}}, &.{ {}, {} }));
+
+    try testing.expect(eql(@TypeOf(null), &.{ null, null }, &.{ null, null }));
+    try testing.expect(!eql(@TypeOf(null), &.{null}, &.{ null, null }));
 }
 
 fn moreReadIntTests() !void {