"""The event queue every device schedules on, stamped in system-clock cycles. The board never ticks a device every cycle (user decision 3). Each device either computes its state from the time when asked (the timers' counters) or puts an event on this queue for the cycle something happens (a line starting, a timer overflowing, an IRQ line moving). The bus advances the clock inside each callback with :meth:`Scheduler.advance`, which fires, in order, every event due up to the new time, with :attr:`now` set to the event's own cycle while it runs. Ordering follows NanoBoyAdvance's queue (``include/nba/scheduler.hpp``): earlier cycle first, then lower priority number (0-3); events equal in both fire in the order they were added. """ from __future__ import annotations import heapq from collections.abc import Callable #: an event's handler: called with the event's argument Handler = Callable[[int], None] NEVER = 1 << 62 class Event: """One scheduled call. ``cancelled`` events stay in the heap and are skipped.""" __slots__ = ("arg", "cancelled", "handler", "key", "time") def __init__(self, time: int, key: tuple[int, int, int], handler: Handler, arg: int) -> None: self.time = time self.key = key self.handler = handler self.arg = arg self.cancelled = False def __lt__(self, other: Event) -> bool: return self.key < other.key class Scheduler: def __init__(self) -> None: self.now = 0 #: the cycle of the earliest pending event (NEVER when none): the bus compares against #: it on every callback, so advancing time costs one comparison when nothing is due self.next_time = NEVER self._heap: list[Event] = [] self._sequence = 0 def add(self, delay: int, handler: Handler, arg: int = 0, priority: int = 0) -> Event: """Run ``handler(arg)`` ``delay`` cycles from now.""" time = self.now + delay self._sequence += 1 event = Event(time, (time, priority, self._sequence), handler, arg) heapq.heappush(self._heap, event) if time < self.next_time: self.next_time = time return event def cancel(self, event: Event | None) -> None: if event is not None: event.cancelled = True def advance(self, cycles: int) -> None: """Move the clock forward ``cycles``, firing every event due on the way.""" target = self.now + cycles if target >= self.next_time: self.run_until(target) self.now = target def run_until(self, target: int) -> None: heap = self._heap while heap and heap[0].time <= target: event = heapq.heappop(heap) if event.cancelled: continue self.now = event.time event.handler(event.arg) self.now = target while heap and heap[0].cancelled: heapq.heappop(heap) self.next_time = heap[0].time if heap else NEVER def cycles_to_next(self) -> int: """Cycles until the next event (for a halted CPU, which skips straight to it).""" return self.next_time - self.now