"""Saving and loading the whole console: board, devices, scheduler queue and CPU. A state is the pickled :class:`gba_python.board.GBA` after a header line, so it holds every pending event exactly (the scheduler's queue is part of the machine). The memoryviews and the I/O table are rebuilt on load (``GBA.__getstate__``). States are for the same gba-python and arm7tdmi-python revisions: the header records both, and a mismatch is refused. data = state.save(gba) gba2 = state.load(data) """ from __future__ import annotations import pickle from importlib.metadata import version from gba_python.board import GBA MAGIC = b"gba-python state 1" def _versions() -> bytes: return f"{version('gba-python')} {version('arm7tdmi-python')}".encode() def save(gba: GBA) -> bytes: return MAGIC + b" " + _versions() + b"\n" + pickle.dumps(gba, protocol=pickle.HIGHEST_PROTOCOL) def load(data: bytes) -> GBA: header, _, body = data.partition(b"\n") if header != MAGIC + b" " + _versions(): raise ValueError(f"not a state of this gba-python/arm7tdmi-python: {header[:80]!r}") gba = pickle.loads(body) if not isinstance(gba, GBA): raise ValueError("the state does not hold a GBA") return gba