From 2279f27e0f97e66aedc87ec5c85f05b185a3631d Mon Sep 17 00:00:00 2001 From: Yujiri Date: Fri, 12 Aug 2022 11:56:00 +0000 Subject: [PATCH] Fix #12423: auto_hash not hashing arrays of slices uniquely --- lib/std/hash/auto_hash.zig | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/lib/std/hash/auto_hash.zig b/lib/std/hash/auto_hash.zig index 951c0148d9..32f4f4378f 100644 --- a/lib/std/hash/auto_hash.zig +++ b/lib/std/hash/auto_hash.zig @@ -30,13 +30,15 @@ pub fn hashPointer(hasher: anytype, key: anytype, comptime strat: HashStrategy) .DeepRecursive => hash(hasher, key.*, .DeepRecursive), }, - .Slice => switch (strat) { - .Shallow => { - hashPointer(hasher, key.ptr, .Shallow); - hash(hasher, key.len, .Shallow); - }, - .Deep => hashArray(hasher, key, .Shallow), - .DeepRecursive => hashArray(hasher, key, .DeepRecursive), + .Slice => { + switch (strat) { + .Shallow => { + hashPointer(hasher, key.ptr, .Shallow); + }, + .Deep => hashArray(hasher, key, .Shallow), + .DeepRecursive => hashArray(hasher, key, .DeepRecursive), + } + hash(hasher, key.len, .Shallow); }, .Many, @@ -53,17 +55,8 @@ pub fn hashPointer(hasher: anytype, key: anytype, comptime strat: HashStrategy) /// Helper function to hash a set of contiguous objects, from an array or slice. pub fn hashArray(hasher: anytype, key: anytype, comptime strat: HashStrategy) void { - switch (strat) { - .Shallow => { - for (key) |element| { - hash(hasher, element, .Shallow); - } - }, - else => { - for (key) |element| { - hash(hasher, element, strat); - } - }, + for (key) |element| { + hash(hasher, element, strat); } } @@ -359,6 +352,12 @@ test "testHash array" { try testing.expectEqual(h, hasher.final()); } +test "testHash multi-dimensional array" { + const a = [_][]const u32{ &.{ 1, 2, 3 }, &.{ 4, 5 } }; + const b = [_][]const u32{ &.{ 1, 2 }, &.{ 3, 4, 5 } }; + try testing.expect(testHash(a) != testHash(b)); +} + test "testHash struct" { const Foo = struct { a: u32 = 1,