std: Fix update() method in PriorityQueue and PriorityDequeue (#13908)
Previously the update() method would iterate over its capacity, which may contain uninitialized memory or already removed elements.
This commit is contained in:
@@ -218,8 +218,10 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF
|
||||
|
||||
pub fn update(self: *Self, elem: T, new_elem: T) !void {
|
||||
const update_index = blk: {
|
||||
for (self.items) |item, idx| {
|
||||
if (compareFn(self.context, item, elem).compare(.eq)) break :blk idx;
|
||||
var idx: usize = 0;
|
||||
while (idx < self.len) : (idx += 1) {
|
||||
const item = self.items[idx];
|
||||
if (compareFn(self.context, item, elem) == .eq) break :blk idx;
|
||||
}
|
||||
return error.ElementNotFound;
|
||||
};
|
||||
@@ -591,6 +593,15 @@ test "std.PriorityQueue: update same max heap" {
|
||||
try expectEqual(@as(u32, 1), queue.remove());
|
||||
}
|
||||
|
||||
test "std.PriorityQueue: update after remove" {
|
||||
var queue = PQlt.init(testing.allocator, {});
|
||||
defer queue.deinit();
|
||||
|
||||
try queue.add(1);
|
||||
try expectEqual(@as(u32, 1), queue.remove());
|
||||
try expectError(error.ElementNotFound, queue.update(1, 1));
|
||||
}
|
||||
|
||||
test "std.PriorityQueue: siftUp in remove" {
|
||||
var queue = PQlt.init(testing.allocator, {});
|
||||
defer queue.deinit();
|
||||
|
||||
Reference in New Issue
Block a user