# SPDX-License-Identifier: MIT """The catch-up scheduler: one clock, and the events devices ask for. Owner's decision (docs/handoff-brief.md): a catch-up scheduler. The board keeps one cycle counter (``Bus.now``); a device that must act at a known future cycle (a timer's overflow, a line's H-blank, a serial transfer's end, the sound sequencer's step) schedules an event, and devices whose state can be computed from the time (a running timer's counter) are brought up to the time when they are read or written. Events due at the same cycle run in the order of their ``order`` key, then in the order they were scheduled: the order of record within one cycle (docs/timing.md "The order of record"): ORDER_TIMER < ORDER_IRQ < ORDER_PPU < ORDER_SERIAL < ORDER_SOUND < ORDER_LATE (HYPOTHESIS: no permitted document orders simultaneous events; a test that depends on it is named beside the rule that fixes it.) """ from __future__ import annotations import heapq ORDER_TIMER, ORDER_IRQ, ORDER_PPU, ORDER_SERIAL, ORDER_SOUND, ORDER_LATE = 0, 1, 2, 3, 4, 5 NEVER = 1 << 62 class Event: """A scheduled call ``callback(time)``; ``cancel()`` keeps it from running.""" __slots__ = ("alive", "callback", "time") def __init__(self, time: int, callback) -> None: self.time = time self.callback = callback self.alive = True def cancel(self) -> None: self.alive = False class Scheduler: def __init__(self, bus) -> None: self.bus = bus self.heap: list = [] self.serial = 0 def schedule(self, time: int, order: int, callback) -> Event: event = Event(time, callback) self.serial += 1 heapq.heappush(self.heap, (time, order, self.serial, event)) self.bus.next_event = min(self.bus.next_event, time) return event def run_due(self) -> None: """Run every live event due at or before ``bus.now``, in time order.""" heap = self.heap bus = self.bus while heap and heap[0][0] <= bus.now: _, _, _, event = heapq.heappop(heap) if event.alive: event.alive = False event.callback(event.time) while heap and not heap[0][3].alive: heapq.heappop(heap) bus.next_event = heap[0][0] if heap else NEVER def next_time(self) -> int: heap = self.heap while heap and not heap[0][3].alive: heapq.heappop(heap) return heap[0][0] if heap else NEVER