authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2021-09-16 17:20:42-07:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2021-09-19 13:52:56+02:00
log2be3b1d2bfd4bab61a481226fd1d714512ea2f44
treedc290d281534f21362fa739e747bb8a5b948dd42
parentcfe71cb67a3cf3814ce12d2a2d87192ef905b9fd

std.PriorityQueue: ensureUnusedCapacity and ensureTotalCapacity

Same as c8ae581fef6506a8234cdba1355ba7f0f449031a, but for PriorityQueue.

1 files changed, 13 insertions(+), 4 deletions(-)

lib/std/priority_queue.zig+13-4
......@@ -42,7 +42,7 @@ pub fn PriorityQueue(comptime T: type) type {
4242
4343 /// Insert a new element, maintaining priority.
4444 pub fn add(self: *Self, elem: T) !void {
45 try ensureCapacity(self, self.len + 1);
45 try self.ensureUnusedCapacity(1);
4646 addUnchecked(self, elem);
4747 }
4848
......@@ -69,7 +69,7 @@ pub fn PriorityQueue(comptime T: type) type {
6969
7070 /// Add each element in `items` to the queue.
7171 pub fn addSlice(self: *Self, items: []const T) !void {
72 try self.ensureCapacity(self.len + items.len);
72 try self.ensureUnusedCapacity(items.len);
7373 for (items) |e| {
7474 self.addUnchecked(e);
7575 }
......@@ -175,7 +175,11 @@ pub fn PriorityQueue(comptime T: type) type {
175175 return queue;
176176 }
177177
178 pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
178 /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
179 pub const ensureCapacity = ensureTotalCapacity;
180
181 /// Ensure that the queue can fit at least `new_capacity` items.
182 pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
179183 var better_capacity = self.capacity();
180184 if (better_capacity >= new_capacity) return;
181185 while (true) {
......@@ -185,6 +189,11 @@ pub fn PriorityQueue(comptime T: type) type {
185189 self.items = try self.allocator.realloc(self.items, better_capacity);
186190 }
187191
192 /// Ensure that the queue can fit at least `additional_count` **more** item.
193 pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
194 return self.ensureTotalCapacity(self.len + additional_count);
195 }
196
188197 /// Reduce allocated capacity to `new_len`.
189198 pub fn shrinkAndFree(self: *Self, new_len: usize) void {
190199 assert(new_len <= self.items.len);
......@@ -483,7 +492,7 @@ test "std.PriorityQueue: shrinkAndFree" {
483492 var queue = PQ.init(testing.allocator, lessThan);
484493 defer queue.deinit();
485494
486 try queue.ensureCapacity(4);
495 try queue.ensureTotalCapacity(4);
487496 try expect(queue.capacity() >= 4);
488497
489498 try queue.add(1);