authorgravatar for 4678790+dweiller@users.noreply.github.comDominic <4678790+dweiller@users.noreply.github.com> 2024-06-14 00:18:58+10:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2025-02-01 19:02:39+01:00
logcdc9d65b0db3e988ae0f4006e05c178312518bfb
tree714e6ac45f8b0617ec77ad3b7cb236d29f4f2215
parent3924f173af51c50ac18be2166fe115555241778e

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 files changed, 17 insertions(+), 1 deletions(-)

lib/std/priority_queue.zig+17-1
...@@ -182,8 +182,14 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF...@@ -182,8 +182,14 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF
182 better_capacity += better_capacity / 2 + 8;182 better_capacity += better_capacity / 2 + 8;
183 if (better_capacity >= new_capacity) break;183 if (better_capacity >= new_capacity) break;
184 }184 }
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
185 const old_memory = self.allocatedSlice();191 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);
187 self.items.ptr = new_memory.ptr;193 self.items.ptr = new_memory.ptr;
188 self.cap = new_memory.len;194 self.cap = new_memory.len;
189 }195 }
...@@ -211,6 +217,16 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF...@@ -211,6 +217,16 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF
211 self.cap = new_memory.len;217 self.cap = new_memory.len;
212 }218 }
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
214 pub fn update(self: *Self, elem: T, new_elem: T) !void {230 pub fn update(self: *Self, elem: T, new_elem: T) !void {
215 const update_index = blk: {231 const update_index = blk: {
216 var idx: usize = 0;232 var idx: usize = 0;