Commit 4bc18c52f7

Andrew Kelley <andrew@ziglang.org>
2024-03-20 19:13:50
std.hash_map: fix pointer lock safety false positive
closes #19358
1 parent 19b6995
Changed files (1)
lib
lib/std/hash_map.zig
@@ -1559,9 +1559,9 @@ pub fn HashMapUnmanaged(
             assert(std.math.isPowerOfTwo(new_cap));
 
             var map: Self = .{};
-            defer map.deinit(allocator);
-            map.pointer_stability.lock();
             try map.allocate(allocator, new_cap);
+            errdefer comptime unreachable;
+            map.pointer_stability.lock();
             map.initMetadatas();
             map.available = @truncate((new_cap * max_load_percentage) / 100);
 
@@ -1581,6 +1581,7 @@ pub fn HashMapUnmanaged(
             self.size = 0;
             self.pointer_stability = .{ .state = .unlocked };
             std.mem.swap(Self, self, &map);
+            map.deinit(allocator);
         }
 
         fn allocate(self: *Self, allocator: Allocator, new_capacity: Size) Allocator.Error!void {
@@ -2266,3 +2267,8 @@ test "repeat fetchRemove" {
     try testing.expect(map.get(2) != null);
     try testing.expect(map.get(3) != null);
 }
+
+test "getOrPut allocation failure" {
+    var map: std.StringHashMapUnmanaged(void) = .{};
+    try testing.expectError(error.OutOfMemory, map.getOrPut(std.testing.failing_allocator, "hello"));
+}