std.PriorityQueue: ensureUnusedCapacity and ensureTotalCapacity

Same as c8ae581fef6506a8234cdba1355ba7f0f449031a, but for PriorityQueue.
This commit is contained in:
Ryan Liptak 2021-09-16 17:20:42 -07:00 committed by Isaac Freund
parent cfe71cb67a
commit 2be3b1d2bf

View File

@ -42,7 +42,7 @@ pub fn PriorityQueue(comptime T: type) type {
/// Insert a new element, maintaining priority.
pub fn add(self: *Self, elem: T) !void {
try ensureCapacity(self, self.len + 1);
try self.ensureUnusedCapacity(1);
addUnchecked(self, elem);
}
@ -69,7 +69,7 @@ pub fn PriorityQueue(comptime T: type) type {
/// Add each element in `items` to the queue.
pub fn addSlice(self: *Self, items: []const T) !void {
try self.ensureCapacity(self.len + items.len);
try self.ensureUnusedCapacity(items.len);
for (items) |e| {
self.addUnchecked(e);
}
@ -175,7 +175,11 @@ pub fn PriorityQueue(comptime T: type) type {
return queue;
}
pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Ensure that the queue can fit at least `new_capacity` items.
pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
var better_capacity = self.capacity();
if (better_capacity >= new_capacity) return;
while (true) {
@ -185,6 +189,11 @@ pub fn PriorityQueue(comptime T: type) type {
self.items = try self.allocator.realloc(self.items, better_capacity);
}
/// Ensure that the queue can fit at least `additional_count` **more** item.
pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
return self.ensureTotalCapacity(self.len + additional_count);
}
/// Reduce allocated capacity to `new_len`.
pub fn shrinkAndFree(self: *Self, new_len: usize) void {
assert(new_len <= self.items.len);
@ -483,7 +492,7 @@ test "std.PriorityQueue: shrinkAndFree" {
var queue = PQ.init(testing.allocator, lessThan);
defer queue.deinit();
try queue.ensureCapacity(4);
try queue.ensureTotalCapacity(4);
try expect(queue.capacity() >= 4);
try queue.add(1);