aboutsummaryrefslogtreecommitdiff
path: root/lib/std/priority_queue.zig
diff options
context:
space:
mode:
authorRyan Liptak <squeek502@hotmail.com>2021-09-16 17:20:42 -0700
committerIsaac Freund <ifreund@ifreund.xyz>2021-09-19 13:52:56 +0200
commit2be3b1d2bfd4bab61a481226fd1d714512ea2f44 (patch)
treedc290d281534f21362fa739e747bb8a5b948dd42 /lib/std/priority_queue.zig
parentcfe71cb67a3cf3814ce12d2a2d87192ef905b9fd (diff)
downloadzig-2be3b1d2bfd4bab61a481226fd1d714512ea2f44.tar.gz
zig-2be3b1d2bfd4bab61a481226fd1d714512ea2f44.zip
std.PriorityQueue: ensureUnusedCapacity and ensureTotalCapacity
Same as c8ae581fef6506a8234cdba1355ba7f0f449031a, but for PriorityQueue.
Diffstat (limited to 'lib/std/priority_queue.zig')
-rw-r--r--lib/std/priority_queue.zig17
1 files changed, 13 insertions, 4 deletions
diff --git a/lib/std/priority_queue.zig b/lib/std/priority_queue.zig
index 228c07cadb..fcdd81b1dd 100644
--- a/lib/std/priority_queue.zig
+++ b/lib/std/priority_queue.zig
@@ -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);