Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A whole machine written down and read back — the save state.//!//! A snapshot is the machine's live state at a moment: its memory, its//! processor, every soft switch, every chip register, and the disks in its//! drives. Take one before a hard bit of a game and go back to it, or hand one//! to somebody else and have them come up exactly where you left off.//!//! The trick is that a machine is not flat data. It is full of *pointers* —//! a Mega II points back at the IIgs it is part of, a card points at its//! firmware ROM, a drive points at the disk in it — and a pointer is an address//! in this run of this program and means nothing in the next. So a snapshot is//! never restored into an empty machine. The front end builds the machine the//! ordinary way first — same ROM, same cards, same everything — and then this//! reads the saved state *into* that machine, overwriting the data and leaving//! every pointer as the live one it already is. The ROM stays the ROM, the//! Mega II keeps pointing at its IIgs, and a card keeps its firmware; only what//! the machine *did* is replaced.//!//! The disks are the exception, because their contents are behind a pointer and//! are wanted anyway: a snapshot holds every drive's surface so it survives the//! disk being written to or swapped out. A type that owns something behind a//! pointer — a disk controller, a block device — takes over its own snapshot by//! declaring `snapshotWrite` and `snapshotRead`, and this walks everything//! else by reflection: integers and enums and booleans as themselves, arrays//! and structs and tagged unions by their parts, a mutable slice — a machine's//! RAM, a card's memory — as its contents, and a single pointer or a `[]const`//! view skipped so the live one survives.
const std = @import("std");
/// The eight bytes at the front, so a file that is not a snapshot is refused/// before anything is read out of it.pub const magic = "ZG65SNAP".*;
/// The format version. A snapshot of a different one is refused rather than/// misread, since the layout is the machine's fields and those move.pub const version: u16 = 1;
pub const Error = error{ /// Not a snapshot, or one this cannot read. NotASnapshot, /// A snapshot of a differently-built machine: a different model, a /// different amount of memory, a different card in a slot. Its fields do /// not line up with this machine's, so it is refused rather than loaded /// into the wrong shape. WrongMachine, /// The file ended in the middle of the state. Truncated,};
/// Whether a field is one to leave alone rather than carry in a snapshot.////// A **mutable slice** is owned state — a machine's RAM, a card's memory — and/// is carried. Everything else that points is borrowed: a single pointer at/// firmware or at the machine a part belongs to, a `[]const` view of somebody/// else's bytes. Those are left as the live machine has them, since their/// address means nothing in another run and the live one is already right. A/// stored error is skipped for the same reason — it is a note about the host's/// last I/O, not machine state.fn skip(comptime T: type) bool { return switch (@typeInfo(T)) { .pointer => |p| p.size != .slice or p.is_const, .error_set, .error_union, .@"fn", .@"opaque" => true, else => false, };}
/// Whether a struct has told this to leave one of its fields out of a snapshot,/// by name in a `snapshot_skip_fields` declaration. That is for a field that is/// not machine state and is not kept defined — a debug ring buffer left/// `undefined` until something is logged into it, which cannot be written down/// without reading uninitialised memory.fn skipField(comptime T: type, comptime name: []const u8) bool { if (!@hasDecl(T, "snapshot_skip_fields")) return false; for (T.snapshot_skip_fields) |skipped| { if (std.mem.eql(u8, skipped, name)) return true; } return false;}
/// Collects the bytes of a snapshot. A growing buffer rather than a stream,/// because a snapshot is made in one go and handed back whole.pub const Writer = struct { list: std.ArrayList(u8) = .empty, gpa: std.mem.Allocator,
pub fn deinit(self: *Writer) void { self.list.deinit(self.gpa); }
pub fn raw(self: *Writer, bytes: []const u8) std.mem.Allocator.Error!void { try self.list.appendSlice(self.gpa, bytes); }
pub fn int(self: *Writer, comptime T: type, n: T) std.mem.Allocator.Error!void { // Rounded up to whole bytes, since a `u2` or a `u12` has no byte width // of its own: it goes out in the bytes its size takes. const Aligned = std.meta.Int(@typeInfo(T).int.signedness, @sizeOf(T) * 8); var bytes: [@sizeOf(T)]u8 = undefined; std.mem.writeInt(Aligned, &bytes, n, .little); try self.raw(&bytes); }
/// Writes any value, walking its type. Types that own something behind a /// pointer take over by declaring `snapshotWrite`. pub fn value(self: *Writer, comptime T: type, ptr: *const T) std.mem.Allocator.Error!void { switch (@typeInfo(T)) { .int => try self.int(T, ptr.*), .float => |f| try self.int(std.meta.Int(.unsigned, f.bits), @bitCast(ptr.*)), .bool => try self.int(u8, @intFromBool(ptr.*)), .@"enum" => |e| try self.int(e.tag_type, @intFromEnum(ptr.*)), .void => {}, .array => |a| { if (a.child == u8) { try self.raw(ptr); } else for (ptr) |*element| try self.value(a.child, element); }, .vector => |v| { const array: [v.len]v.child = ptr.*; try self.value([v.len]v.child, &array); }, .optional => |o| { if (comptime skip(o.child)) return; // a borrowed pointer, left live if (ptr.*) |*present| { try self.int(u8, 1); try self.value(o.child, present); } else try self.int(u8, 0); }, .pointer => |p| { if (comptime skip(T)) return; // borrowed, left live // A mutable slice, which is owned memory: its length and then // its contents. const slice = ptr.*; try self.int(u64, slice.len); if (p.child == u8) { try self.raw(slice); } else for (slice) |*element| try self.value(p.child, element); }, .error_set, .error_union => {}, // left as the live machine has it .@"struct" => |s| { // A packed struct is its backing integer, bits and all; walking // its fields would take the address of a bit, which is not an // ordinary pointer. if (comptime s.layout == .@"packed") { const Backing = s.backing_integer.?; return self.int(Backing, @bitCast(ptr.*)); } if (comptime @hasDecl(T, "snapshotWrite")) return ptr.snapshotWrite(self); inline for (s.fields) |field| { if (comptime !skip(field.type) and !skipField(T, field.name) and @sizeOf(field.type) != 0) try self.value(field.type, &@field(ptr.*, field.name)); } }, .@"union" => |u| { const Tag = u.tag_type orelse @compileError("cannot snapshot an untagged union: " ++ @typeName(T)); try self.int(@typeInfo(Tag).@"enum".tag_type, @intFromEnum(std.meta.activeTag(ptr.*))); switch (ptr.*) { inline else => |*active| try self.value(@TypeOf(active.*), active), } }, else => @compileError("cannot snapshot a " ++ @typeName(T)), } }};
/// Reads the bytes of a snapshot back. A cursor over the whole thing rather/// than a stream, for the same reason the writer is a buffer.pub const Reader = struct { data: []const u8, pos: usize = 0, gpa: std.mem.Allocator,
pub fn raw(self: *Reader, into: []u8) Error!void { if (self.pos + into.len > self.data.len) return error.Truncated; @memcpy(into, self.data[self.pos..][0..into.len]); self.pos += into.len; }
pub fn int(self: *Reader, comptime T: type) Error!T { const Aligned = std.meta.Int(@typeInfo(T).int.signedness, @sizeOf(T) * 8); var bytes: [@sizeOf(T)]u8 = undefined; try self.raw(&bytes); return @intCast(std.mem.readInt(Aligned, &bytes, .little)); }
/// Reads a value in place, walking its type the way the writer wrote it. /// Pointers are left as they are — the live machine's — and a value read /// into an existing one keeps whatever the walk does not touch. pub fn value(self: *Reader, comptime T: type, ptr: *T) Error!void { switch (@typeInfo(T)) { .int => ptr.* = try self.int(T), .float => |f| ptr.* = @bitCast(try self.int(std.meta.Int(.unsigned, f.bits))), .bool => ptr.* = try self.int(u8) != 0, .@"enum" => |e| ptr.* = @enumFromInt(try self.int(e.tag_type)), .void => {}, .array => |a| { if (a.child == u8) { try self.raw(ptr); } else for (ptr) |*element| try self.value(a.child, element); }, .vector => |v| { var array: [v.len]v.child = undefined; try self.value([v.len]v.child, &array); ptr.* = array; }, .optional => |o| { if (comptime skip(o.child)) return; // left live if (try self.int(u8) != 0) { var child: o.child = if (ptr.*) |existing| existing else undefined; try self.value(o.child, &child); ptr.* = child; } else ptr.* = null; }, .pointer => |p| { if (comptime skip(T)) return; // left live // A mutable slice: read its length, and require it to match the // buffer the live machine already has — a machine built with a // different amount of memory is a different machine — then read // straight into that buffer rather than allocating a new one. const len = try self.int(u64); const slice = ptr.*; if (len != slice.len) return error.WrongMachine; if (p.child == u8) { try self.raw(slice); } else for (slice) |*element| try self.value(p.child, element); }, .error_set, .error_union => {}, // left live .@"struct" => |s| { if (comptime s.layout == .@"packed") { const Backing = s.backing_integer.?; ptr.* = @bitCast(try self.int(Backing)); return; } if (comptime @hasDecl(T, "snapshotRead")) return ptr.snapshotRead(self); inline for (s.fields) |field| { if (comptime !skip(field.type) and !skipField(T, field.name) and @sizeOf(field.type) != 0) try self.value(field.type, &@field(ptr.*, field.name)); } }, .@"union" => |u| { const Tag = u.tag_type.?; const tag: Tag = @enumFromInt(try self.int(@typeInfo(Tag).@"enum".tag_type)); // The machine was built the same way, so the variant already // matches; if it does not, this is a snapshot of a different // machine and its bytes would land in the wrong field. if (tag != std.meta.activeTag(ptr.*)) return error.WrongMachine; switch (ptr.*) { inline else => |*active| try self.value(@TypeOf(active.*), active), } }, else => @compileError("cannot snapshot a " ++ @typeName(T)), } }};
/// An identity for the machine's shape, so a snapshot cannot be loaded into a/// machine of a different type. It is the type name hashed, which changes with/// the model, the processor and every comptime option baked into it.fn identity(comptime Machine: type) u64 { return std.hash.Wyhash.hash(0, @typeName(Machine));}
/// Writes a whole machine to a fresh buffer the caller owns: the header, then/// the state./// Writes the header — the magic, the version, and the machine's identity — so/// a front end that wants a section of its own after the machine (a session's/// disks, say) can compose one snapshot rather than two. `save` is this plus/// the machine and nothing after.pub fn writeHeader(writer: *Writer, comptime Machine: type) std.mem.Allocator.Error!void { try writer.raw(&magic); try writer.int(u16, version); try writer.int(u64, identity(Machine));}
/// Reads and checks the header, so the matching front end can go on to read its/// own section. Refuses a file that is not a snapshot, or is of another version/// or another machine, before any state is read.pub fn readHeader(reader: *Reader, comptime Machine: type) Error!void { var head: [magic.len]u8 = undefined; reader.raw(&head) catch return error.NotASnapshot; if (!std.mem.eql(u8, &head, &magic)) return error.NotASnapshot; if (reader.int(u16) catch 0 != version) return error.NotASnapshot; if (reader.int(u64) catch 0 != identity(Machine)) return error.WrongMachine;}
pub fn save(gpa: std.mem.Allocator, machine: anytype) std.mem.Allocator.Error![]u8 { const Machine = @TypeOf(machine.*); var writer: Writer = .{ .gpa = gpa }; errdefer writer.deinit(); try writeHeader(&writer, Machine); try writer.value(Machine, machine); return writer.list.toOwnedSlice(gpa);}
/// Reads a snapshot into `machine`, which must already be the machine it was a/// snapshot of, built the ordinary way. Refuses one whose header does not/// match rather than loading it wrong.pub fn load(gpa: std.mem.Allocator, data: []const u8, machine: anytype) Error!void { const Machine = @TypeOf(machine.*); var reader: Reader = .{ .data = data, .gpa = gpa }; try readHeader(&reader, Machine); try reader.value(Machine, machine);}
const testing = std.testing;
test "the plain values round-trip as themselves" { const Colours = enum(u8) { red, green, blue }; const Thing = struct { a: u32 = 0, b: i16 = 0, c: bool = false, d: Colours = .red, e: [4]u8 = @splat(0), f: f32 = 0, g: ?u16 = null, h: [2]u16 = .{ 0, 0 }, }; const alloc = testing.allocator;
var out: Thing = .{ .a = 0xdeadbeef, .b = -3, .c = true, .d = .blue, .e = "abcd".*, .f = 1.5, .g = 0x1234, .h = .{ 7, 9 } }; const bytes = try save(alloc, &out); defer alloc.free(bytes);
var in: Thing = .{}; try load(alloc, bytes, &in); try testing.expectEqual(out, in);}
test "a borrowed pointer is skipped and the live one survives" { const rom = [_]u8{ 1, 2, 3 }; const Card = struct { firmware: *const [3]u8, count: u16 = 0 }; const alloc = testing.allocator;
var live_rom = rom; var out: Card = .{ .firmware = &live_rom, .count = 42 }; const bytes = try save(alloc, &out); defer alloc.free(bytes);
// The snapshot carries `count` and nothing for the pointer. var other_rom = [_]u8{ 9, 9, 9 }; var in: Card = .{ .firmware = &other_rom, .count = 0 }; try load(alloc, bytes, &in); try testing.expectEqual(@as(u16, 42), in.count); // Its pointer is left exactly as the live machine's was. try testing.expectEqual(&other_rom, in.firmware);}
test "a tagged union round-trips its active variant, and a mismatch is refused" { const U = union(enum) { none, number: u32, flag: bool }; const alloc = testing.allocator;
var out: U = .{ .number = 1000 }; const bytes = try save(alloc, &out); defer alloc.free(bytes);
// Read into a value already on the same variant. var in: U = .{ .number = 0 }; try load(alloc, bytes, &in); try testing.expectEqual(@as(u32, 1000), in.number);
// A value on a different variant is a differently-built machine. var wrong: U = .{ .flag = false }; try testing.expectError(error.WrongMachine, load(alloc, bytes, &wrong));}
test "a header that is not this snapshot is refused" { const alloc = testing.allocator; var target: u32 = 0; try testing.expectError(error.NotASnapshot, load(alloc, "not a snapshot at all", &target)); var short: [4]u8 = "ZG65".*; try testing.expectError(error.NotASnapshot, load(alloc, &short, &target));}
test "a mutable slice is carried; a const view is left live" { const alloc = testing.allocator; const Machine = struct { ram: []u8, name: []const u8, count: u16 = 0 };
var live = [_]u8{ 1, 2, 3, 4 }; var out: Machine = .{ .ram = &live, .name = "saved", .count = 5 }; const bytes = try save(alloc, &out); defer alloc.free(bytes);
// Restore onto a machine whose RAM is its own buffer of the same size and // whose name is a different borrowed string. var other = [_]u8{ 0, 0, 0, 0 }; var in: Machine = .{ .ram = &other, .name = "live" }; try load(alloc, bytes, &in); // The RAM's contents came across, into the live buffer. try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, &other); try testing.expectEqual(@as(u16, 5), in.count); // The borrowed name was left as the live machine's. try testing.expectEqualStrings("live", in.name);
// A machine with a different amount of memory is a different machine. var bigger = [_]u8{ 0, 0, 0, 0, 0 }; var wrong: Machine = .{ .ram = &bigger, .name = "x" }; try testing.expectError(error.WrongMachine, load(alloc, bytes, &wrong));}
test "a type may take over its own snapshot" { // A stand-in for a disk controller: it owns something behind a pointer and // wants it in the snapshot, so it writes itself. const Owner = struct { held: *[3]u8, pub fn snapshotWrite(self: *const @This(), w: *Writer) !void { try w.raw(self.held); } pub fn snapshotRead(self: *@This(), r: *Reader) Error!void { try r.raw(self.held); } }; const alloc = testing.allocator;
var surface = [_]u8{ 10, 20, 30 }; var out: Owner = .{ .held = &surface }; const bytes = try save(alloc, &out); defer alloc.free(bytes);
var restored = [_]u8{ 0, 0, 0 }; var in: Owner = .{ .held = &restored }; try load(alloc, bytes, &in); try testing.expectEqualSlices(u8, &.{ 10, 20, 30 }, &restored);}