//! Inter-process communication: message-passing channels.
//!
//! IPC is the backbone of a microkernel ([vision](../docs/vision.md)): once
//! drivers and services live in separate address spaces, a message is how they
//! talk. This first form is a **bounded blocking channel** — a ring buffer of
//! messages with a producer/consumer rendezvous, built on the scheduler's
//! [wait queues](scheduling.md). `send` blocks when the channel is full, `receive`
//! blocks when it's empty; neither busy-waits.
//!
//! For now both endpoints are kernel threads sharing the kernel address space.
//! When user mode arrives, the same primitive carries messages across the
//! isolation boundary (with the payload copied between address spaces).

const scheduler = @import("scheduler.zig");
const sync = @import("sync.zig");

/// A bounded blocking channel of `capacity` messages of type `T`.
pub fn Channel(comptime T: type, comptime capacity: usize) type {
    return struct {
        const Self = @This();

        buffer: [capacity]T = undefined,
        head: usize = 0, // next slot to read
        tail: usize = 0, // next slot to write
        count: usize = 0,
        not_full: scheduler.WaitQueue = .{}, // senders wait here
        not_empty: scheduler.WaitQueue = .{}, // receivers wait here

        /// Send a message, blocking while the channel is full.
        pub fn send(self: *Self, message: T) void {
            const flags = sync.enter();
            // Recheck the condition in a loop: a wakeup only means "try again"
            // (another waiter may have taken the slot first).
            while (self.count == capacity) scheduler.waitLocked(&self.not_full);
            self.buffer[self.tail] = message;
            self.tail = (self.tail + 1) % capacity;
            self.count += 1;
            scheduler.wakeLocked(&self.not_empty); // a receiver can now proceed
            sync.leave(flags);
        }

        /// Receive a message, blocking while the channel is empty.
        pub fn receive(self: *Self) T {
            const flags = sync.enter();
            while (self.count == 0) scheduler.waitLocked(&self.not_empty);
            const message = self.buffer[self.head];
            self.head = (self.head + 1) % capacity;
            self.count -= 1;
            scheduler.wakeLocked(&self.not_full); // a sender can now proceed
            sync.leave(flags);
            return message;
        }
    };
}
