Skip to content

Instantly share code, notes, and snippets.

@jailop
Last active March 23, 2025 01:53
Show Gist options
  • Select an option

  • Save jailop/0dc186ee4f870b55f1ced5148d3d4d07 to your computer and use it in GitHub Desktop.

Select an option

Save jailop/0dc186ee4f870b55f1ced5148d3d4d07 to your computer and use it in GitHub Desktop.
Priority Circular Queue
/// A Priority Circular Queue Implementation
///
/// (c) 2025, Jaime Lopez <https://github.com/jailop>
const std = @import("std");
pub const QueueError = error {
Full,
Empty,
};
pub fn PriorityCircularQueue(T: type, example_value: T, size: usize) type {
return struct {
items: [size]T = [_]T{example_value} ** size,
priorities: [size]u8 = [_]u8{0} ** size,
size: usize = size,
len: usize = 0,
head: usize = 0,
// Special condition, to indicate the queue is empty
tail: usize = size,
pub fn enqueue(self: *@This(), item: T, priority: u8) !void {
if (self.tail == self.head) {
return QueueError.Full;
}
if (self.tail == self.size) {
// The queue is empty, so let's
// start filling it
self.tail = self.head;
}
self.items[self.tail] = item;
self.priorities[self.tail] = priority;
var curr = self.head;
var move_to = self.tail;
while (curr != self.tail) {
if (self.priorities[self.tail] > self.priorities[curr]) {
move_to = curr;
break;
}
curr = (curr + 1) % self.size;
}
while (move_to != self.tail) {
std.mem.swap(T, &self.items[self.tail], &self.items[move_to]);
std.mem.swap(u8, &self.priorities[self.tail], &self.priorities[move_to]);
move_to = (move_to + 1) % self.size;
}
self.len += 1;
self.tail = (self.tail + 1) % self.size;
}
pub fn dequeue(self: *@This()) !T {
if (self.tail == self.size) {
return QueueError.Empty;
}
const curr = self.head;
self.head = (self.head + 1) % self.size;
if (self.head == self.tail) {
// Set the queue as empty
self.tail = self.size;
}
self.len -= 1;
return self.items[curr];
}
pub fn peek(self: @This()) !T {
if (self.tail == self.size) {
return QueueError.Empty;
}
return self.items[self.head];
}
};
}
test "Priory Circular Queue" {
const size: u32 = 16;
const TestingQueue = PriorityCircularQueue(u32, 0, size);
var prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.posix.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
var queue = TestingQueue{};
const len: u32 = @intCast(size);
for (0..10) |_| {
for (0..len) |i| {
const priority = rand.int(u8) % 5 + 1;
try queue.enqueue(@intCast(i), priority);
}
try std.testing.expect(queue.enqueue(0, rand.int(u8)) == QueueError.Full);
try std.testing.expect(queue.len == size);
for (0..len) |_| {
_ = try queue.dequeue();
}
try std.testing.expect(queue.dequeue() == QueueError.Empty);
try std.testing.expect(queue.len == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment