Skip to content

Commit cdc9d65

Browse files
dweillerifreund
authored andcommitted
std.priority_queue: add useful functions from ArrayList API
The `ensureTotalCapacityPrecise`, `clearRetainingCapacity` and `clearAndFree` functions from the ArrayList API are also useful for a PriorityQueue.
1 parent 3924f17 commit cdc9d65

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

lib/std/priority_queue.zig

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,14 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF
182182
better_capacity += better_capacity / 2 + 8;
183183
if (better_capacity >= new_capacity) break;
184184
}
185+
try self.ensureTotalCapacityPrecise(better_capacity);
186+
}
187+
188+
pub fn ensureTotalCapacityPrecise(self: *Self, new_capacity: usize) !void {
189+
if (self.capacity() >= new_capacity) return;
190+
185191
const old_memory = self.allocatedSlice();
186-
const new_memory = try self.allocator.realloc(old_memory, better_capacity);
192+
const new_memory = try self.allocator.realloc(old_memory, new_capacity);
187193
self.items.ptr = new_memory.ptr;
188194
self.cap = new_memory.len;
189195
}
@@ -211,6 +217,16 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF
211217
self.cap = new_memory.len;
212218
}
213219

220+
pub fn clearRetainingCapacity(self: *Self) void {
221+
self.items.len = 0;
222+
}
223+
224+
pub fn clearAndFree(self: *Self) void {
225+
self.allocator.free(self.allocatedSlice());
226+
self.items.len = 0;
227+
self.cap = 0;
228+
}
229+
214230
pub fn update(self: *Self, elem: T, new_elem: T) !void {
215231
const update_index = blk: {
216232
var idx: usize = 0;

0 commit comments

Comments
 (0)