const std = @import("std"); const Io = std.Io; pub const Shedding = enum { /// Keep queued work, reject the submitted item. drop_newest, /// Evict the oldest queued item, then accept the submitted item. drop_oldest, }; pub const PushStatus = enum { accepted, dropped_newest, dropped_oldest, }; pub fn PushResult(comptime Item: type) type { return struct { status: PushStatus, dropped: ?Item = null, pub fn accepted(self: @This()) bool { return self.status != .dropped_newest; } }; } pub fn BoundedQueue(comptime Item: type) type { return struct { const Self = @This(); buffer: []Item, head: usize = 0, len: usize = 0, closed: bool = false, aborted: bool = false, mutex: Io.Mutex = .init, not_empty: Io.Condition = .init, not_full: Io.Condition = .init, pub fn init(buffer: []Item) Self { std.debug.assert(buffer.len > 0); return .{ .buffer = buffer }; } pub fn close(self: *Self, io: Io) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); self.closed = true; self.not_empty.broadcast(io); self.not_full.broadcast(io); } pub fn abort(self: *Self, io: Io) void { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); self.closed = true; self.aborted = true; self.not_empty.broadcast(io); self.not_full.broadcast(io); } pub fn put(self: *Self, io: Io, item: Item) (error{Closed} || Io.Cancelable)!void { try io.checkCancel(); try self.mutex.lock(io); defer self.mutex.unlock(io); if (self.closed) return error.Closed; while (self.len == self.buffer.len and !self.closed) { try self.not_full.wait(io, &self.mutex); } if (self.closed) return error.Closed; self.pushLocked(item); self.not_empty.signal(io); } pub fn offer(self: *Self, io: Io, item: Item, shedding: Shedding) error{Closed}!PushResult(Item) { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); if (self.closed) return error.Closed; if (self.len == self.buffer.len) { switch (shedding) { .drop_newest => return .{ .status = .dropped_newest, .dropped = item }, .drop_oldest => { const dropped = self.popLocked(); self.pushLocked(item); self.not_empty.signal(io); return .{ .status = .dropped_oldest, .dropped = dropped }; }, } } self.pushLocked(item); self.not_empty.signal(io); return .{ .status = .accepted }; } pub fn pop(self: *Self, io: Io) (error{Closed} || Io.Cancelable)!Item { try io.checkCancel(); try self.mutex.lock(io); defer self.mutex.unlock(io); while (self.len == 0 and !self.closed) { try self.not_empty.wait(io, &self.mutex); } if (self.aborted or self.len == 0) return error.Closed; const item = self.popLocked(); self.not_full.signal(io); return item; } pub fn take(self: *Self, io: Io) ?Item { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); if (self.len == 0) return null; const item = self.popLocked(); self.not_full.signal(io); return item; } pub fn count(self: *Self, io: Io) usize { self.mutex.lockUncancelable(io); defer self.mutex.unlock(io); return self.len; } pub fn capacity(self: *const Self) usize { return self.buffer.len; } fn pushLocked(self: *Self, item: Item) void { const idx = (self.head + self.len) % self.buffer.len; self.buffer[idx] = item; self.len += 1; } fn popLocked(self: *Self) Item { std.debug.assert(self.len > 0); const item = self.buffer[self.head]; self.head = (self.head + 1) % self.buffer.len; self.len -= 1; return item; } }; } test "drop_newest rejects full queue" { const testing = std.testing; const io = testing.io; var buffer: [2]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); try testing.expect((try q.offer(io, 1, .drop_newest)).accepted()); try testing.expect((try q.offer(io, 2, .drop_newest)).accepted()); const r = try q.offer(io, 3, .drop_newest); try testing.expectEqual(PushStatus.dropped_newest, r.status); try testing.expectEqual(@as(?u32, 3), r.dropped); try testing.expectEqual(@as(u32, 1), try q.pop(io)); try testing.expectEqual(@as(u32, 2), try q.pop(io)); } test "drop_oldest evicts full queue head" { const testing = std.testing; const io = testing.io; var buffer: [2]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); _ = try q.offer(io, 1, .drop_oldest); _ = try q.offer(io, 2, .drop_oldest); const r = try q.offer(io, 3, .drop_oldest); try testing.expectEqual(PushStatus.dropped_oldest, r.status); try testing.expectEqual(@as(?u32, 1), r.dropped); try testing.expectEqual(@as(u32, 2), try q.pop(io)); try testing.expectEqual(@as(u32, 3), try q.pop(io)); } test "put preserves order" { const testing = std.testing; const io = testing.io; var buffer: [2]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); try q.put(io, 1); try q.put(io, 2); try testing.expectEqual(@as(u32, 1), try q.pop(io)); try testing.expectEqual(@as(u32, 2), try q.pop(io)); } test "blocked put observes cancellation" { const testing = std.testing; const io = testing.io; var buffer: [1]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); try q.put(io, 1); const Helper = struct { fn putFull(queue: *BoundedQueue(u32), task_io: Io) (error{Closed} || Io.Cancelable)!void { try queue.put(task_io, 2); } }; var future = try io.concurrent(Helper.putFull, .{ &q, io }); try testing.expectError(error.Canceled, future.cancel(io)); try testing.expectEqual(@as(u32, 1), try q.pop(io)); } test "blocked pop observes cancellation" { const testing = std.testing; const io = testing.io; var buffer: [1]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); const Helper = struct { fn popEmpty(queue: *BoundedQueue(u32), task_io: Io) (error{Closed} || Io.Cancelable)!u32 { return try queue.pop(task_io); } }; var future = try io.concurrent(Helper.popEmpty, .{ &q, io }); try testing.expectError(error.Canceled, future.cancel(io)); } test "close wakes producers and drains consumers while abort preserves queued items" { const io = std.testing.io; var buffer: [1]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); try q.put(io, 1); const Helper = struct { fn put(queue: *BoundedQueue(u32), task_io: Io) (error{Closed} || Io.Cancelable)!void { try queue.put(task_io, 2); } }; var producer = try io.concurrent(Helper.put, .{ &q, io }); defer producer.cancel(io) catch {}; q.close(io); try std.testing.expectError(error.Closed, producer.await(io)); try std.testing.expectEqual(@as(u32, 1), try q.pop(io)); try std.testing.expectError(error.Closed, q.pop(io)); q = BoundedQueue(u32).init(&buffer); try q.put(io, 3); q.abort(io); try std.testing.expectError(error.Closed, q.pop(io)); try std.testing.expectEqual(@as(?u32, 3), q.take(io)); try std.testing.expectEqual(@as(?u32, null), q.take(io)); } test "pending cancellation interrupts ready queue operations without transferring ownership" { const io = std.testing.io; const Helper = struct { fn run(queue: *BoundedQueue(u32), task_io: Io, ready: *Io.Event) !void { var never: Io.Event = .unset; ready.set(task_io); never.wait(task_io) catch { task_io.recancel(); try std.testing.expectError(error.Canceled, queue.put(task_io, 2)); task_io.recancel(); try std.testing.expectError(error.Canceled, queue.pop(task_io)); return; }; unreachable; } }; var buffer: [2]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); try q.put(io, 1); var ready: Io.Event = .unset; var future = try io.concurrent(Helper.run, .{ &q, io, &ready }); defer _ = future.cancel(io) catch {}; try ready.wait(io); try future.cancel(io); try std.testing.expectEqual(@as(usize, 1), q.count(io)); try std.testing.expectEqual(@as(u32, 1), try q.pop(io)); } test "ring wraps arbitrary capacities and shedding preserves fifo" { const io = std.testing.io; inline for (.{ 1, 3, 7, 16 }) |capacity_value| { var buffer: [capacity_value]u32 = undefined; var q = BoundedQueue(u32).init(&buffer); for (0..capacity_value * 10) |i| { _ = try q.offer(io, @intCast(i), .drop_oldest); } for (capacity_value * 9..capacity_value * 10) |i| { try std.testing.expectEqual(@as(u32, @intCast(i)), try q.pop(io)); } try std.testing.expectEqual(@as(usize, 0), q.count(io)); } }