From a3342cea188e1c006b20dd2e4712398f9e8c7fdd Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 22 Nov 2024 15:10:34 -0800 Subject: [PATCH] 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 --- lib/std/mem.zig | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 039b9d4324..53b7d29567 100644 --- a/lib/std/mem.zig +++ b/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 {