From 347abeced54722d233ecd812fd4f05f4ea2acd79 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Tue, 1 Sep 2026 13:06:39 -0500 Subject: [PATCH] make ProDOS volumes, and the files and directories on them The other filing system, in the shape the DOS 3.3 one already has: `format` and `open`, `openFile` and `saveFile`, `dirty`, `write`, `writeParts`, `read`, `delete` and `setLocked`, with `find` and `catalog` for looking. What ProDOS asks for beyond that is directories, so everything takes a path, and `makeDirectory` makes one; index blocks, so `write` lays out a seedling, a sapling or a tree as the size demands and `read` follows whichever it finds; and a length kept to the byte, so what `read` gives back is the file rather than the blocks it sits in. Blocks are 512 bytes and there can be 65,535 of them, so the same code serves a floppy and a thirty-two megabyte hard disk; `disk2.reorder` puts a 5.25 inch image into the order that wants, since a file says nothing about which of the two it holds. Nothing here was taken on trust. The module reads a ProDOS 2.4.2 master disk file for file. A volume made here, holding nothing but a copied loader and ProDOS's own two files written by this module, boots this emulator to a BASIC prompt, catalogues itself with the right types, block counts, dates and lock stars, and agrees with the bit map here about how many blocks are free. ProDOS opens a directory this module wrote, and a directory ProDOS makes reads back here with every field where this module puts its own. The one place they differed was the access byte on a directory header, where ProDOS clears the backup bit, and that is what this does now. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01FawbWzEu5hoLLZSMCehUGP --- README.md | 65 +++ src/disk2.zig | 43 +- src/prodos.zig | 1402 ++++++++++++++++++++++++++++++++++++++++++++++++ src/root.zig | 4 + 4 files changed, 1513 insertions(+), 1 deletion(-) create mode 100644 src/prodos.zig diff --git a/README.md b/README.md index 6ecfca0..ebf79cd 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,70 @@ emulator and answers CATALOG with what was put on it. DOS reads a text file written here with EXEC, and a program DOS saves onto such a disk reads back through `read` as the Applesoft it is. +### Making a ProDOS volume + +`prodos` does the same for the other filing system, and where DOS 3.3 knew +only a 5.25 inch disk of 560 sectors, ProDOS works in 512 byte blocks and will +address 65,535 of them, so the same code serves a floppy and a thirty-two +megabyte hard disk. It works on blocks laid end to end, which is what a `.po` +file, a `.hdv` file and `blockdevice.Volume` all hold; a 5.25 inch image in DOS +order wants `disk2.reorder` first. + +```zig +var volume = try zig65.prodos.Volume.format(image, "WORK"); +volume.stamp = .from(2026, 9, 1, 12, 0); // there is no clock in here to ask + +try volume.makeDirectory("SOURCE"); +try volume.write("SOURCE/MAIN", .{ .kind = .text }, text); +try volume.write("STARTUP", .{ .kind = .system, .aux = 0x2000 }, code); + +var files = try volume.catalog("SOURCE"); +while (files.next()) |file| { + var kind: [3]u8 = undefined; + // "MAIN TXT 1", the way CAT prints it + std.debug.print("{s:<16}{s}{d:>8}\n", .{ file.name(), file.kind.abbreviation(&kind), file.blocks_used }); +} +``` + +It is the same shape as the DOS 3.3 one: `format` and `open`, `openFile` and +`saveFile`, `dirty`, and `write`, `writeParts`, `read`, `delete` and +`setLocked`, with `find` and `catalog` for looking. What ProDOS adds is +directories, so everything takes a path rather than a name: `SOURCE/MAIN`, or +`/WORK/SOURCE/MAIN` written out in full the way ProDOS writes one. +`makeDirectory` makes one, and a directory has to be empty before it can go. + +Two other things differ. ProDOS keeps a file's length to the byte, so `read` +gives back the file rather than the blocks it sits in. And a file's blocks are +found through index blocks, which `write` builds as the size demands: one +block is a seedling, up to 256 a sapling with an index, and beyond that a tree +whose key block indexes the indexes. A block pointer of zero anywhere in that +is a hole and reads back as zeroes. + +`stamp` is what goes on a file as it is written. There is no clock in the +library to ask, so a caller that wants dates on its files says what they are, +and one that does not gets what ProDOS shows as no date at all. + +This too was settled against the real thing rather than the book alone. The +module reads a ProDOS 2.4.2 master disk file for file, sapling index blocks +and all. A volume made here, with the loader copied into its first two blocks +and ProDOS's own two files written onto it by this module and nothing else, +boots on this emulator to a BASIC prompt and catalogues itself: + +``` +]CAT +/ZIG65 + NAME TYPE BLOCKS MODIFIED +*PRODOS SYS 35 1-SEP-26 +*BASIC.SYSTEM SYS 21 1-SEP-26 + MADE.BY.ZIG65 DIR 1 1-SEP-26 +BLOCKS FREE: 215 BLOCKS USED: 65 +``` + +ProDOS opens a directory this module wrote and lists what is in it, its idea +of how many blocks are free agrees with the bit map here, and a directory +ProDOS creates on such a volume reads back through `find` and `catalog` with +every field where this module puts its own. + A model is chosen with options: `memory.AppleIIe(.{})` for the machine, or `memory.Flat(.{ .bus_log = true })` to have it keep a record of what went past on the address bus. The record is what the corpus checks against @@ -639,6 +703,7 @@ machine around it is not. | `src/cpu/add.zig` | binary and decimal addition and subtraction | | `src/disk2.zig` | the Disk II: the card, its drives, and six and two | | `src/dos33.zig` | DOS 3.3 on the disk: making an image, and the files on it | +| `src/prodos.zig` | ProDOS on the volume: directories, index blocks, and the bit map | | `src/screen.zig` | reading the text screen: the modes and the character set | | `src/speaker.zig` | when the cone moved, and turning that into sound | | `src/cassette.zig` | the cassette port, whose output is the speaker over again | diff --git a/src/disk2.zig b/src/disk2.zig index 8a5d829..f8dbdb2 100644 --- a/src/disk2.zig +++ b/src/disk2.zig @@ -69,7 +69,7 @@ pub const Order = enum { /// Which sector of the file belongs at a given place on the track. /// Beneath Apple DOS, table 3.1. - fn logical(self: Order, physical: u8) u8 { + pub fn logical(self: Order, physical: u8) u8 { return switch (self) { .dos => ([_]u8{ 0x0, 0x7, 0xe, 0x6, 0xd, 0x5, 0xc, 0x4, 0xb, 0x3, 0xa, 0x2, 0x9, 0x1, 0x8, 0xf })[physical], .prodos => ([_]u8{ 0x0, 0x8, 0x1, 0x9, 0x2, 0xa, 0x3, 0xb, 0x4, 0xc, 0x5, 0xd, 0x6, 0xe, 0x7, 0xf })[physical], @@ -209,6 +209,26 @@ fn decodeSector(from: *const [343]u8, into: *[bytes_per_sector]u8) DecodeError!v } } +/// Puts an image into a different sector order. +/// +/// A file says nothing about which order it holds, so the same disk turns up +/// both ways: a ProDOS volume on a 5.25 inch disk is `.po` when its blocks lie +/// end to end and `.dsk` when its sectors are interleaved as DOS numbered +/// them. The sectors themselves are the same either way, so this is a +/// shuffle: whatever sits at a physical place on the track under one order is +/// put where the other order keeps it. +pub fn reorder(image: []const u8, into: []u8, from: Order, to: Order) Floppy.LoadError!void { + if (image.len != image_size or into.len != image_size) return error.WrongSize; + for (0..tracks_per_disk) |track| { + const base = track * bytes_per_track; + for (0..sectors_per_track) |physical| { + const source = base + @as(usize, from.logical(@intCast(physical))) * bytes_per_sector; + const target = base + @as(usize, to.logical(@intCast(physical))) * bytes_per_sector; + @memcpy(into[target..][0..bytes_per_sector], image[source..][0..bytes_per_sector]); + } + } +} + /// A floppy, held the way the drive sees it rather than the way the file does. /// /// This is deliberately large — a third of a megabyte — and deliberately not @@ -879,3 +899,24 @@ test "a reset stops the drive but leaves the disk where it is" { try testing.expectEqual(@as(u8, 1), controller.drive(0).half_track); try testing.expectEqual(floppy, controller.drive(0).floppy.?); } + +test "a disk put into the other order comes back when it is put back" { + const original = try testing.allocator.alloc(u8, image_size); + defer testing.allocator.free(original); + for (original, 0..) |*byte, i| byte.* = @truncate(i / bytes_per_sector); + + const other = try testing.allocator.alloc(u8, image_size); + defer testing.allocator.free(other); + try reorder(original, other, .dos, .prodos); + + // The first sector of a track is where it was; the rest have moved. + try testing.expectEqualSlices(u8, original[0..bytes_per_sector], other[0..bytes_per_sector]); + try testing.expect(!std.mem.eql(u8, original, other)); + + const back = try testing.allocator.alloc(u8, image_size); + defer testing.allocator.free(back); + try reorder(other, back, .prodos, .dos); + try testing.expectEqualSlices(u8, original, back); + + try testing.expectError(error.WrongSize, reorder(original, back[0 .. image_size - 1], .dos, .prodos)); +} diff --git a/src/prodos.zig b/src/prodos.zig new file mode 100644 index 0000000..9ff1870 --- /dev/null +++ b/src/prodos.zig @@ -0,0 +1,1402 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! ProDOS as it lies on a volume: the directories that name the files, the bit +//! map that says which blocks are spoken for, and the index blocks that say +//! where a file's blocks are. +//! +//! Where DOS 3.3 knew only a 5.25 inch disk of 560 sectors, ProDOS works in +//! 512 byte blocks and will address 65,535 of them, so the same code here +//! serves a floppy of 280 blocks and a hard disk of thirty-two megabytes. It +//! works on the image itself, blocks laid end to end, which is what a `.po` +//! file, a `.hdv` file and `blockdevice.Volume` all hold; a 5.25 inch image in +//! DOS order has its sectors interleaved differently and wants `disk2.reorder` +//! first. Nothing here allocates: the caller owns the image and every +//! operation works in place. +//! +//! Beneath Apple ProDOS and the ProDOS 8 Technical Reference are where the +//! layout comes from, and all of it below was checked against a real volume. + +const std = @import("std"); +const testing = std.testing; + +pub const block_size = 512; + +/// Blocks 0 and 1 are the loader the drive's firmware reads, and the volume +/// directory follows it. Four blocks of directory is what a volume is made +/// with, and unlike a subdirectory it cannot grow later. +pub const loader_blocks = 2; +pub const volume_directory = 2; +pub const volume_directory_blocks = 4; + +/// The smallest volume worth the name is a 5.25 inch disk, and the block +/// number is sixteen bits, so a volume tops out at thirty-two megabytes. +pub const min_blocks = 280; +pub const max_blocks = 0xffff; + +/// A directory block is a pair of links and then thirteen entries of +/// thirty-nine bytes, which comes to 511 of the 512. +pub const entry_size = 39; +pub const entries_per_block = 13; +const first_entry = 0x04; + +/// Fifteen characters of name, and the pointers an index block holds: 256 of +/// them, low bytes in the first half of the block and high bytes in the +/// second. +pub const name_length = 15; +pub const pointers_per_index = 256; + +/// One bit for every block, so one block of bit map covers four thousand of +/// them and a volume of any size has as many as it needs. +pub const blocks_per_bitmap = block_size * 8; + +/// What the access byte means. A locked file is one that cannot be written, +/// renamed or destroyed, which is what LOCK leaves behind. +pub const access_read = 0x01; +pub const access_write = 0x02; +pub const access_backup = 0x20; +pub const access_rename = 0x40; +pub const access_destroy = 0x80; +pub const access_unlocked = access_destroy | access_rename | access_backup | access_write | access_read; +pub const access_locked = access_backup | access_read; +/// What ProDOS puts on the header that begins a directory, which is the same +/// but for the backup bit: there is nothing in a header for a backup to copy. +pub const access_directory = access_destroy | access_rename | access_write | access_read; + +/// How a file's blocks are found from its key block. +pub const StorageType = enum(u4) { + /// An entry that has never held a file, or whose file is gone. + empty = 0x0, + /// One block, which is the file. + seedling = 0x1, + /// The key block is an index of up to 256 data blocks. + sapling = 0x2, + /// The key block indexes up to 128 index blocks, which is as large as a + /// file gets: sixteen megabytes. + tree = 0x3, + /// A file whose data and resource forks are kept apart, which is a GS/OS + /// arrangement. Nothing here writes one, and one found is left alone. + extended = 0x5, + subdirectory = 0xd, + subdirectory_header = 0xe, + volume_header = 0xf, + _, +}; + +/// What a file holds. The set is open because the byte is whatever was put +/// there, and a volume that holds something else should still be readable. +pub const FileType = enum(u8) { + typeless = 0x00, + text = 0x04, + binary = 0x06, + directory = 0x0f, + appleworks_database = 0x19, + appleworks_word_processor = 0x1a, + appleworks_spreadsheet = 0x1b, + pascal = 0xef, + command = 0xf0, + integer_basic = 0xfa, + integer_variables = 0xfb, + applesoft = 0xfc, + applesoft_variables = 0xfd, + relocatable = 0xfe, + system = 0xff, + _, + + /// The three letters a catalog shows, or the type in hexadecimal for one + /// of the many that never got a name. + pub fn abbreviation(self: FileType, buffer: *[3]u8) []const u8 { + const known = switch (self) { + .typeless => " ", + .text => "TXT", + .binary => "BIN", + .directory => "DIR", + .appleworks_database => "ADB", + .appleworks_word_processor => "AWP", + .appleworks_spreadsheet => "ASP", + .pascal => "PAS", + .command => "CMD", + .integer_basic => "INT", + .integer_variables => "IVR", + .applesoft => "BAS", + .applesoft_variables => "VAR", + .relocatable => "REL", + .system => "SYS", + _ => { + _ = std.fmt.bufPrint(buffer, "${x:0>2}", .{@intFromEnum(self)}) catch unreachable; + return buffer; + }, + }; + @memcpy(buffer, known); + return buffer; + } +}; + +/// When something happened, in the two words ProDOS keeps it in: the year +/// counted from 1900 with anything under forty meaning the century after, +/// then the month and the day, and the hour and the minute in a word of their +/// own. +pub const DateTime = struct { + date: u16 = 0, + time: u16 = 0, + + /// Nothing, which is what a volume made by something with no clock has, + /// and what a catalog shows as no date at all. + pub const none: DateTime = .{}; + + pub fn from(in_year: u16, in_month: u4, in_day: u5, in_hour: u5, in_minute: u6) DateTime { + const counted: u16 = if (in_year >= 2000) in_year - 2000 else in_year - 1900; + return .{ + .date = counted << 9 | @as(u16, in_month) << 5 | in_day, + .time = @as(u16, in_hour) << 8 | in_minute, + }; + } + + /// The year as it was meant: under forty is this century, the rest the + /// last one. ProDOS was written before that mattered and the rule came + /// afterwards. + pub fn year(self: DateTime) u16 { + const counted = self.date >> 9; + return if (counted < 40) 2000 + counted else 1900 + counted; + } + pub fn month(self: DateTime) u4 { + return @truncate(self.date >> 5); + } + pub fn day(self: DateTime) u5 { + return @truncate(self.date); + } + pub fn hour(self: DateTime) u5 { + return @truncate(self.time >> 8); + } + pub fn minute(self: DateTime) u6 { + return @truncate(self.time); + } +}; + +/// Where things are in a directory entry, and in the header that begins a +/// directory, which is an entry of the same size and shape. +const field = struct { + const storage = 0x00; + const name = 0x01; + const kind = 0x10; + const key = 0x11; + const blocks_used = 0x13; + const eof = 0x15; + const created = 0x18; + const version = 0x1c; + const min_version = 0x1d; + const access = 0x1e; + const aux = 0x1f; + const modified = 0x21; + const header = 0x25; + + /// The header's own fields, which take the space an entry uses for the + /// file's whereabouts. + const entry_length = 0x1f; + const entries = 0x20; + const file_count = 0x21; + /// A volume header ends with where the bit map is and how big the volume + /// is; a subdirectory header with which entry of which directory names it. + const bitmap = 0x23; + const total_blocks = 0x25; + const parent = 0x23; + const parent_entry = 0x25; + const parent_entry_length = 0x26; + /// ProDOS writes this into a subdirectory header where a file entry keeps + /// its type, and looks for it when it opens one. + const subdirectory_mark = 0x10; + const subdirectory_mark_value = 0x75; +}; + +/// Where a directory entry sits, so that it can be written back. +pub const Slot = struct { + block: u16, + index: u8, +}; + +/// A file, as its directory entry describes it. +pub const Entry = struct { + slot: Slot, + storage: StorageType, + kind: FileType, + /// The first block of the file: the file itself for a seedling, an index + /// for anything longer. + key: u16, + blocks_used: u16, + /// How many bytes of it mean anything, which ProDOS keeps exactly, unlike + /// DOS 3.3 and its whole sectors. + eof: u32, + aux: u16, + access: u8, + created: DateTime, + modified: DateTime, + stored: [name_length]u8, + length: u8, + + pub fn name(self: *const Entry) []const u8 { + return self.stored[0..self.length]; + } + + /// Whether it cannot be written, renamed or destroyed, which is what LOCK + /// leaves behind. + pub fn locked(self: *const Entry) bool { + return self.access & access_write == 0; + } + + pub fn isDirectory(self: *const Entry) bool { + return self.storage == .subdirectory; + } + + fn from(bytes: *const [entry_size]u8, slot: Slot) Entry { + var self: Entry = .{ + .slot = slot, + .storage = @enumFromInt(@as(u4, @truncate(bytes[field.storage] >> 4))), + .kind = @enumFromInt(bytes[field.kind]), + .key = std.mem.readInt(u16, bytes[field.key..][0..2], .little), + .blocks_used = std.mem.readInt(u16, bytes[field.blocks_used..][0..2], .little), + .eof = std.mem.readInt(u24, bytes[field.eof..][0..3], .little), + .aux = std.mem.readInt(u16, bytes[field.aux..][0..2], .little), + .access = bytes[field.access], + .created = .{ + .date = std.mem.readInt(u16, bytes[field.created..][0..2], .little), + .time = std.mem.readInt(u16, bytes[field.created + 2 ..][0..2], .little), + }, + .modified = .{ + .date = std.mem.readInt(u16, bytes[field.modified..][0..2], .little), + .time = std.mem.readInt(u16, bytes[field.modified + 2 ..][0..2], .little), + }, + .stored = undefined, + .length = @truncate(bytes[field.storage] & 0x0f), + }; + @memcpy(&self.stored, bytes[field.name..][0..name_length]); + return self; + } +}; + +/// What a file is made when it is written. +pub const Attributes = struct { + kind: FileType, + /// What the type calls for: where a binary file loads, how long a text + /// file's records are, and nothing at all for the rest. + aux: u16 = 0, + access: u8 = access_unlocked, +}; + +/// A ProDOS volume, held as the image itself and nothing more. +pub const Volume = struct { + image: []u8, + /// Whether anything has been written since the volume was opened or last + /// saved. `format` leaves it set; writing through `blockAt` is not + /// noticed. + dirty: bool = false, + /// What to stamp on a file as it is written. There is no clock in here to + /// ask, so a caller who wants dates on its files says what they are. + stamp: DateTime = .none, + + pub const SizeError = error{ WrongSize, TooSmall, TooLarge }; + pub const OpenError = SizeError || error{NotProdos}; + pub const NameError = error{BadName}; + pub const PathError = NameError || error{ NotFound, NotADirectory }; + pub const WriteError = PathError || error{ VolumeFull, DirectoryFull, Locked, TooBig, IsADirectory, Exists }; + pub const DeleteError = PathError || error{ Locked, NotEmpty }; + pub const ReadError = PathError || error{ IsADirectory, Damaged } || std.Io.Writer.Error; + + /// Lays out an empty volume: the loader blocks, four blocks of volume + /// directory, and a bit map with everything else free. + /// + /// The loader is left as it is found rather than zeroed, so that a caller + /// who has copied one in keeps it and ends up with a volume that boots. + pub fn format(image: []u8, volume_name: []const u8) (SizeError || NameError)!Volume { + if (image.len % block_size != 0) return error.WrongSize; + const count = image.len / block_size; + if (count < min_blocks) return error.TooSmall; + if (count > max_blocks) return error.TooLarge; + + var stored: [name_length]u8 = undefined; + const length = try store(volume_name, &stored); + + var self: Volume = .{ .image = image, .dirty = true }; + const total: u16 = @intCast(count); + const maps = (total + blocks_per_bitmap - 1) / blocks_per_bitmap; + const bitmap_at = volume_directory + volume_directory_blocks; + const reserved = bitmap_at + maps; + + @memset(image[loader_blocks * block_size ..], 0); + + // The directory blocks, chained one to the next. + for (0..volume_directory_blocks) |i| { + const at: u16 = @intCast(volume_directory + i); + const bytes = self.blockAt(at); + const previous: u16 = if (i == 0) 0 else at - 1; + const next: u16 = if (i + 1 == volume_directory_blocks) 0 else at + 1; + std.mem.writeInt(u16, bytes[0..2], previous, .little); + std.mem.writeInt(u16, bytes[2..4], next, .little); + } + + const header = self.headerAt(volume_directory); + header[field.storage] = @as(u8, @intFromEnum(StorageType.volume_header)) << 4 | length; + @memcpy(header[field.name..][0..name_length], &stored); + header[field.access] = access_directory; + header[field.entry_length] = entry_size; + header[field.entries] = entries_per_block; + std.mem.writeInt(u16, header[field.file_count..][0..2], 0, .little); + std.mem.writeInt(u16, header[field.bitmap..][0..2], bitmap_at, .little); + std.mem.writeInt(u16, header[field.total_blocks..][0..2], total, .little); + + // Everything is free but the loader, the directory and the map itself. + for (0..count) |block| self.setFree(@intCast(block), block >= reserved); + return self; + } + + /// Takes an image that already holds a volume, checking that the volume + /// directory says what a volume directory says. + pub fn open(image: []u8) OpenError!Volume { + if (image.len % block_size != 0) return error.WrongSize; + const count = image.len / block_size; + if (count < min_blocks) return error.TooSmall; + if (count > max_blocks) return error.TooLarge; + + const self: Volume = .{ .image = image }; + const header = self.headerAt(volume_directory); + if (header[field.storage] >> 4 != @intFromEnum(StorageType.volume_header)) return error.NotProdos; + if (header[field.storage] & 0x0f == 0) return error.NotProdos; + if (header[field.entry_length] != entry_size) return error.NotProdos; + if (header[field.entries] != entries_per_block) return error.NotProdos; + const total = std.mem.readInt(u16, header[field.total_blocks..][0..2], .little); + if (total == 0 or total > count) return error.NotProdos; + const bitmap_at = std.mem.readInt(u16, header[field.bitmap..][0..2], .little); + if (bitmap_at == 0 or bitmap_at >= total) return error.NotProdos; + return self; + } + + /// Reads a whole image off the file system and opens it. The caller owns + /// `image` and frees it. + /// + /// var volume = try Volume.openFile(.cwd(), io, "work.po", allocator); + /// defer allocator.free(volume.image); + pub fn openFile( + dir: std.Io.Dir, + io: std.Io, + sub_path: []const u8, + gpa: std.mem.Allocator, + ) !Volume { + const image = try dir.readFileAlloc(io, sub_path, gpa, .limited(max_blocks * block_size)); + errdefer gpa.free(image); + return open(image); + } + + /// Writes the image back over a file, and marks the volume as no longer + /// needing it. + pub fn saveFile(self: *Volume, 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's name, which is the first part of every path on it. + pub fn name(self: *const Volume, buffer: *[name_length]u8) []const u8 { + const header = self.headerAt(volume_directory); + const length = header[field.storage] & 0x0f; + @memcpy(buffer, header[field.name..][0..name_length]); + return buffer[0..length]; + } + + /// How many blocks the volume says it has, which is what it was made with + /// rather than how long the image happens to be. + pub fn blocks(self: *const Volume) u16 { + return std.mem.readInt(u16, self.headerAt(volume_directory)[field.total_blocks..][0..2], .little); + } + + pub fn freeBlocks(self: *const Volume) u16 { + var count: u16 = 0; + for (0..self.blocks()) |block| { + if (self.isFree(@intCast(block))) count += 1; + } + return count; + } + + /// Everything in a directory, in the order the directory holds it. An + /// empty path is the volume directory itself. + pub fn catalog(self: *const Volume, path: []const u8) PathError!Catalog { + return .{ .walk = try self.walkOf(path) }; + } + + /// The entry for a path, or nothing if the volume has no such file. A path + /// may begin with the volume's own name, as ProDOS writes them, or with + /// the first directory below it. + pub fn find(self: *const Volume, path: []const u8) ?Entry { + const slot = self.resolve(path) catch return null; + return Entry.from(self.entryAt(slot), slot); + } + + /// Writes a file's bytes out, following its index blocks, and stops at the + /// length the entry gives, which ProDOS keeps to the byte. + /// + /// A block pointer of zero is a hole, left by a file written past its own + /// end, and reads back as a block of zeroes. + pub fn read(self: *const Volume, path: []const u8, writer: *std.Io.Writer) ReadError!void { + const slot = try self.resolve(path); + const entry = Entry.from(self.entryAt(slot), slot); + if (entry.isDirectory()) return error.IsADirectory; + + const hole: [block_size]u8 = @splat(0); + var left = entry.eof; + var index: u32 = 0; + while (left > 0) : (index += 1) { + const take: u32 = @min(left, block_size); + const where = try self.dataBlock(entry, index); + if (where == 0) { + try writer.writeAll(hole[0..take]); + } else { + if (where >= self.blocks()) return error.Damaged; + try writer.writeAll(self.blockAt(where)[0..take]); + } + left -= take; + } + } + + /// Puts a file on the volume, over one of the same name if there is one. + pub fn write( + self: *Volume, + path: []const u8, + attributes: Attributes, + data: []const u8, + ) WriteError!void { + return self.writeParts(path, attributes, &.{data}); + } + + /// The same, from several pieces laid end to end, so that a header can go + /// in front of a body without joining the two first. + pub fn writeParts( + self: *Volume, + path: []const u8, + attributes: Attributes, + parts: []const []const u8, + ) WriteError!void { + var bytes: usize = 0; + for (parts) |part| bytes += part.len; + if (bytes > 0xffffff) return error.TooBig; + + const data_blocks = (bytes + block_size - 1) / block_size; + const storage: StorageType = if (data_blocks <= 1) + .seedling + else if (data_blocks <= pointers_per_index) + .sapling + else + .tree; + const indexes: usize = switch (storage) { + .seedling => 0, + .sapling => 1, + else => 1 + (data_blocks + pointers_per_index - 1) / pointers_per_index, + }; + if (storage == .tree and data_blocks > pointers_per_index * 128) return error.TooBig; + const wanted = @max(1, data_blocks) + indexes; + + const where = try self.place(path); + var room: usize = self.freeBlocks(); + if (where.existing) |slot| { + const entry = self.entryAt(slot); + if (entry[field.access] & access_write == 0) return error.Locked; + if (entry[field.storage] >> 4 == @intFromEnum(StorageType.subdirectory)) return error.IsADirectory; + room += std.mem.readInt(u16, entry[field.blocks_used..][0..2], .little); + } + if (wanted > room) return error.VolumeFull; + + // Nothing is touched until everything that could refuse the write has + // had its say. + const slot = if (where.existing) |existing| existing else try self.emptySlot(where.directory); + if (where.existing != null) self.release(slot); + + const key = self.allocate() orelse return error.VolumeFull; + var written: usize = 0; + var at: usize = 0; + switch (storage) { + .seedling => { + const target = self.blockAt(key); + @memset(target, 0); + gather(parts, 0, target); + }, + .sapling => { + @memset(self.blockAt(key), 0); + while (written < data_blocks) : (written += 1) { + const put = self.allocate() orelse return error.VolumeFull; + self.fill(put, parts, at); + at += block_size; + self.setPointer(key, written, put); + } + }, + else => { + @memset(self.blockAt(key), 0); + var index_block: u16 = 0; + while (written < data_blocks) { + const list = self.allocate() orelse return error.VolumeFull; + @memset(self.blockAt(list), 0); + self.setPointer(key, index_block, list); + index_block += 1; + var within: usize = 0; + while (within < pointers_per_index and written < data_blocks) : (within += 1) { + const put = self.allocate() orelse return error.VolumeFull; + self.fill(put, parts, at); + at += block_size; + self.setPointer(list, within, put); + written += 1; + } + } + }, + } + + const entry = self.entryAt(slot); + const was_empty = entry[field.storage] >> 4 == @intFromEnum(StorageType.empty); + @memset(entry, 0); + entry[field.storage] = @as(u8, @intFromEnum(storage)) << 4 | where.length; + @memcpy(entry[field.name..][0..name_length], &where.stored); + entry[field.kind] = @intFromEnum(attributes.kind); + std.mem.writeInt(u16, entry[field.key..][0..2], key, .little); + std.mem.writeInt(u16, entry[field.blocks_used..][0..2], @intCast(wanted), .little); + std.mem.writeInt(u24, entry[field.eof..][0..3], @intCast(bytes), .little); + self.stampAt(entry, field.created); + self.stampAt(entry, field.modified); + entry[field.access] = attributes.access; + std.mem.writeInt(u16, entry[field.aux..][0..2], attributes.aux, .little); + std.mem.writeInt(u16, entry[field.header..][0..2], where.directory, .little); + if (was_empty) self.countFile(where.directory, 1); + self.dirty = true; + } + + /// Makes a directory, which is a file of directory blocks whose first + /// entry says which entry of which directory named it. + pub fn makeDirectory(self: *Volume, path: []const u8) WriteError!void { + const where = try self.place(path); + if (where.existing != null) return error.Exists; + if (self.freeBlocks() < 1) return error.VolumeFull; + const slot = try self.emptySlot(where.directory); + + const key = self.allocate() orelse return error.VolumeFull; + const bytes = self.blockAt(key); + @memset(bytes, 0); + + const header = self.headerAt(key); + header[field.storage] = @as(u8, @intFromEnum(StorageType.subdirectory_header)) << 4 | where.length; + @memcpy(header[field.name..][0..name_length], &where.stored); + header[field.subdirectory_mark] = field.subdirectory_mark_value; + header[field.access] = access_directory; + header[field.entry_length] = entry_size; + header[field.entries] = entries_per_block; + std.mem.writeInt(u16, header[field.file_count..][0..2], 0, .little); + std.mem.writeInt(u16, header[field.parent..][0..2], slot.block, .little); + header[field.parent_entry] = slot.index + 1; + header[field.parent_entry_length] = entry_size; + + const entry = self.entryAt(slot); + const was_empty = entry[field.storage] >> 4 == @intFromEnum(StorageType.empty); + @memset(entry, 0); + entry[field.storage] = @as(u8, @intFromEnum(StorageType.subdirectory)) << 4 | where.length; + @memcpy(entry[field.name..][0..name_length], &where.stored); + entry[field.kind] = @intFromEnum(FileType.directory); + std.mem.writeInt(u16, entry[field.key..][0..2], key, .little); + std.mem.writeInt(u16, entry[field.blocks_used..][0..2], 1, .little); + std.mem.writeInt(u24, entry[field.eof..][0..3], block_size, .little); + self.stampAt(entry, field.created); + self.stampAt(entry, field.modified); + entry[field.access] = access_unlocked; + std.mem.writeInt(u16, entry[field.header..][0..2], where.directory, .little); + if (was_empty) self.countFile(where.directory, 1); + self.dirty = true; + } + + /// Takes a file off the volume, giving its blocks back. A directory has to + /// be empty first, as ProDOS insists. + pub fn delete(self: *Volume, path: []const u8) DeleteError!void { + const slot = try self.resolve(path); + const entry = self.entryAt(slot); + if (entry[field.access] & access_destroy == 0) return error.Locked; + if (entry[field.storage] >> 4 == @intFromEnum(StorageType.subdirectory)) { + const key = std.mem.readInt(u16, entry[field.key..][0..2], .little); + const header = self.headerAt(key); + if (std.mem.readInt(u16, header[field.file_count..][0..2], .little) != 0) return error.NotEmpty; + } + const directory = std.mem.readInt(u16, entry[field.header..][0..2], .little); + self.release(slot); + @memset(self.entryAt(slot), 0); + self.countFile(directory, -1); + self.dirty = true; + } + + /// Puts the lock on a file, or takes it off, which is what LOCK and UNLOCK + /// do to the access byte. + pub fn setLocked(self: *Volume, path: []const u8, locked: bool) PathError!void { + const slot = try self.resolve(path); + self.entryAt(slot)[field.access] = if (locked) access_locked else access_unlocked; + self.dirty = true; + } + + /// One block of the image. + /// + /// What comes back can be written to even from a volume 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. + pub fn blockAt(self: *const Volume, block: u16) *[block_size]u8 { + return self.image[@as(usize, block) * block_size ..][0..block_size]; + } + + /// The header that begins a directory, which is the first entry of its + /// first block. + fn headerAt(self: *const Volume, block: u16) *[entry_size]u8 { + return self.blockAt(block)[first_entry..][0..entry_size]; + } + + fn entryAt(self: *const Volume, slot: Slot) *[entry_size]u8 { + const bytes = self.blockAt(slot.block); + return bytes[first_entry + @as(usize, slot.index) * entry_size ..][0..entry_size]; + } + + /// The bit map, which is as many blocks as the volume needs: a bit for + /// every block, the first block being the top bit of the first byte, and a + /// bit set meaning free. + fn bitmapBit(self: *const Volume, block: u16) struct { *u8, u8 } { + const at = std.mem.readInt(u16, self.headerAt(volume_directory)[field.bitmap..][0..2], .little); + const byte = @as(usize, block) / 8; + const bytes = self.blockAt(@intCast(at + byte / block_size)); + return .{ &bytes[byte % block_size], @as(u8, 0x80) >> @intCast(block % 8) }; + } + + fn isFree(self: *const Volume, block: u16) bool { + const byte, const bit = self.bitmapBit(block); + return byte.* & bit != 0; + } + + fn setFree(self: *Volume, block: u16, free: bool) void { + const byte, const bit = self.bitmapBit(block); + if (free) byte.* |= bit else byte.* &= ~bit; + } + + /// The lowest free block, which is where ProDOS puts things: it fills a + /// volume from the front and leaves no gaps behind a deleted file. + fn allocate(self: *Volume) ?u16 { + for (0..self.blocks()) |block| { + if (!self.isFree(@intCast(block))) continue; + self.setFree(@intCast(block), false); + return @intCast(block); + } + return null; + } + + /// Which block holds a file's nth block, or zero for a hole. + fn dataBlock(self: *const Volume, entry: Entry, index: u32) error{Damaged}!u16 { + return switch (entry.storage) { + .seedling => if (index == 0) entry.key else 0, + .sapling => if (index < pointers_per_index) self.pointer(entry.key, @intCast(index)) else 0, + .tree => tree: { + const which = index / pointers_per_index; + if (which >= pointers_per_index) break :tree 0; + const list = self.pointer(entry.key, @intCast(which)); + if (list == 0) break :tree 0; + if (list >= self.blocks()) return error.Damaged; + break :tree self.pointer(list, @intCast(index % pointers_per_index)); + }, + else => error.Damaged, + }; + } + + /// An index block keeps its pointers split in half: every low byte in the + /// first half of the block, every high byte in the second. + fn pointer(self: *const Volume, index: u16, which: u8) u16 { + const bytes = self.blockAt(index); + return @as(u16, bytes[pointers_per_index + @as(usize, which)]) << 8 | bytes[which]; + } + + fn setPointer(self: *Volume, index: u16, which: usize, block: u16) void { + const bytes = self.blockAt(index); + bytes[which] = @truncate(block); + bytes[pointers_per_index + which] = @intCast(block >> 8); + } + + fn fill(self: *Volume, block: u16, parts: []const []const u8, from: usize) void { + const target = self.blockAt(block); + @memset(target, 0); + gather(parts, from, target); + } + + fn stampAt(self: *const Volume, entry: *[entry_size]u8, at: usize) void { + std.mem.writeInt(u16, entry[at..][0..2], self.stamp.date, .little); + std.mem.writeInt(u16, entry[at + 2 ..][0..2], self.stamp.time, .little); + } + + /// Gives back every block a file holds, index blocks and all, leaving the + /// entry to the caller. + fn release(self: *Volume, slot: Slot) void { + const entry = Entry.from(self.entryAt(slot), slot); + if (entry.key == 0 or entry.key >= self.blocks()) return; + switch (entry.storage) { + .seedling => self.setFree(entry.key, true), + .sapling => { + for (0..pointers_per_index) |i| { + const block = self.pointer(entry.key, @intCast(i)); + if (block != 0 and block < self.blocks()) self.setFree(block, true); + } + self.setFree(entry.key, true); + }, + .tree => { + for (0..pointers_per_index) |i| { + const list = self.pointer(entry.key, @intCast(i)); + if (list == 0 or list >= self.blocks()) continue; + for (0..pointers_per_index) |j| { + const block = self.pointer(list, @intCast(j)); + if (block != 0 and block < self.blocks()) self.setFree(block, true); + } + self.setFree(list, true); + } + self.setFree(entry.key, true); + }, + .subdirectory => { + var at = entry.key; + for (0..max_blocks) |_| { + if (at == 0 or at >= self.blocks()) break; + const next = std.mem.readInt(u16, self.blockAt(at)[2..4], .little); + self.setFree(at, true); + at = next; + } + }, + else => {}, + } + } + + /// Counts a file into a directory, or out of it, which the header keeps + /// so that a catalog knows when to stop. + fn countFile(self: *Volume, directory: u16, by: i2) void { + const header = self.headerAt(directory); + const count = std.mem.readInt(u16, header[field.file_count..][0..2], .little); + const now: u16 = if (by < 0) count -| 1 else count +| 1; + std.mem.writeInt(u16, header[field.file_count..][0..2], now, .little); + } + + /// Where a name is to go: which directory, what it will be called, and + /// whether something of that name is there already. + const Place = struct { + directory: u16, + stored: [name_length]u8, + length: u8, + existing: ?Slot, + }; + + fn place(self: *const Volume, path: []const u8) PathError!Place { + const parts = split(path) orelse return error.BadName; + var stored: [name_length]u8 = undefined; + const length = try store(parts.name, &stored); + const directory = try self.directoryOf(parts.parent); + return .{ + .directory = directory, + .stored = stored, + .length = length, + .existing = self.slotIn(directory, &stored, length), + }; + } + + /// The first entry in a directory that has never held a file or whose file + /// is gone, growing the directory if it is a subdirectory and full. A + /// volume directory cannot grow: four blocks is what it was made with. + fn emptySlot(self: *Volume, directory: u16) error{DirectoryFull}!Slot { + var walk = self.walkIn(directory); + while (walk.next()) |slot| { + if (self.entryAt(slot)[field.storage] >> 4 == @intFromEnum(StorageType.empty)) return slot; + } + if (directory == volume_directory) return error.DirectoryFull; + + const last = walk.block; + const grown = self.allocate() orelse return error.DirectoryFull; + const bytes = self.blockAt(grown); + @memset(bytes, 0); + std.mem.writeInt(u16, bytes[0..2], last, .little); + std.mem.writeInt(u16, self.blockAt(last)[2..4], grown, .little); + + // The directory's own entry counts the blocks it takes up, and there + // is one more of them now. + const header = self.headerAt(directory); + const parent = std.mem.readInt(u16, header[field.parent..][0..2], .little); + const number = header[field.parent_entry]; + if (parent != 0 and number > 0) { + const entry = self.entryAt(.{ .block = parent, .index = number - 1 }); + const before = std.mem.readInt(u16, entry[field.blocks_used..][0..2], .little); + std.mem.writeInt(u16, entry[field.blocks_used..][0..2], before + 1, .little); + const eof = std.mem.readInt(u24, entry[field.eof..][0..3], .little); + std.mem.writeInt(u24, entry[field.eof..][0..3], eof + block_size, .little); + } + return .{ .block = grown, .index = 0 }; + } + + fn slotIn(self: *const Volume, directory: u16, wanted: *const [name_length]u8, length: u8) ?Slot { + var walk = self.walkIn(directory); + while (walk.next()) |slot| { + const entry = self.entryAt(slot); + if (entry[field.storage] >> 4 == @intFromEnum(StorageType.empty)) continue; + if (entry[field.storage] & 0x0f != length) continue; + if (std.mem.eql(u8, entry[field.name..][0..length], wanted[0..length])) return slot; + } + return null; + } + + /// Follows a path to the entry it names. + fn resolve(self: *const Volume, path: []const u8) PathError!Slot { + const parts = split(path) orelse return error.BadName; + var stored: [name_length]u8 = undefined; + const length = try store(parts.name, &stored); + const directory = try self.directoryOf(parts.parent); + return self.slotIn(directory, &stored, length) orelse error.NotFound; + } + + /// Follows a path to the directory it names, the volume directory being + /// what an empty path means. + fn directoryOf(self: *const Volume, path: []const u8) PathError!u16 { + var parts = components(path); + var at: u16 = volume_directory; + var first = true; + while (parts.next()) |part| { + var stored: [name_length]u8 = undefined; + const length = try store(part, &stored); + + // A path may name the volume it is on, which is how ProDOS writes + // one, and that first part is the directory already reached. + if (first) { + first = false; + const header = self.headerAt(volume_directory); + if (header[field.storage] & 0x0f == length and + std.mem.eql(u8, header[field.name..][0..length], stored[0..length])) + continue; + } + + const slot = self.slotIn(at, &stored, length) orelse return error.NotFound; + const entry = self.entryAt(slot); + if (entry[field.storage] >> 4 != @intFromEnum(StorageType.subdirectory)) return error.NotADirectory; + at = std.mem.readInt(u16, entry[field.key..][0..2], .little); + } + return at; + } + + fn walkOf(self: *const Volume, path: []const u8) PathError!Walk { + return self.walkIn(try self.directoryOf(path)); + } + + fn walkIn(self: *const Volume, directory: u16) Walk { + return .{ + .volume = self.*, + .block = directory, + // The first entry of the first block is the directory's own + // header, not a file. + .index = 1, + }; + } +}; + +/// Every entry of a directory, used or not, which is what finding a file and +/// finding somewhere to put one both walk. +const Walk = struct { + volume: Volume, + block: u16, + index: u8, + visited: u16 = 0, + + fn next(self: *Walk) ?Slot { + while (self.block != 0) { + if (self.block >= self.volume.blocks()) return null; + if (self.index >= entries_per_block) { + const following = std.mem.readInt(u16, self.volume.blockAt(self.block)[2..4], .little); + if (following == 0) return null; + self.block = following; + self.index = 0; + // A chain that bites its own tail would otherwise go round for + // ever, and no directory is longer than the volume. + self.visited += 1; + if (self.visited >= self.volume.blocks()) return null; + continue; + } + const slot: Slot = .{ .block = self.block, .index = self.index }; + self.index += 1; + return slot; + } + return null; + } +}; + +/// The files in a directory, skipping the entries that hold none. +pub const Catalog = struct { + walk: Walk, + + pub fn next(self: *Catalog) ?Entry { + while (self.walk.next()) |slot| { + const bytes = self.walk.volume.entryAt(slot); + if (bytes[field.storage] >> 4 == @intFromEnum(StorageType.empty)) continue; + return Entry.from(bytes, slot); + } + return null; + } +}; + +/// The parts of a path, which ProDOS separates with slashes and may begin with +/// the volume's own name. +const Components = struct { + path: []const u8, + at: usize = 0, + + fn next(self: *Components) ?[]const u8 { + while (self.at < self.path.len and self.path[self.at] == '/') self.at += 1; + if (self.at >= self.path.len) return null; + const start = self.at; + while (self.at < self.path.len and self.path[self.at] != '/') self.at += 1; + return self.path[start..self.at]; + } +}; + +fn components(path: []const u8) Components { + return .{ .path = path }; +} + +/// A path split into the directory to look in and the name to look for. +const Split = struct { + parent: []const u8, + name: []const u8, +}; + +fn split(path: []const u8) ?Split { + var parts = components(path); + var name: ?[]const u8 = null; + var at: usize = 0; + while (parts.next()) |part| { + name = part; + at = @intFromPtr(part.ptr) - @intFromPtr(path.ptr); + } + return .{ .parent = path[0..at], .name = name orelse return null }; +} + +/// Puts a name into the fifteen bytes an entry holds it in. +/// +/// ProDOS is strict about names in a way DOS 3.3 was not: a letter first, then +/// letters, digits and full stops, and no more than fifteen of them. They are +/// held in upper case and without the high bit, and compared without regard to +/// case, so that is what a name given here is turned into. +fn store(name: []const u8, into: *[name_length]u8) Volume.NameError!u8 { + if (name.len == 0 or name.len > name_length) return error.BadName; + if (!std.ascii.isAlphabetic(name[0])) return error.BadName; + @memset(into, 0); + for (name, 0..) |character, i| { + if (!std.ascii.isAlphanumeric(character) and character != '.') return error.BadName; + into[i] = std.ascii.toUpper(character); + } + return @intCast(name.len); +} + +/// Copies one block'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: *[block_size]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, block_size - put); + @memcpy(into[put..][0..take], part[at..][0..take]); + put += take; + at = 0; + if (put == block_size) return; + } +} + +/// A volume to work on. A 5.25 inch disk of 280 blocks is the smallest there +/// is, and more than a test wants on its stack. +fn blank(allocator: std.mem.Allocator, count: usize) !Volume { + const image = try allocator.alloc(u8, count * block_size); + @memset(image, 0); + return Volume.format(image, "TEST.VOLUME"); +} + +test "a formatted volume has the shape ProDOS gives it" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + var buffer: [name_length]u8 = undefined; + try testing.expectEqualStrings("TEST.VOLUME", volume.name(&buffer)); + try testing.expectEqual(@as(u16, 280), volume.blocks()); + try testing.expect(volume.dirty); + + // The header says how a directory is shaped and where the map is: two + // loader blocks, four of directory, one of map, and the rest free. + const header = volume.headerAt(volume_directory); + try testing.expectEqual(@as(u8, entry_size), header[field.entry_length]); + try testing.expectEqual(@as(u8, entries_per_block), header[field.entries]); + try testing.expectEqual(@as(u16, 6), std.mem.readInt(u16, header[field.bitmap..][0..2], .little)); + try testing.expectEqual(@as(u16, 280 - 7), volume.freeBlocks()); + try testing.expect(!volume.isFree(0)); + try testing.expect(!volume.isFree(6)); + try testing.expect(volume.isFree(7)); + try testing.expect(volume.isFree(279)); + + // Four directory blocks, chained, and nothing in them. + var files = try volume.catalog(""); + try testing.expectEqual(@as(?Entry, null), files.next()); + try testing.expectEqual(@as(u16, 3), std.mem.readInt(u16, volume.blockAt(2)[2..4], .little)); + try testing.expectEqual(@as(u16, 0), std.mem.readInt(u16, volume.blockAt(5)[2..4], .little)); + + _ = try Volume.open(volume.image); +} + +test "a file comes back the way it went on, to the byte" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + // Under a block, so the file is a seedling and the key block is the file. + var data: [300]u8 = undefined; + for (&data, 0..) |*byte, i| byte.* = @truncate(i * 7); + try volume.write("SMALL", .{ .kind = .binary, .aux = 0x2000 }, &data); + + const entry = volume.find("SMALL") orelse return error.NotFound; + try testing.expectEqualStrings("SMALL", entry.name()); + try testing.expectEqual(StorageType.seedling, entry.storage); + try testing.expectEqual(FileType.binary, entry.kind); + try testing.expectEqual(@as(u16, 0x2000), entry.aux); + try testing.expectEqual(@as(u32, 300), entry.eof); + try testing.expectEqual(@as(u16, 1), entry.blocks_used); + try testing.expect(!entry.locked()); + + // ProDOS keeps the length to the byte, so what comes back is the file + // rather than the blocks it sits in. + var buffer: [block_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + try volume.read("SMALL", &writer); + try testing.expectEqualSlices(u8, &data, writer.buffered()); +} + +test "a file over a block gets an index, and one over that a tree" { + var volume = try blank(testing.allocator, 2000); + defer testing.allocator.free(volume.image); + + const sapling = try testing.allocator.alloc(u8, 5000); + defer testing.allocator.free(sapling); + for (sapling, 0..) |*byte, i| byte.* = @truncate(i / 7); + try volume.write("SAPLING", .{ .kind = .text }, sapling); + + const one = volume.find("SAPLING") orelse return error.NotFound; + try testing.expectEqual(StorageType.sapling, one.storage); + // Ten blocks of data and the index that says where they are. + try testing.expectEqual(@as(u16, 11), one.blocks_used); + + const back = try testing.allocator.alloc(u8, sapling.len); + defer testing.allocator.free(back); + var writer: std.Io.Writer = .fixed(back); + try volume.read("SAPLING", &writer); + try testing.expectEqualSlices(u8, sapling, writer.buffered()); + + // One block more than an index holds, so the key block becomes an index + // of indexes. + const tree = try testing.allocator.alloc(u8, (pointers_per_index + 1) * block_size); + defer testing.allocator.free(tree); + for (tree, 0..) |*byte, i| byte.* = @truncate(i / block_size); + try volume.write("TREE", .{ .kind = .text }, tree); + + const two = volume.find("TREE") orelse return error.NotFound; + try testing.expectEqual(StorageType.tree, two.storage); + try testing.expectEqual(@as(u16, pointers_per_index + 1 + 3), two.blocks_used); + + const grown = try testing.allocator.alloc(u8, tree.len); + defer testing.allocator.free(grown); + var into: std.Io.Writer = .fixed(grown); + try volume.read("TREE", &into); + try testing.expectEqualSlices(u8, tree, into.buffered()); +} + +test "a file in pieces is laid end to end" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + const body: [700]u8 = @splat(0xa9); + const header = [_]u8{ 1, 2, 3, 4 }; + try volume.writeParts("PIECES", .{ .kind = .binary }, &.{ &header, &body }); + + var buffer: [2 * block_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + try volume.read("PIECES", &writer); + const read = writer.buffered(); + try testing.expectEqual(@as(usize, 704), read.len); + try testing.expectEqualSlices(u8, &header, read[0..4]); + try testing.expectEqualSlices(u8, &body, read[4..]); +} + +test "directories hold files, and paths find them" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + try volume.makeDirectory("WORK"); + try volume.makeDirectory("WORK/DEEPER"); + try volume.write("WORK/NOTES", .{ .kind = .text }, "in a directory"); + try volume.write("WORK/DEEPER/UNDER", .{ .kind = .text }, "further down"); + try volume.write("TOP", .{ .kind = .text }, "at the top"); + + // A path may name the volume it is on, as ProDOS writes them. + try testing.expect(volume.find("/TEST.VOLUME/WORK/NOTES") != null); + try testing.expect(volume.find("WORK/NOTES") != null); + try testing.expect(volume.find("NOTES") == null); + + const directory = volume.find("WORK") orelse return error.NotFound; + try testing.expect(directory.isDirectory()); + try testing.expectEqual(FileType.directory, directory.kind); + + // The volume directory holds two things, and the one below it two more. + // A name borrows from the entry it came off, so it is copied out here + // rather than kept. + var top = try volume.catalog(""); + var names: [8][name_length]u8 = undefined; + var lengths: [8]usize = undefined; + var count: usize = 0; + while (top.next()) |file| : (count += 1) { + @memcpy(names[count][0..file.name().len], file.name()); + lengths[count] = file.name().len; + } + try testing.expectEqual(@as(usize, 2), count); + try testing.expectEqualStrings("WORK", names[0][0..lengths[0]]); + try testing.expectEqualStrings("TOP", names[1][0..lengths[1]]); + + var inside = try volume.catalog("WORK"); + count = 0; + while (inside.next()) |_| count += 1; + try testing.expectEqual(@as(usize, 2), count); + + var buffer: [block_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + try volume.read("WORK/DEEPER/UNDER", &writer); + try testing.expectEqualStrings("further down", writer.buffered()); + + // A file is not a directory, and a directory is not a file. + try testing.expectError(error.NotADirectory, volume.catalog("TOP")); + try testing.expectError(error.IsADirectory, volume.read("WORK", &writer)); +} + +test "the file count is what a catalog stops at" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + const header = volume.headerAt(volume_directory); + try volume.write("ONE", .{ .kind = .text }, "1"); + try volume.write("TWO", .{ .kind = .text }, "2"); + try testing.expectEqual(@as(u16, 2), std.mem.readInt(u16, header[field.file_count..][0..2], .little)); + + // Writing over a file is not another file. + try volume.write("ONE", .{ .kind = .text }, "one again"); + try testing.expectEqual(@as(u16, 2), std.mem.readInt(u16, header[field.file_count..][0..2], .little)); + + try volume.delete("ONE"); + try testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, header[field.file_count..][0..2], .little)); +} + +test "deleting a file gives its blocks back" { + var volume = try blank(testing.allocator, 2000); + defer testing.allocator.free(volume.image); + const before = volume.freeBlocks(); + + const data = try testing.allocator.alloc(u8, (pointers_per_index + 1) * block_size); + defer testing.allocator.free(data); + @memset(data, 0x5a); + try volume.write("BIG", .{ .kind = .binary }, data); + try testing.expect(volume.freeBlocks() < before); + try volume.delete("BIG"); + try testing.expectEqual(before, volume.freeBlocks()); + try testing.expect(volume.find("BIG") == null); + + // A directory has to be empty before it can go. + try volume.makeDirectory("KEEP"); + try volume.write("KEEP/SOMETHING", .{ .kind = .text }, "x"); + try testing.expectError(error.NotEmpty, volume.delete("KEEP")); + try volume.delete("KEEP/SOMETHING"); + try volume.delete("KEEP"); + try testing.expectEqual(before, volume.freeBlocks()); +} + +test "a file is written over, unless it is locked" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + const long: [3000]u8 = @splat(0x11); + try volume.write("SAME", .{ .kind = .binary }, &long); + const after_long = volume.freeBlocks(); + + try volume.write("SAME", .{ .kind = .text }, "short"); + const entry = volume.find("SAME") orelse return error.NotFound; + try testing.expectEqual(FileType.text, entry.kind); + try testing.expectEqual(@as(u32, 5), entry.eof); + try testing.expect(volume.freeBlocks() > after_long); + + try volume.setLocked("SAME", true); + try testing.expect((volume.find("SAME") orelse return error.NotFound).locked()); + try testing.expectError(error.Locked, volume.write("SAME", .{ .kind = .text }, "no")); + try testing.expectError(error.Locked, volume.delete("SAME")); + try volume.setLocked("SAME", false); + try volume.write("SAME", .{ .kind = .text }, "yes"); +} + +test "a name ProDOS could not use is refused" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + try testing.expectError(error.BadName, volume.write("", .{ .kind = .text }, "x")); + try testing.expectError(error.BadName, volume.write("A" ** 16, .{ .kind = .text }, "x")); + // A name begins with a letter, and holds only letters, digits and stops. + try testing.expectError(error.BadName, volume.write("1FIRST", .{ .kind = .text }, "x")); + try testing.expectError(error.BadName, volume.write("HAS SPACE", .{ .kind = .text }, "x")); + try testing.expectError(error.BadName, volume.write("HAS-DASH", .{ .kind = .text }, "x")); + + // Names are held in upper case and matched without regard to it. + try volume.write("MixedCase", .{ .kind = .text }, "x"); + try testing.expectEqualStrings("MIXEDCASE", (volume.find("mixedcase") orelse return error.NotFound).name()); + try testing.expectError(error.Exists, volume.makeDirectory("MIXEDCASE")); +} + +test "a volume and a directory both fill up" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + + // The volume directory is four blocks and cannot grow: the header takes + // one of the thirteen entries in the first, so fifty-one is all it holds. + var name: [8]u8 = undefined; + for (0..50) |i| { + try volume.write(try std.fmt.bufPrint(&name, "F{d}", .{i}), .{ .kind = .text }, "x"); + } + + // A subdirectory does grow, so more than twelve files fit in one, and + // this is the fifty-first and last thing the volume directory holds. + try volume.makeDirectory("SUB"); + for (0..20) |i| { + try volume.write(try std.fmt.bufPrint(&name, "SUB/G{d}", .{i}), .{ .kind = .text }, "x"); + } + var inside = try volume.catalog("SUB"); + var count: usize = 0; + while (inside.next()) |_| count += 1; + try testing.expectEqual(@as(usize, 20), count); + const directory = volume.find("SUB") orelse return error.NotFound; + try testing.expectEqual(@as(u16, 2), directory.blocks_used); + + // And now there is nowhere left in the volume directory itself. + try testing.expectError(error.DirectoryFull, volume.write("ONEMORE", .{ .kind = .text }, "x")); + + // And a file that wants more blocks than are left is refused outright. + const left = volume.freeBlocks(); + const too_big = try testing.allocator.alloc(u8, (@as(usize, left) + 1) * block_size); + defer testing.allocator.free(too_big); + @memset(too_big, 0); + try testing.expectError(error.VolumeFull, volume.write("SUB/HUGE", .{ .kind = .binary }, too_big)); + try testing.expectEqual(left, volume.freeBlocks()); +} + +test "a volume says when it has been written to" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + try testing.expect(volume.dirty); + volume.dirty = false; + + try volume.write("ONE", .{ .kind = .text }, "x"); + try testing.expect(volume.dirty); + volume.dirty = false; + + var buffer: [block_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buffer); + try volume.read("ONE", &writer); + _ = volume.find("ONE"); + _ = volume.freeBlocks(); + try testing.expect(!volume.dirty); + + try testing.expectError(error.BadName, volume.write("1BAD", .{ .kind = .text }, "x")); + try testing.expectError(error.NotFound, volume.delete("NOTHERE")); + try testing.expect(!volume.dirty); +} + +test "the date is the one ProDOS keeps" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + volume.stamp = .from(2016, 9, 19, 19, 16); + try volume.write("STAMPED", .{ .kind = .text }, "x"); + + const entry = volume.find("STAMPED") orelse return error.NotFound; + // The two words a real volume holds, which is where these came from. + try testing.expectEqual(@as(u16, 0x2133), entry.created.date); + try testing.expectEqual(@as(u16, 0x1310), entry.created.time); + try testing.expectEqual(@as(u16, 2016), entry.created.year()); + try testing.expectEqual(@as(u4, 9), entry.created.month()); + try testing.expectEqual(@as(u5, 19), entry.created.day()); + try testing.expectEqual(@as(u5, 19), entry.created.hour()); + try testing.expectEqual(@as(u6, 16), entry.created.minute()); +} + +test "the type is shown the way a catalog shows it" { + var buffer: [3]u8 = undefined; + try testing.expectEqualStrings("TXT", FileType.text.abbreviation(&buffer)); + try testing.expectEqualStrings("BIN", FileType.binary.abbreviation(&buffer)); + try testing.expectEqualStrings("DIR", FileType.directory.abbreviation(&buffer)); + try testing.expectEqualStrings("SYS", FileType.system.abbreviation(&buffer)); + try testing.expectEqualStrings("BAS", FileType.applesoft.abbreviation(&buffer)); + // One of the many that never got a name. + try testing.expectEqualStrings("$42", @as(FileType, @enumFromInt(0x42)).abbreviation(&buffer)); +} + +test "a volume is read off a file and written back to one" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = testing.io; + + { + var made = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(made.image); + try made.write("ON.THE.DISK", .{ .kind = .binary }, "what was put there"); + try made.saveFile(tmp.dir, io, "made.po"); + try testing.expect(!made.dirty); + } + + var volume = try Volume.openFile(tmp.dir, io, "made.po", testing.allocator); + defer testing.allocator.free(volume.image); + try testing.expect(!volume.dirty); + var buffer: [name_length]u8 = undefined; + try testing.expectEqualStrings("TEST.VOLUME", volume.name(&buffer)); + + var out: [block_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&out); + try volume.read("ON.THE.DISK", &writer); + try testing.expectEqualStrings("what was put there", writer.buffered()); + + try tmp.dir.writeFile(io, .{ .sub_path = "short.po", .data = "not a volume" }); + try testing.expectError(error.WrongSize, Volume.openFile(tmp.dir, io, "short.po", testing.allocator)); +} + +test "an image that holds no ProDOS volume is not opened" { + const image = try testing.allocator.alloc(u8, min_blocks * block_size); + defer testing.allocator.free(image); + @memset(image, 0); + try testing.expectError(error.NotProdos, Volume.open(image)); + try testing.expectError(error.WrongSize, Volume.open(image[0 .. image.len - 1])); + try testing.expectError(error.TooSmall, Volume.open(image[0 .. 100 * block_size])); + try testing.expectError(error.BadName, Volume.format(image, "1BAD")); +} + +test "a directory header is written the way ProDOS writes one" { + var volume = try blank(testing.allocator, min_blocks); + defer testing.allocator.free(volume.image); + try volume.makeDirectory("SUB"); + const entry = volume.find("SUB") orelse return error.NotFound; + + // What a real volume holds, and what ProDOS itself writes when it makes a + // directory: the mark it looks for, the shape of the directory, the entry + // that named it, and the access byte a header carries, which is the one a + // file carries without the backup bit. + const header = volume.headerAt(entry.key); + try testing.expectEqual(@as(u8, 0xe0 | 3), header[field.storage]); + try testing.expectEqual(@as(u8, 0x75), header[field.subdirectory_mark]); + try testing.expectEqual(@as(u8, 0xc3), header[field.access]); + try testing.expectEqual(@as(u8, entry_size), header[field.entry_length]); + try testing.expectEqual(@as(u8, entries_per_block), header[field.entries]); + try testing.expectEqual(@as(u16, volume_directory), std.mem.readInt(u16, header[field.parent..][0..2], .little)); + try testing.expectEqual(@as(u8, entry_size), header[field.parent_entry_length]); + // The entry it points back at is this directory's own. + const back: Slot = .{ .block = volume_directory, .index = header[field.parent_entry] - 1 }; + try testing.expectEqual(entry.slot.index, back.index); + + // The volume's own header carries it too. + try testing.expectEqual(@as(u8, 0xc3), volume.headerAt(volume_directory)[field.access]); + // A file, and the entry that names a directory, carry the backup bit. + try testing.expectEqual(@as(u8, 0xe3), volume.entryAt(entry.slot)[field.access]); +} diff --git a/src/root.zig b/src/root.zig index 45f22a0..1330e42 100644 --- a/src/root.zig +++ b/src/root.zig @@ -36,6 +36,9 @@ pub const disk2 = @import("disk2.zig"); /// DOS 3.3 as it lies on a disk: making an image, and the files on it. pub const dos33 = @import("dos33.zig"); +/// ProDOS as it lies on a volume: making an image, and the files on it. +pub const prodos = @import("prodos.zig"); + /// The memory models a processor can be given. Flat is the only one so far; /// a machine with banking and soft switches goes alongside it. pub const memory = @import("memory.zig"); @@ -58,6 +61,7 @@ test { _ = @import("instantiation.zig"); _ = disk2; _ = dos33; + _ = prodos; _ = screen; _ = speaker; _ = cassette; -- knotmirror 0.0.1