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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! Putting a disk back in the file it came out of.//!//! Free functions rather than methods on a session, so that they can be tested//! without a whole machine around them and so that both front ends can reach//! them: what they need is somewhere to read and write, a path, and the drive//! being saved.//!//! What is written out is always the *whole file*, re-read and re-opened//! first, so that the disk goes back inside whatever wrapper it came in — a//! 2IMG keeps its header, the disk being a slice of the file rather than the//! file itself.
const std = @import("std");
const disk2 = @import("disk2.zig");const disk35 = @import("disk35.zig");const diskfile = @import("diskfile.zig");const twomg = @import("twomg.zig");const woz = @import("woz.zig");const shrinkit = @import("shrinkit");
/// How big a disk file is allowed to be. The largest thing any of these/// drives reads, plus room for a wrapper.pub const file_limit = @max( disk2.image_size, disk2.Floppy.nibble_size, woz.max_file_size,) + twomg.header_size + 1;
pub const Error = error{ CannotReRead, NotTheSameDisk, CannotWrite };
/// Reads the file back, lets `fill` put the disk into it, and moves the/// result into place.////// Read again rather than remembered so that the disk goes back inside/// whatever wrapper it came in: what is written out is the whole file, and/// the disk is a slice of it, so a 2IMG keeps its header.fn replace( io: std.Io, alloc: std.mem.Allocator, path: []const u8, context: anytype, comptime fill: fn (@TypeOf(context), twomg.Image) bool,) Error!void { const file = std.Io.Dir.cwd().readFileAlloc(io, path, alloc, .limited(file_limit)) catch return error.CannotReRead; defer alloc.free(file); const opened = diskfile.open(alloc, file, path) catch return error.CannotReRead; defer opened.deinit(alloc); if (!fill(context, opened.image)) return error.NotTheSameDisk;
// A disk that came out of an archive is not a slice of the file: it was // unpacked into its own buffer, so writing `file` back would write the // archive unchanged. It has to go home the way it came, re-archived. A // failure there -- an archive holding more than the one disk -- is a // refusal, the same as a disk that did not match. if (opened.owned) |disk| { const archived = reArchive(alloc, file, disk) catch return error.NotTheSameDisk; defer alloc.free(archived); return moveIntoPlace(io, alloc, path, archived); }
// Otherwise written beside the disk and moved into place, rather than over // the top of it. Overwriting means a moment where the file is neither the // old disk nor the new one, and the one thing worse than losing what // the machine wrote is losing what was there before it started. return moveIntoPlace(io, alloc, path, file);}
/// Rebuilds a single-record archive around a disk written back to it, taking/// the disk's name and block size from the archive it came out of. The/// `zig-shrinkit` writer squeezes it the way ShrinkIt did -- LZW/2 by default/// -- so the file that goes home is about the size of the one that came in,/// not the larger stored copy this used to write.////// Only an archive of a single record is rewritten; one holding more than the/// disk is refused rather than rebuilt with the rest of it thrown away.fn reArchive(alloc: std.mem.Allocator, original: []const u8, disk: []const u8) ![]u8 { const archive = try shrinkit.nufx.open(original); if (archive.records != 1) return error.Unwritable; const record, _ = try shrinkit.nufx.findDisk(archive); return shrinkit.writer.diskAlloc(alloc, .{ .name = record.filename(original), .data = disk, .block_size = if (record.storage_type == 0) 512 else record.storage_type, }, .{});}
/// Writes `contents` beside `path` and moves it over the top.pub fn moveIntoPlace(io: std.Io, alloc: std.mem.Allocator, path: []const u8, contents: []const u8) Error!void { const temporary = std.fmt.allocPrint(alloc, "{s}.tmp", .{path}) catch return error.CannotWrite; defer alloc.free(temporary); const cwd = std.Io.Dir.cwd(); cwd.writeFile(io, .{ .sub_path = temporary, .data = contents }) catch return error.CannotWrite; cwd.rename(temporary, cwd, path, io) catch { cwd.deleteFile(io, temporary) catch {}; return error.CannotWrite; };}
/// A drive that keeps a recorded surface: the 3.5-inch one in a case.pub fn floppy35(io: std.Io, alloc: std.mem.Allocator, path: []const u8, from: *const disk35.Floppy) Error!void { return replace(io, alloc, path, from, struct { fn fill(disk: *const disk35.Floppy, image: twomg.Image) bool { disk.save(image.data) catch return false; return true; } }.fill);}
/// And one that keeps plain blocks: the intelligent drive on a IIc's port,/// which is asked for numbered blocks and has no notion of a track.pub fn blocks(io: std.Io, alloc: std.mem.Allocator, path: []const u8, from: []const u8) Error!void { return replace(io, alloc, path, from, struct { fn fill(disk: []const u8, image: twomg.Image) bool { if (disk.len > image.data.len) return false; @memcpy(image.data[0..disk.len], disk); return true; } }.fill);}
/// A five-and-a-quarter drive, which is the one with two shapes of file/// behind it.////// A `.nib` is a recording of what the head saw and is the only sector-free/// file that can hold a track the machine laid out itself, so it goes back/// nibble for nibble; a sectored file goes back as sectors. A `.woz` is/// neither: its tracks go back bit for bit into the slots they came from — see/// `fillWoz` — with two things it will not do, a track the file did not already/// record and a track kept as flux rather than as bits.pub fn floppy(io: std.Io, alloc: std.mem.Allocator, path: []const u8, from: *const disk2.Floppy) Error!void { return replace(io, alloc, path, from, struct { fn fill(disk: *const disk2.Floppy, image: twomg.Image) bool { if (image.isWoz()) return fillWoz(disk, image.data); if (image.isNibble()) { if (image.data.len != disk2.Floppy.nibble_size) return false; disk.saveNibbles(image.data) catch return false; } else { if (image.data.len != disk2.image_size) return false; disk.save(image.data) catch return false; } return true; }
/// Puts the drive's tracks back into the WOZ they came from, in place. /// /// A drive write never changes a track's length, so each track goes /// straight back into the same slot; the file's INFO, TMAP and any /// other chunks are left as they were, and the header CRC is redone /// over the result. A file with any flux-recorded track is refused /// whole: a drive reads flux as bits and nothing here turns bits back /// into flux, so a flux track cannot be trusted to have gone untouched. fn fillWoz(disk: *const disk2.Floppy, bytes: []u8) bool { const opened = woz.open(bytes) catch return false; if (opened.hasFlux()) return false; for (0..woz.positions) |position| { const bits = disk.bitsAt(@intCast(position)) orelse continue; opened.patch(bytes, @intCast(position), bits) catch return false; } woz.reChecksum(bytes); return true; } }.fill);}
const testing = std.testing;
/// A disk written back has to land in the file it came out of, and that is not/// something the drive models can be asked about: they know only their own/// blocks. So these go through the free functions above, on a file made for/// the purpose.fn scratchDisk(alloc: std.mem.Allocator, name: []const u8, size: usize) ![]u8 { const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; const path = try std.fmt.allocPrint(alloc, "{s}/zig65-{s}", .{ dir, name }); errdefer alloc.free(path); const blank = try alloc.alloc(u8, size); defer alloc.free(blank); @memset(blank, 0); try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = blank }); return path;}
test "a disk of blocks is written back into the file it came out of" { const alloc = testing.allocator; const path = try scratchDisk(alloc, "writeback-blocks.po", disk35.image_size); defer { std.Io.Dir.cwd().deleteFile(testing.io, path) catch {}; alloc.free(path); }
// What the machine wrote, in the drive rather than in the file. const written = try alloc.alloc(u8, disk35.image_size); defer alloc.free(written); @memset(written, 0); @memcpy(written[0..11], "HELLO DISK "); @memcpy(written[disk35.image_size - 4 ..], "TAIL");
try blocks(testing.io, alloc, path, written);
const back = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(file_limit)); defer alloc.free(back); try testing.expectEqual(disk35.image_size, back.len); try testing.expectEqualStrings("HELLO DISK ", back[0..11]); try testing.expectEqualStrings("TAIL", back[back.len - 4 ..]);}
test "a disk written back keeps the wrapper it came in" { // A 2IMG is a header and then the blocks, and what goes back is the whole // file: the header has to survive, or the disk stops being readable by // whatever put it in one. const alloc = testing.allocator; const dir = testing.environ.getPosix("TMPDIR") orelse "/tmp"; const path = try std.fmt.allocPrint(alloc, "{s}/zig65-writeback-wrapper.2mg", .{dir}); defer { std.Io.Dir.cwd().deleteFile(testing.io, path) catch {}; alloc.free(path); }
// The smallest header that `twomg.open` will take: the mark, the format // word saying ProDOS order, where the data starts and how much of it there // is. const header = twomg.header_size; const file = try alloc.alloc(u8, header + disk35.image_size); defer alloc.free(file); @memset(file, 0); @memcpy(file[0..4], twomg.magic); std.mem.writeInt(u32, file[12..16], 1, .little); // ProDOS order std.mem.writeInt(u32, file[20..24], disk35.image_size / 512, .little); std.mem.writeInt(u32, file[24..28], header, .little); std.mem.writeInt(u32, file[28..32], disk35.image_size, .little); try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = file });
const written = try alloc.alloc(u8, disk35.image_size); defer alloc.free(written); @memset(written, 0); @memcpy(written[0..5], "BLOCK"); try blocks(testing.io, alloc, path, written);
const back = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(file_limit)); defer alloc.free(back); try testing.expectEqualStrings("2IMG", back[0..4]); try testing.expectEqualStrings("BLOCK", back[header..][0..5]);}
test "a disk written back to an archive keeps its change and stays a NuFX" { const alloc = testing.allocator;
// A small disk, and a `.SDK` around it the way a source archive comes. const original = try alloc.alloc(u8, 512 * 4); defer alloc.free(original); @memset(original, 0); @memcpy(original[0..5], "FIRST"); const sdk = try shrinkit.writer.diskAlloc(alloc, .{ .name = "MYDISK", .data = original }, .{}); defer alloc.free(sdk);
// What the machine wrote onto it instead. const changed = try alloc.dupe(u8, original); defer alloc.free(changed); @memcpy(changed[0..5], "AFTER");
const rebuilt = try reArchive(alloc, sdk, changed); defer alloc.free(rebuilt);
// One record still, the name kept, and the disk inside it is the change. const archive = try shrinkit.nufx.open(rebuilt); try testing.expectEqual(@as(u32, 1), archive.records); const record, _ = try shrinkit.nufx.findDisk(archive); try testing.expectEqualStrings("MYDISK", record.filename(rebuilt)); const back = try shrinkit.nufx.diskAlloc(alloc, rebuilt); defer alloc.free(back); try testing.expectEqualSlices(u8, changed, back);}
test "an archive holding more than the disk is refused rather than rebuilt lossily" { const alloc = testing.allocator;
var builder: shrinkit.writer.Builder = .init(alloc, .{}); defer builder.deinit(); const disk = [_]u8{0} ** 512; try builder.addDisk(.{ .name = "DISK", .data = &disk }); try builder.addFile(.{ .name = "NOTES", .data = "and a file beside it" }); const multi = try builder.toOwnedSlice(); defer alloc.free(multi);
try testing.expectError(error.Unwritable, reArchive(alloc, multi, &disk));}