authorgravatar for red.black.liquorice@gmail.comHila Friedman <red.black.liquorice@gmail.com> 2026-06-26 15:50:53+03:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-08-05 03:17:02+02:00
log6afdd3370a50fe4a20108363b6b7d31e93765cd2
treed752150deb2faaef0e0af3d466ba204a8ac8d6b2
parent867ab50575b89de123c852aa74b481966f00d8eb

handle non-reflexive types in std.mem.eql and std.mem.findDiff


1 files changed, 21 insertions(+), 12 deletions(-)

lib/std/mem.zig+21-12
......@@ -756,7 +756,8 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
756756 }
757757
758758 if (a.len != b.len) return false;
759 if (a.len == 0 or a.ptr == b.ptr) return true;
759 if (a.len == 0) return true;
760 if (@typeInfo(T) != .float and a.ptr == b.ptr) return true;
760761
761762 for (a, b) |a_elem, b_elem| {
762763 if (a_elem != b_elem) return false;
......@@ -781,6 +782,9 @@ test eql {
781782
782783 try testing.expect(eql(void, &.{ {}, {} }, &.{ {}, {} }));
783784 try testing.expect(!eql(void, &.{{}}, &.{ {}, {} }));
785
786 const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
787 try testing.expect(!eql(f64, &x, &x));
784788}
785789
786790/// std.mem.eql heavily optimized for slices of bytes.
......@@ -850,20 +854,25 @@ pub const indexOfDiff = findDiff;
850854/// Compares two slices and returns the index of the first inequality.
851855/// Returns null if the slices are equal.
852856pub fn findDiff(comptime T: type, a: []const T, b: []const T) ?usize {
853 const shortest = @min(a.len, b.len);
854 if (a.ptr == b.ptr)
855 return if (a.len == b.len) null else shortest;
856 var index: usize = 0;
857 while (index < shortest) : (index += 1) if (a[index] != b[index]) return index;
858 return if (a.len == b.len) null else shortest;
857 const shorter = @min(a.len, b.len);
858 if (@typeInfo(T) != .float and a.ptr == b.ptr) {
859 return if (a.len == b.len) null else shorter;
860 }
861 for (a[0..shorter], b[0..shorter], 0..) |a_elem, b_elem, i| {
862 if (a_elem != b_elem) return i;
863 }
864 return if (a.len == b.len) null else shorter;
859865}
860866
861867test findDiff {
862 try testing.expectEqual(findDiff(u8, "one", "one"), null);
863 try testing.expectEqual(findDiff(u8, "one two", "one"), 3);
864 try testing.expectEqual(findDiff(u8, "one", "one two"), 3);
865 try testing.expectEqual(findDiff(u8, "one twx", "one two"), 6);
866 try testing.expectEqual(findDiff(u8, "xne", "one"), 0);
868 try testing.expectEqual(null, findDiff(u8, "one", "one"));
869 try testing.expectEqual(3, findDiff(u8, "one two", "one"));
870 try testing.expectEqual(3, findDiff(u8, "one", "one two"));
871 try testing.expectEqual(6, findDiff(u8, "one twx", "one two"));
872 try testing.expectEqual(0, findDiff(u8, "xne", "one"));
873
874 const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
875 try testing.expectEqual(1, findDiff(f64, &x, &x));
867876}
868877
869878/// Takes a sentinel-terminated pointer and returns a slice preserving pointer attributes.