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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! DOS 3.3 as it lies on a disk: the volume table of contents that says which//! sectors are spoken for, the catalog that names the files, and the track and//! sector lists that say where each file's bytes are.//!//! This works on the plain image a `.dsk` file holds rather than on the//! encoded surface a drive reads, so a disk can be made and filled here and//! then handed to `disk2.Floppy.load` for the machine to use, or read back out//! of one that `disk2.Floppy.save` has written. Nothing here allocates: the//! caller owns the image and every operation works in place.//!//! Beneath Apple DOS is where all of this comes from (Worth & Lechner, 1981,//! Chapter 4), and the offsets quoted throughout are its.
const std = @import("std");const testing = std.testing;
const disk2 = @import("disk2.zig");
pub const tracks_per_disk = disk2.tracks_per_disk;pub const sectors_per_track = disk2.sectors_per_track;pub const bytes_per_sector = disk2.bytes_per_sector;pub const bytes_per_track = disk2.bytes_per_track;pub const image_size = disk2.image_size;
/// Track 17 is the middle of the thirty-five, which is where the catalog goes/// so that the head has the shortest distance to travel to reach it from/// wherever it happens to be.pub const catalog_track = 17;
/// The volume table of contents is the first sector of that track. The catalog/// runs backwards from the last sector of it, so that reading it in order/// follows the head round rather than waiting a revolution a time.pub const vtoc_sector = 0;pub const first_catalog_sector = 15;
/// Tracks 0 to 2 hold DOS itself: the boot sector the drive's PROM reads, and/// the rest read in by that. INIT reserves them whether or not anything is/// written there, and so does `format`, which leaves them empty. Copying an/// image of DOS over the first `dos_tracks * bytes_per_track` bytes is what/// makes a disk bootable; nothing else here needs them.pub const dos_tracks = 3;
/// Thirty characters of name, seven entries to a catalog sector, thirty-five/// bytes to an entry.pub const name_length = 30;pub const entries_per_sector = 7;pub const entry_size = 35;const first_entry = 0x0b;
/// How many track and sector pairs one list sector holds: the sector is 256/// bytes, twelve of them are its own header, and a pair is two.pub const pairs_per_list = (bytes_per_sector - 0x0c) / 2;const first_pair = 0x0c;
/// The volume number an unnumbered disk gets. DOS writes it into every address/// field and compares it on every read, and 254 is what INIT uses unless told/// otherwise.pub const default_volume = 254;
/// Where things are in the volume table of contents.const vtoc = struct { const track_of_catalog = 0x01; const sector_of_catalog = 0x02; const release = 0x03; const volume = 0x06; const pairs = 0x27; const last_track = 0x30; const direction = 0x31; const tracks = 0x34; const sectors = 0x35; const bytes = 0x36; const bitmap = 0x38;};
/// Where things are in a file's catalog entry.const field = struct { const track = 0x00; const sector = 0x01; const kind = 0x02; const name = 0x03; /// A deleted entry keeps the track its list started on here, in the last /// byte of the name, so that the file can be put back. const deleted_track = 0x20; const length = 0x21;};
/// Where things are in a track and sector list.const list = struct { const next_track = 0x01; const next_sector = 0x02; const offset = 0x05;};
/// What a catalog entry says a file is. The value is the low seven bits of the/// type byte, the eighth being whether the file is locked.////// Two pairs share a letter in the catalog: $20 and $40 are the "A" and "B"/// types, which nothing much ever wrote. The set is open because the byte on/// the disk is whatever was put there, and a disk that holds something else/// should still be readable.pub const FileType = enum(u7) { text = 0x00, integer_basic = 0x01, applesoft = 0x02, binary = 0x04, s = 0x08, relocatable = 0x10, a = 0x20, b = 0x40, _,
/// The letter the catalog shows for it, or a question mark for a type /// byte that is none of the eight. pub fn letter(self: FileType) u8 { return switch (self) { .text => 'T', .integer_basic => 'I', .applesoft => 'A', .binary => 'B', .s => 'S', .relocatable => 'R', .a => 'A', .b => 'B', _ => '?', }; }};
/// Where a catalog entry sits, so that it can be written back after being/// read.pub const Slot = struct { track: u8, sector: u8, index: u8,};
/// A file, as its catalog entry describes it.pub const Entry = struct { slot: Slot, /// The first track and sector list sector. track: u8, sector: u8, kind: FileType, locked: bool, /// The length in sectors, which counts the list sectors as well as the /// data, since that is the figure the catalog prints. sectors: u16, stored: [name_length]u8, length: u8,
/// The name with the high bits taken off and the padding trimmed. pub fn name(self: *const Entry) []const u8 { return self.stored[0..self.length]; }
fn from(bytes: *const [entry_size]u8, slot: Slot) Entry { var self: Entry = .{ .slot = slot, .track = bytes[field.track], .sector = bytes[field.sector], .kind = @enumFromInt(@as(u7, @truncate(bytes[field.kind]))), .locked = bytes[field.kind] & 0x80 != 0, .sectors = std.mem.readInt(u16, bytes[field.length..][0..2], .little), .stored = undefined, .length = 0, }; for (&self.stored, bytes[field.name..][0..name_length]) |*into, byte| into.* = byte & 0x7f; var end: usize = name_length; while (end > 0 and self.stored[end - 1] == ' ') end -= 1; self.length = @intCast(end); return self; }};
/// A DOS 3.3 disk, held as the plain image a file holds and nothing more. Copy/// it about freely: it is a slice, and every operation writes through it.pub const Disk = struct { image: []u8, /// Whether anything has been written since the disk was opened or last /// saved, so that a caller knows whether writing the image back is worth /// doing. `format` leaves it set, since a disk just laid out is not what /// any file holds. Writing through `sectorAt` is not noticed: a caller /// reaching in that far sets this itself. dirty: bool = false,
pub const SizeError = error{WrongSize}; pub const OpenError = SizeError || error{NotDos33}; pub const NameError = error{BadName}; pub const WriteError = NameError || error{ DiskFull, CatalogFull, FileLocked }; pub const DeleteError = error{ FileNotFound, FileLocked }; pub const ReadError = error{ FileNotFound, Damaged } || std.Io.Writer.Error;
/// Lays out an empty disk the way INIT does: a volume table of contents, a /// chain of empty catalog sectors, and every sector free but the three /// tracks DOS lives on and the one the catalog is on. /// /// Those three tracks are left as they are rather than zeroed, so that a /// caller who has copied an image of DOS into them keeps it and ends up /// with a disk that boots. pub fn format(image: []u8, number: u8) SizeError!Disk { if (image.len != image_size) return error.WrongSize; var self: Disk = .{ .image = image, .dirty = true }; @memset(image[dos_tracks * bytes_per_track ..], 0);
const table = self.sectorAt(catalog_track, vtoc_sector); // INIT leaves a four in the first byte. Nothing reads it, but a disk // without it is not quite what the machine would have written. table[0x00] = 0x04; table[vtoc.track_of_catalog] = catalog_track; table[vtoc.sector_of_catalog] = first_catalog_sector; table[vtoc.release] = 3; table[vtoc.volume] = number; table[vtoc.pairs] = pairs_per_list; table[vtoc.last_track] = catalog_track + 1; table[vtoc.direction] = 1; table[vtoc.tracks] = tracks_per_disk; table[vtoc.sectors] = sectors_per_track; std.mem.writeInt(u16, table[vtoc.bytes..][0..2], bytes_per_sector, .little);
for (0..tracks_per_disk) |track| { const reserved = track < dos_tracks or track == catalog_track; for (0..sectors_per_track) |sector| { self.setFree(@intCast(track), @intCast(sector), !reserved); } }
var sector: u8 = first_catalog_sector; while (sector > 0) : (sector -= 1) { const entries = self.sectorAt(catalog_track, sector); @memset(entries, 0); if (sector > 1) { entries[0x01] = catalog_track; entries[0x02] = sector - 1; } } return self; }
/// Takes an image that already holds a disk, checking that the volume /// table of contents describes the disk this is: thirty-five tracks of /// sixteen sectors of 256 bytes, with a catalog somewhere on it. pub fn open(image: []u8) OpenError!Disk { if (image.len != image_size) return error.WrongSize; const self: Disk = .{ .image = image }; const table = self.sectorAt(catalog_track, vtoc_sector); if (table[vtoc.track_of_catalog] >= tracks_per_disk) return error.NotDos33; if (table[vtoc.sector_of_catalog] >= sectors_per_track) return error.NotDos33; if (table[vtoc.tracks] != tracks_per_disk) return error.NotDos33; if (table[vtoc.sectors] != sectors_per_track) return error.NotDos33; if (std.mem.readInt(u16, table[vtoc.bytes..][0..2], .little) != bytes_per_sector) return error.NotDos33; return self; }
/// Reads a whole image off the file system and opens it, which is all /// that pointing any of this at a `.dsk` file amounts to: a disk is /// 140K, so it is read in one piece, worked on in place, and written /// back. The caller owns `image` and frees it. /// /// var disk = try Disk.openFile(.cwd(), io, "game.dsk", allocator); /// defer allocator.free(disk.image); pub fn openFile( dir: std.Io.Dir, io: std.Io, sub_path: []const u8, gpa: std.mem.Allocator, ) !Disk { // One more than a disk, so that a file of exactly the right size is // read rather than being taken for the start of a longer one. const image = try dir.readFileAlloc(io, sub_path, gpa, .limited(image_size + 1)); errdefer gpa.free(image); return open(image); }
/// Writes the image back over a file, and marks the disk as no longer /// needing it. pub fn saveFile(self: *Disk, dir: std.Io.Dir, io: std.Io, sub_path: []const u8) !void { try dir.writeFile(io, .{ .sub_path = sub_path, .data = self.image }); self.dirty = false; }
/// The volume number, which DOS writes into every address field on the /// disk and checks on every read. pub fn volume(self: *const Disk) u8 { return self.sectorAt(catalog_track, vtoc_sector)[vtoc.volume]; }
/// How many sectors the bit map says are still going spare. pub fn freeSectors(self: *const Disk) u16 { var count: u16 = 0; for (0..tracks_per_disk) |track| { for (0..sectors_per_track) |sector| { if (self.isFree(@intCast(track), @intCast(sector))) count += 1; } } return count; }
/// Every file on the disk, in the order the catalog holds them, which is /// the order CATALOG prints. pub fn catalog(self: *const Disk) Catalog { return .{ .slots = self.slots() }; }
/// The entry for a name, or nothing if the disk has no such file. pub fn find(self: *const Disk, name: []const u8) ?Entry { var wanted: [name_length]u8 = undefined; store(name, &wanted) catch return null; const slot = self.findSlot(&wanted) orelse return null; return Entry.from(self.entryAt(slot), slot); }
/// Writes a file's bytes out, following the track and sector list. /// /// What comes back is whole sectors, since sectors are all DOS records: /// the catalog says how many a file has and nothing says how many bytes of /// the last one mean anything. For the types that carry it, the length is /// in the file's own first bytes, which is what `binaryPrefix` and /// `basicPrefix` write. /// /// A pair of zeroes in the middle of a list is a hole, left by a text file /// written at a record number nothing has reached yet, and reads back as a /// sector of zeroes. The zeroes after the last pair are just the unused /// end of the list. pub fn read(self: *const Disk, name: []const u8, writer: *std.Io.Writer) ReadError!void { const entry = self.find(name) orelse return error.FileNotFound; const hole: [bytes_per_sector]u8 = @splat(0);
var track = entry.track; var sector = entry.sector; var lists: usize = 0; while (track != 0 or sector != 0) { if (track >= tracks_per_disk or sector >= sectors_per_track) return error.Damaged; lists += 1; if (lists > tracks_per_disk * sectors_per_track) return error.Damaged;
const pairs = self.sectorAt(track, sector); var used: usize = 0; for (0..pairs_per_list) |i| { const pair = pairs[first_pair + i * 2 ..][0..2]; if (pair[0] != 0 or pair[1] != 0) used = i + 1; } for (0..used) |i| { const pair = pairs[first_pair + i * 2 ..][0..2]; if (pair[0] == 0 and pair[1] == 0) { try writer.writeAll(&hole); continue; } if (pair[0] >= tracks_per_disk or pair[1] >= sectors_per_track) return error.Damaged; try writer.writeAll(self.sectorAt(pair[0], pair[1])); }
track = pairs[list.next_track]; sector = pairs[list.next_sector]; } }
/// Puts a file on the disk, over one of the same name if there is one, the /// way SAVE writes over a program. pub fn write(self: *Disk, name: []const u8, kind: FileType, data: []const u8) WriteError!void { return self.writeParts(name, kind, &.{data}); }
/// The same, from several pieces laid end to end, so that a header can be /// put in front of a body without joining the two first. pub fn writeParts( self: *Disk, name: []const u8, kind: FileType, parts: []const []const u8, ) WriteError!void { var wanted: [name_length]u8 = undefined; try store(name, &wanted);
var bytes: usize = 0; for (parts) |part| bytes += part.len; const data_sectors = (bytes + bytes_per_sector - 1) / bytes_per_sector; const lists = @max(1, (data_sectors + pairs_per_list - 1) / pairs_per_list);
// Everything that can refuse the write is settled before anything is // touched, so that a disk that turns out to be too full still holds // the file that was there. const existing = self.findSlot(&wanted); var room = self.freeSectors(); if (existing) |slot| { const entry = self.entryAt(slot); if (entry[field.kind] & 0x80 != 0) return error.FileLocked; room += std.mem.readInt(u16, entry[field.length..][0..2], .little); } if (data_sectors + lists > room) return error.DiskFull; const slot = existing orelse self.freeSlot() orelse return error.CatalogFull; if (existing != null) self.release(slot);
var first: [2]u8 = .{ 0, 0 }; var previous: ?[2]u8 = null; var written: usize = 0; var at: usize = 0; for (0..lists) |index| { const where = self.allocate() orelse return error.DiskFull; const pairs = self.sectorAt(where[0], where[1]); @memset(pairs, 0); std.mem.writeInt(u16, pairs[list.offset..][0..2], @intCast(index * pairs_per_list), .little); if (previous) |before| { const earlier = self.sectorAt(before[0], before[1]); earlier[list.next_track] = where[0]; earlier[list.next_sector] = where[1]; } else { first = where; } previous = where;
var pair: usize = 0; while (pair < pairs_per_list and written < data_sectors) : (pair += 1) { const put = self.allocate() orelse return error.DiskFull; const target = self.sectorAt(put[0], put[1]); @memset(target, 0); gather(parts, at, target); at += bytes_per_sector; pairs[first_pair + pair * 2] = put[0]; pairs[first_pair + pair * 2 + 1] = put[1]; written += 1; } }
const entry = self.entryAt(slot); @memset(entry, 0); entry[field.track] = first[0]; entry[field.sector] = first[1]; entry[field.kind] = @intFromEnum(kind); @memcpy(entry[field.name..][0..name_length], &wanted); std.mem.writeInt(u16, entry[field.length..][0..2], @intCast(data_sectors + lists), .little); self.dirty = true; }
/// Takes a file off the disk, giving its sectors back. pub fn delete(self: *Disk, name: []const u8) DeleteError!void { var wanted: [name_length]u8 = undefined; store(name, &wanted) catch return error.FileNotFound; const slot = self.findSlot(&wanted) orelse return error.FileNotFound; if (self.entryAt(slot)[field.kind] & 0x80 != 0) return error.FileLocked; self.release(slot); self.dirty = true; }
/// Puts the lock on a file, or takes it off, which is what DOS's LOCK and /// UNLOCK do to the top bit of the type byte. pub fn setLocked(self: *Disk, name: []const u8, locked: bool) error{FileNotFound}!void { var wanted: [name_length]u8 = undefined; store(name, &wanted) catch return error.FileNotFound; const slot = self.findSlot(&wanted) orelse return error.FileNotFound; const entry = self.entryAt(slot); if (locked) entry[field.kind] |= 0x80 else entry[field.kind] &= 0x7f; self.dirty = true; }
/// One sector of the image. The image holds them in the order DOS numbers /// them; where they sit on the track is the encoder's business. /// /// What comes back can be written to even from a disk held as a constant, /// since the image is the caller's and this only points into it. Nothing /// written that way sets `dirty` or touches the bit map, so a caller /// working at this level is on its own. pub fn sectorAt(self: *const Disk, track: u8, sector: u8) *[bytes_per_sector]u8 { const at = (@as(usize, track) * sectors_per_track + sector) * bytes_per_sector; return self.image[at..][0..bytes_per_sector]; }
/// The four bytes of the bit map that cover one track. Two are used: the /// first holds sectors 15 down to 8 from the top bit down, the second /// sectors 7 down to 0. A bit set means the sector is free. fn bitmapAt(self: *const Disk, track: u8) *[4]u8 { const table = self.sectorAt(catalog_track, vtoc_sector); return table[vtoc.bitmap + @as(usize, track) * 4 ..][0..4]; }
fn isFree(self: *const Disk, track: u8, sector: u8) bool { const map = self.bitmapAt(track); const byte = if (sector >= 8) map[0] else map[1]; return byte >> @intCast(sector % 8) & 1 == 1; }
fn setFree(self: *Disk, track: u8, sector: u8, free: bool) void { const map = self.bitmapAt(track); const index: usize = if (sector >= 8) 0 else 1; const bit = @as(u8, 1) << @intCast(sector % 8); if (free) map[index] |= bit else map[index] &= ~bit; }
/// Takes the next free sector, the way DOS does: outward from where it /// last wrote, highest sector of a track first, turning round at the edge /// of the disk to fill the tracks on the other side of the catalog. fn allocate(self: *Disk) ?[2]u8 { const table = self.sectorAt(catalog_track, vtoc_sector); var track: i16 = table[vtoc.last_track]; var step: i16 = if (table[vtoc.direction] == 0xff) -1 else 1;
for (0..tracks_per_disk * 2) |_| { if (track >= 0 and track < tracks_per_disk and track != catalog_track) { var sector: u8 = sectors_per_track; while (sector > 0) { sector -= 1; if (!self.isFree(@intCast(track), sector)) continue; self.setFree(@intCast(track), sector, false); table[vtoc.last_track] = @intCast(track); table[vtoc.direction] = if (step < 0) 0xff else 0x01; return .{ @intCast(track), sector }; } } track += step; if (track < 0 or track >= tracks_per_disk) { step = -step; track = catalog_track + step; } } return null; }
/// Frees everything a file holds and marks its entry gone. DOS moves the /// track its list started on into the last byte of the name and writes /// $ff over it, which is what leaves a deleted file recoverable. fn release(self: *Disk, slot: Slot) void { const entry = self.entryAt(slot); var track = entry[field.track]; var sector = entry[field.sector]; for (0..tracks_per_disk * sectors_per_track) |_| { if (track == 0 and sector == 0) break; if (track >= tracks_per_disk or sector >= sectors_per_track) break; const pairs = self.sectorAt(track, sector); for (0..pairs_per_list) |i| { const pair = pairs[first_pair + i * 2 ..][0..2]; if (pair[0] == 0 and pair[1] == 0) continue; if (pair[0] >= tracks_per_disk or pair[1] >= sectors_per_track) continue; self.setFree(pair[0], pair[1], true); } const next_track = pairs[list.next_track]; const next_sector = pairs[list.next_sector]; self.setFree(track, sector, true); track = next_track; sector = next_sector; } entry[field.deleted_track] = entry[field.track]; entry[field.track] = 0xff; }
fn entryAt(self: *const Disk, slot: Slot) *[entry_size]u8 { const entries = self.sectorAt(slot.track, slot.sector); return entries[first_entry + @as(usize, slot.index) * entry_size ..][0..entry_size]; }
fn slots(self: *const Disk) Slots { const table = self.sectorAt(catalog_track, vtoc_sector); return .{ .disk = self.*, .track = table[vtoc.track_of_catalog], .sector = table[vtoc.sector_of_catalog], }; }
fn findSlot(self: *const Disk, wanted: *const [name_length]u8) ?Slot { var walk = self.slots(); while (walk.next()) |slot| { const entry = self.entryAt(slot); if (entry[field.track] == 0x00 or entry[field.track] == 0xff) continue; if (std.mem.eql(u8, entry[field.name..][0..name_length], wanted)) return slot; } return null; }
fn freeSlot(self: *const Disk) ?Slot { var walk = self.slots(); while (walk.next()) |slot| { const entry = self.entryAt(slot); if (entry[field.track] == 0x00 or entry[field.track] == 0xff) return slot; } return null; }};
/// Every catalog entry there is, used or not, which is what finding a file and/// finding somewhere to put one both walk.const Slots = struct { disk: Disk, track: u8, sector: u8, index: u8 = 0, visited: u8 = 0,
fn next(self: *Slots) ?Slot { while (self.track != 0 or self.sector != 0) { if (self.track >= tracks_per_disk or self.sector >= sectors_per_track) return null; if (self.index >= entries_per_sector) { const entries = self.disk.sectorAt(self.track, self.sector); self.track = entries[0x01]; self.sector = entries[0x02]; self.index = 0; // A chain that bites its own tail would otherwise go round // for ever, and no disk has more catalog sectors than a track // holds. self.visited += 1; if (self.visited > sectors_per_track) return null; continue; } const slot: Slot = .{ .track = self.track, .sector = self.sector, .index = self.index }; self.index += 1; return slot; } return null; }};
/// The files on a disk, skipping the entries that never held one and the ones/// whose file has been deleted.pub const Catalog = struct { slots: Slots,
pub fn next(self: *Catalog) ?Entry { while (self.slots.next()) |slot| { const entry = self.slots.disk.entryAt(slot); if (entry[field.track] == 0x00 or entry[field.track] == 0xff) continue; return Entry.from(entry, slot); } return null; }};
/// What BSAVE puts at the front of a binary file: where it came from and how/// long it is, so that BLOAD knows where to put it back and how much to read.pub fn binaryPrefix(address: u16, length: u16) [4]u8 { var prefix: [4]u8 = undefined; std.mem.writeInt(u16, prefix[0..2], address, .little); std.mem.writeInt(u16, prefix[2..4], length, .little); return prefix;}
/// What SAVE puts at the front of an Applesoft or Integer BASIC program: its/// length, since the sectors it sits in hold whatever was there before past/// the end of it.pub fn basicPrefix(length: u16) [2]u8 { var prefix: [2]u8 = undefined; std.mem.writeInt(u16, prefix[0..2], length, .little); return prefix;}
/// Puts a name into the thirty bytes an entry holds it in: the high bit set on/// every character, and spaces to the end.////// A comma is refused because DOS's own command parser stops at one, so a file/// with a comma in its name could not be named to LOAD or DELETE. Anything/// outside printable ASCII is refused for the same reason: the keyboard could/// not produce it. DOS's parser also wants the first character to be a letter,/// which is not enforced here, since the file manager itself does not.fn store(name: []const u8, into: *[name_length]u8) Disk.NameError!void { if (name.len == 0 or name.len > name_length) return error.BadName; @memset(into, ' ' | 0x80); for (name, 0..) |character, i| { if (character < 0x20 or character > 0x7e or character == ',') return error.BadName; into[i] = character | 0x80; }}
/// Copies one sector's worth out of a run of pieces laid end to end, starting/// at a byte offset into the whole.fn gather(parts: []const []const u8, from: usize, into: *[bytes_per_sector]u8) void { var at = from; var put: usize = 0; for (parts) |part| { if (at >= part.len) { at -= part.len; continue; } const take = @min(part.len - at, bytes_per_sector - put); @memcpy(into[put..][0..take], part[at..][0..take]); put += take; at = 0; if (put == bytes_per_sector) return; }}
/// A disk to work on, since 140K is more than a test wants on its stack.fn blank(allocator: std.mem.Allocator) !Disk { const image = try allocator.alloc(u8, image_size); @memset(image, 0); return Disk.format(image, default_volume);}
test "a formatted disk has the shape INIT gives it" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
// Beneath Apple DOS (Worth & Lechner, 1981, Table 4.1): what the volume // table of contents says about the disk it is on. const table = disk.sectorAt(catalog_track, vtoc_sector); try testing.expectEqual(@as(u8, catalog_track), table[vtoc.track_of_catalog]); try testing.expectEqual(@as(u8, first_catalog_sector), table[vtoc.sector_of_catalog]); try testing.expectEqual(@as(u8, 3), table[vtoc.release]); try testing.expectEqual(@as(u8, 122), table[vtoc.pairs]); try testing.expectEqual(@as(u8, 35), table[vtoc.tracks]); try testing.expectEqual(@as(u8, 16), table[vtoc.sectors]); try testing.expectEqual(@as(u16, 256), std.mem.readInt(u16, table[vtoc.bytes..][0..2], .little)); try testing.expectEqual(@as(u8, default_volume), disk.volume());
// Everything is free but the three tracks DOS lives on and the one this // sector is on, which is thirty-one tracks of sixteen. try testing.expectEqual(@as(u16, 31 * 16), disk.freeSectors()); try testing.expect(!disk.isFree(0, 0)); try testing.expect(!disk.isFree(2, 15)); try testing.expect(!disk.isFree(catalog_track, 0)); try testing.expect(disk.isFree(3, 0)); try testing.expect(disk.isFree(34, 15));
// Fifteen catalog sectors, each pointing at the next, and nothing in any // of them. var walk = disk.slots(); var count: usize = 0; while (walk.next()) |_| count += 1; try testing.expectEqual(@as(usize, 15 * entries_per_sector), count); var files = disk.catalog(); try testing.expectEqual(@as(?Entry, null), files.next());
// And it is a disk this module will open again. _ = try Disk.open(disk.image);}
test "a file comes back the way it went on" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
var data: [700]u8 = undefined; for (&data, 0..) |*byte, i| byte.* = @truncate(i * 3 + i / 5); try disk.write("HELLO", .binary, &data);
const entry = disk.find("HELLO") orelse return error.NotFound; try testing.expectEqualStrings("HELLO", entry.name()); try testing.expectEqual(FileType.binary, entry.kind); try testing.expect(!entry.locked); // Three sectors of data and the list that says where they are, which is // the figure CATALOG prints. try testing.expectEqual(@as(u16, 4), entry.sectors); try testing.expectEqual(@as(u16, 31 * 16 - 4), disk.freeSectors());
// What comes back is whole sectors: the file's own length is its // business, not the catalog's. var buffer: [4 * bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try disk.read("HELLO", &writer); const read = writer.buffered(); try testing.expectEqual(@as(usize, 3 * bytes_per_sector), read.len); try testing.expectEqualSlices(u8, &data, read[0..data.len]); for (read[data.len..]) |byte| try testing.expectEqual(@as(u8, 0), byte);
try testing.expectError(error.FileNotFound, disk.read("NOTHERE", &writer));}
test "a file in pieces is laid end to end" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
// What BSAVE writes: where the bytes came from and how many, and then the // bytes, which here straddle the end of the first sector. const body: [300]u8 = @splat(0xa9); const prefix = binaryPrefix(0x0300, body.len); try disk.writeParts("PROGRAM", .binary, &.{ &prefix, &body });
var buffer: [2 * bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try disk.read("PROGRAM", &writer); const read = writer.buffered(); try testing.expectEqual(@as(u16, 0x0300), std.mem.readInt(u16, read[0..2], .little)); try testing.expectEqual(@as(u16, body.len), std.mem.readInt(u16, read[2..4], .little)); try testing.expectEqualSlices(u8, &body, read[4 .. 4 + body.len]);}
test "a file too long for one list gets another" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
// One sector more than a list has room for, so a second list is needed // and has to say where in the file it takes over. const sectors = pairs_per_list + 1; const data = try testing.allocator.alloc(u8, sectors * bytes_per_sector); defer testing.allocator.free(data); for (data, 0..) |*byte, i| byte.* = @truncate(i / bytes_per_sector); try disk.write("BIG", .text, data);
const entry = disk.find("BIG") orelse return error.NotFound; try testing.expectEqual(@as(u16, sectors + 2), entry.sectors);
const second = disk.sectorAt(entry.track, entry.sector)[list.next_track]; try testing.expect(second != 0);
const back = try testing.allocator.alloc(u8, data.len); defer testing.allocator.free(back); var writer: std.Io.Writer = .fixed(back); try disk.read("BIG", &writer); try testing.expectEqualSlices(u8, data, writer.buffered());}
test "the catalog shows what is on the disk" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
try disk.write("FIRST", .applesoft, "one"); try disk.write("SECOND", .text, "two"); try disk.write("THIRD", .integer_basic, "three"); try disk.setLocked("SECOND", true);
var files = disk.catalog(); const first = files.next() orelse return error.NotFound; try testing.expectEqualStrings("FIRST", first.name()); try testing.expectEqual(@as(u8, 'A'), first.kind.letter()); const second = files.next() orelse return error.NotFound; try testing.expectEqualStrings("SECOND", second.name()); try testing.expect(second.locked); const third = files.next() orelse return error.NotFound; try testing.expectEqualStrings("THIRD", third.name()); try testing.expectEqual(@as(u8, 'I'), third.kind.letter()); try testing.expectEqual(@as(?Entry, null), files.next());}
test "deleting a file gives its sectors back" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image); const before = disk.freeSectors();
const data: [1000]u8 = @splat(0x55); try disk.write("GONE", .binary, &data); try testing.expect(disk.freeSectors() < before); try disk.delete("GONE"); try testing.expectEqual(before, disk.freeSectors()); try testing.expectEqual(@as(?Entry, null), disk.find("GONE"));
// The way DOS marks it gone: $ff over the track, which is kept in the // last byte of the name so that the file could be put back. const slot: Slot = .{ .track = catalog_track, .sector = first_catalog_sector, .index = 0 }; const entry = disk.entryAt(slot); try testing.expectEqual(@as(u8, 0xff), entry[field.track]); try testing.expect(entry[field.deleted_track] != 0xff);
// And the entry is free for the next file, rather than lost. try disk.write("AFTER", .text, "x"); try testing.expectEqual(slot.index, (disk.find("AFTER") orelse return error.NotFound).slot.index);
try testing.expectError(error.FileNotFound, disk.delete("GONE"));}
test "a file is written over, unless it is locked" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
const long: [2000]u8 = @splat(0x11); try disk.write("SAME", .text, &long); const after_long = disk.freeSectors();
// Writing over it takes the same entry and gives back what the longer // version held. try disk.write("SAME", .applesoft, "short"); const entry = disk.find("SAME") orelse return error.NotFound; try testing.expectEqual(FileType.applesoft, entry.kind); try testing.expectEqual(@as(u16, 2), entry.sectors); try testing.expect(disk.freeSectors() > after_long); var count: usize = 0; var files = disk.catalog(); while (files.next()) |_| count += 1; try testing.expectEqual(@as(usize, 1), count);
// A locked file is left alone, as DOS leaves it. try disk.setLocked("SAME", true); try testing.expectError(error.FileLocked, disk.write("SAME", .text, "no")); try testing.expectError(error.FileLocked, disk.delete("SAME")); try disk.setLocked("SAME", false); try disk.write("SAME", .text, "yes");}
test "a name DOS could not use is refused" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
try testing.expectError(error.BadName, disk.write("", .text, "x")); try testing.expectError(error.BadName, disk.write("A" ** 31, .text, "x")); // DOS's own parser stops at a comma, so the file could never be named. try testing.expectError(error.BadName, disk.write("A,B", .text, "x")); try testing.expectError(error.BadName, disk.write("A\x00B", .text, "x")); // Thirty is the limit, and a name is padded out to it with spaces. try disk.write("A" ** 30, .text, "x"); try testing.expectEqualStrings("A" ** 30, (disk.find("A" ** 30) orelse return error.NotFound).name());}
test "the disk and the catalog both fill up" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
// A file that wants more sectors than the disk has left is refused, and // refused before anything is written. const free_at_first = disk.freeSectors(); const too_big = try testing.allocator.alloc(u8, @as(usize, free_at_first) * bytes_per_sector); defer testing.allocator.free(too_big); @memset(too_big, 0); try testing.expectError(error.DiskFull, disk.write("HUGE", .binary, too_big)); try testing.expectEqual(free_at_first, disk.freeSectors()); try testing.expectEqual(@as(?Entry, null), disk.find("HUGE"));
// The catalog holds seven entries in each of fifteen sectors, and the // hundred and sixth file has nowhere to go. var name: [8]u8 = undefined; for (0..15 * entries_per_sector) |i| { try disk.write(try std.fmt.bufPrint(&name, "F{d}", .{i}), .text, "x"); } try testing.expectError(error.CatalogFull, disk.write("ONEMORE", .text, "x"));}
test "a hole in a file reads back as a sector of nothing" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image);
// What a text file written at a record number nothing has reached yet // looks like: a pair of zeroes in the middle of the list, which DOS // leaves unallocated until something writes there. const data: [3 * bytes_per_sector]u8 = @splat(0x7f); try disk.write("SPARSE", .text, &data); const entry = disk.find("SPARSE") orelse return error.NotFound; const pairs = disk.sectorAt(entry.track, entry.sector); disk.setFree(pairs[first_pair + 2], pairs[first_pair + 3], true); pairs[first_pair + 2] = 0; pairs[first_pair + 3] = 0;
var buffer: [3 * bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try disk.read("SPARSE", &writer); const read = writer.buffered(); try testing.expectEqual(@as(usize, 3 * bytes_per_sector), read.len); for (read[0..bytes_per_sector]) |byte| try testing.expectEqual(@as(u8, 0x7f), byte); for (read[bytes_per_sector .. 2 * bytes_per_sector]) |byte| try testing.expectEqual(@as(u8, 0), byte); for (read[2 * bytes_per_sector ..]) |byte| try testing.expectEqual(@as(u8, 0x7f), byte);}
test "a disk built here survives being written to a surface and read back" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image); try disk.write("ROUNDTRIP", .binary, "the bytes that went on");
// Through the encoder and back: what a drive would lay down, and what // saving the disk afterwards gives. const floppy = try testing.allocator.create(disk2.Floppy); defer testing.allocator.destroy(floppy); floppy.* = .{}; try floppy.load(disk.image, .dos);
const saved = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(saved); @memcpy(saved, disk.image); try floppy.save(saved); try testing.expectEqualSlices(u8, disk.image, saved);
const again = try Disk.open(saved); var buffer: [bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try again.read("ROUNDTRIP", &writer); try testing.expectEqualStrings("the bytes that went on", writer.buffered()[0.."the bytes that went on".len]);}
test "an image that holds no DOS 3.3 disk is not opened" { const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); try testing.expectError(error.NotDos33, Disk.open(image)); try testing.expectError(error.WrongSize, Disk.open(image[0 .. image_size - 1])); try testing.expectError(error.WrongSize, Disk.format(image[0..10], 254));}
test "a disk says when it has been written to" { var disk = try blank(testing.allocator); defer testing.allocator.free(disk.image); // A disk just laid out is not what any file holds. try testing.expect(disk.dirty); disk.dirty = false;
try disk.write("ONE", .text, "x"); try testing.expect(disk.dirty); disk.dirty = false;
// Reading changes nothing, so nothing is owed to the file. var buffer: [bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try disk.read("ONE", &writer); _ = disk.find("ONE"); _ = disk.freeSectors(); var files = disk.catalog(); while (files.next()) |_| {} try testing.expect(!disk.dirty);
// A write that was refused leaves the disk as it was, and says so. try testing.expectError(error.BadName, disk.write("A,B", .text, "x")); try testing.expectError(error.FileNotFound, disk.delete("NOTHERE")); try testing.expect(!disk.dirty);
try disk.setLocked("ONE", true); try testing.expect(disk.dirty); disk.dirty = false; try disk.setLocked("ONE", false); try disk.delete("ONE"); try testing.expect(disk.dirty);}
test "a disk is read off a file and written back to one" { var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const io = testing.io;
{ const image = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(image); @memset(image, 0); var made = try Disk.format(image, 200); try made.write("ON THE DISK", .binary, "what was put there"); try testing.expect(made.dirty); try made.saveFile(tmp.dir, io, "made.dsk"); // Saved is saved: there is nothing left to write back. try testing.expect(!made.dirty); }
var disk = try Disk.openFile(tmp.dir, io, "made.dsk", testing.allocator); defer testing.allocator.free(disk.image); try testing.expect(!disk.dirty); try testing.expectEqual(@as(u8, 200), disk.volume());
var buffer: [bytes_per_sector]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try disk.read("ON THE DISK", &writer); try testing.expectEqualStrings("what was put there", writer.buffered()[0.."what was put there".len]);
// And back the other way, over the same file. try disk.write("AND ANOTHER", .text, "more"); try disk.saveFile(tmp.dir, io, "made.dsk"); var again = try Disk.openFile(tmp.dir, io, "made.dsk", testing.allocator); defer testing.allocator.free(again.image); try testing.expect(again.find("AND ANOTHER") != null); try testing.expect(again.find("ON THE DISK") != null);
// A file that is not a disk at all is refused rather than half read. try tmp.dir.writeFile(io, .{ .sub_path = "short.dsk", .data = "not a disk" }); try testing.expectError(error.WrongSize, Disk.openFile(tmp.dir, io, "short.dsk", testing.allocator));}