authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2021-09-16 17:21:19-07:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2021-09-19 13:52:56+02:00
logfeeb25908bebd5d09cf05128fad7d7c1a8a803a1
tree030e1e9a32c10f7c0428b6c208e5c1446fc2cf28
parent2be3b1d2bfd4bab61a481226fd1d714512ea2f44

std.PriorityDequeue: ensureUnusedCapacity and ensureTotalCapacity

Same as c8ae581fef6506a8234cdba1355ba7f0f449031a, but for PriorityDequeue.

1 files changed, 14 insertions(+), 5 deletions(-)

lib/std/priority_dequeue.zig+14-5
......@@ -43,13 +43,13 @@ pub fn PriorityDequeue(comptime T: type) type {
4343
4444 /// Insert a new element, maintaining priority.
4545 pub fn add(self: *Self, elem: T) !void {
46 try ensureCapacity(self, self.len + 1);
46 try self.ensureUnusedCapacity(1);
4747 addUnchecked(self, elem);
4848 }
4949
5050 /// Add each element in `items` to the dequeue.
5151 pub fn addSlice(self: *Self, items: []const T) !void {
52 try self.ensureCapacity(self.len + items.len);
52 try self.ensureUnusedCapacity(items.len);
5353 for (items) |e| {
5454 self.addUnchecked(e);
5555 }
......@@ -359,7 +359,11 @@ pub fn PriorityDequeue(comptime T: type) type {
359359 return queue;
360360 }
361361
362 pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
362 /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
363 pub const ensureCapacity = ensureTotalCapacity;
364
365 /// Ensure that the dequeue can fit at least `new_capacity` items.
366 pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
363367 var better_capacity = self.capacity();
364368 if (better_capacity >= new_capacity) return;
365369 while (true) {
......@@ -369,6 +373,11 @@ pub fn PriorityDequeue(comptime T: type) type {
369373 self.items = try self.allocator.realloc(self.items, better_capacity);
370374 }
371375
376 /// Ensure that the dequeue can fit at least `additional_count` **more** items.
377 pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
378 return self.ensureTotalCapacity(self.len + additional_count);
379 }
380
372381 /// Reduce allocated capacity to `new_len`.
373382 pub fn shrinkAndFree(self: *Self, new_len: usize) void {
374383 assert(new_len <= self.items.len);
......@@ -824,7 +833,7 @@ test "std.PriorityDequeue: shrinkAndFree" {
824833 var queue = PDQ.init(testing.allocator, lessThanComparison);
825834 defer queue.deinit();
826835
827 try queue.ensureCapacity(4);
836 try queue.ensureTotalCapacity(4);
828837 try expect(queue.capacity() >= 4);
829838
830839 try queue.add(1);
......@@ -940,7 +949,7 @@ fn fuzzTestMinMax(rng: *std.rand.Random, queue_size: usize) !void {
940949
941950fn generateRandomSlice(allocator: *std.mem.Allocator, rng: *std.rand.Random, size: usize) ![]u32 {
942951 var array = std.ArrayList(u32).init(allocator);
943 try array.ensureCapacity(size);
952 try array.ensureTotalCapacity(size);
944953
945954 var i: usize = 0;
946955 while (i < size) : (i += 1) {