Commit 34dae73005

Andrew Kelley <andrew@ziglang.org>
2023-06-02 08:45:36
std.hash: auto hash signed ints as bitcasts of unsigned ints
1 parent e017964
Changed files (1)
lib
std
lib/std/hash/auto_hash.zig
@@ -91,15 +91,21 @@ pub fn hash(hasher: anytype, key: anytype, comptime strat: HashStrategy) void {
 
         // Help the optimizer see that hashing an int is easy by inlining!
         // TODO Check if the situation is better after #561 is resolved.
-        .Int => {
-            if (comptime meta.trait.hasUniqueRepresentation(Key)) {
-                @call(.always_inline, Hasher.update, .{ hasher, std.mem.asBytes(&key) });
-            } else {
-                // Take only the part containing the key value, the remaining
-                // bytes are undefined and must not be hashed!
-                const byte_size = comptime std.math.divCeil(comptime_int, @bitSizeOf(Key), 8) catch unreachable;
-                @call(.always_inline, Hasher.update, .{ hasher, std.mem.asBytes(&key)[0..byte_size] });
-            }
+        .Int => |int| switch (int.signedness) {
+            .signed => hash(hasher, @bitCast(@Type(.{ .Int = .{
+                .bits = int.bits,
+                .signedness = .unsigned,
+            } }), key), strat),
+            .unsigned => {
+                if (comptime meta.trait.hasUniqueRepresentation(Key)) {
+                    @call(.always_inline, Hasher.update, .{ hasher, std.mem.asBytes(&key) });
+                } else {
+                    // Take only the part containing the key value, the remaining
+                    // bytes are undefined and must not be hashed!
+                    const byte_size = comptime std.math.divCeil(comptime_int, @bitSizeOf(Key), 8) catch unreachable;
+                    @call(.always_inline, Hasher.update, .{ hasher, std.mem.asBytes(&key)[0..byte_size] });
+                }
+            },
         },
 
         .Bool => hash(hasher, @boolToInt(key), strat),