Skip to content

Commit

Permalink
std/hash_map: fix ensureUnusedCapacity() over-allocating
Browse files Browse the repository at this point in the history
Currently this function adds the desired unused capactiy to the current
total capacity instead of the current used capactiy.
  • Loading branch information
ifreund authored and andrewrk committed Jul 12, 2021
1 parent 3063f0a commit 03156e5
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/std/hash_map.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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));
Expand Down

0 comments on commit 03156e5

Please sign in to comment.