From 03156e589939993bba339162d27d24fd511601c6 Mon Sep 17 00:00:00 2001 From: Isaac Freund Date: Mon, 12 Jul 2021 18:32:02 +0200 Subject: std/hash_map: fix ensureUnusedCapacity() over-allocating Currently this function adds the desired unused capactiy to the current total capacity instead of the current used capactiy. --- lib/std/hash_map.zig | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'lib/std') diff --git a/lib/std/hash_map.zig b/lib/std/hash_map.zig index d6762c9d3b..ef97e7d7fa 100644 --- a/lib/std/hash_map.zig +++ b/lib/std/hash_map.zig @@ -848,7 +848,7 @@ pub fn HashMapUnmanaged( return ensureUnusedCapacityContext(self, allocator, additional_size, undefined); } pub fn ensureUnusedCapacityContext(self: *Self, allocator: *Allocator, additional_size: Size, ctx: Context) !void { - return ensureTotalCapacityContext(self, allocator, self.capacity() + additional_size, ctx); + return ensureTotalCapacityContext(self, allocator, self.count() + additional_size, ctx); } pub fn clearRetainingCapacity(self: *Self) void { @@ -1956,6 +1956,19 @@ test "std.hash_map getOrPutAdapted" { } } +test "std.hash_map ensureUnusedCapacity" { + var map = AutoHashMap(u64, u64).init(testing.allocator); + defer map.deinit(); + + try map.ensureUnusedCapacity(32); + const capacity = map.capacity(); + try map.ensureUnusedCapacity(32); + + // Repeated ensureUnusedCapacity() calls with no insertions between + // should not change the capacity. + try testing.expectEqual(capacity, map.capacity()); +} + test "compile everything" { std.testing.refAllDecls(AutoHashMap(i32, i32)); std.testing.refAllDecls(StringHashMap([]const u8)); -- cgit v1.2.3