Commit 2279f27e0f

Yujiri <yujiri@disroot.org>
2022-08-12 13:56:00
Fix #12423: auto_hash not hashing arrays of slices uniquely
1 parent d234237
Changed files (1)
lib
std
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,