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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The UCSD p-System filesystem as Apple Pascal lies it on a disk: a directory//! of fixed-size entries naming files, each of which is a contiguous run of//! 512-byte blocks.//!//! This is the third of the disk filesystems here, beside `dos33` and//! `prodos`, and it works the same way: on the plain block image a `.po` file//! holds rather than on the encoded surface a drive reads, in place, allocating//! nothing. A `.dsk` in DOS sector order has to be put into block order first —//! `disk2.reorder(image, into, .dos, .prodos)` — because a p-System volume, like//! a ProDOS one, keeps its blocks in the logical order DOS interleaves.//!//! A volume is a run of blocks. The first two are the bootstrap; the next four//! are the directory, two kilobytes holding seventy-eight twenty-six-byte//! entries. The first entry describes the volume — its name, how many blocks it//! has, how many files are on it — and the rest, up to seventy-seven of them,//! describe the files, kept packed and in ascending order of the block each//! starts on. There is no free-space map: the gaps between one file and the//! next are the free space, which is why the p-System's own answer to a//! fragmented disk was to shuffle every file down against its neighbour//! ("krunch") rather than to allocate around the holes.//!//! Every file is contiguous: an entry gives the first block and the block one//! past the last, so a file's length is that many whole blocks bar the last,//! whose used byte count the entry carries as well. Nothing here decodes what//! is inside a file — a text file's two-block editor header and its//! run-compressed lines come back as the bytes they are stored as.//!//! The layout is that of the p-System's own `DIRENTRY` record, a variant record//! whose two arms — the volume header and a file — share the first six bytes//! and then differ, and it was settled against Apple's own Pascal 1.1 disks.
const std = @import("std");const testing = std.testing;
const disk2 = @import("disk2.zig");
/// A block is half a kilobyte, which is two of a 5.25-inch disk's sectors and/// the unit everything in a p-System volume is counted in.pub const block_size = 512;
/// The first two blocks are the bootstrap and the next four are the directory,/// so a file can start no earlier than block six.pub const boot_blocks = 2;pub const directory_block = 2;pub const directory_blocks = 4;pub const first_file_block = directory_block + directory_blocks;
/// Twenty-six bytes to an entry, seventy-eight of them in the four-block/// directory: one for the volume and up to seventy-seven for files.pub const entry_size = 26;pub const directory_entries = directory_blocks * block_size / entry_size;pub const max_files = directory_entries - 1;
/// Seven characters of volume name, fifteen of a file's, each kept with a/// length byte in front the way a Pascal string is.pub const volume_name_length = 7;pub const file_name_length = 15;
/// The smallest volume this will open — the boot blocks and the directory and/// nothing else — and the largest, since a p-System block number is a signed/// sixteen-bit integer.pub const min_blocks = first_file_block;pub const max_blocks = 0x7fff;
/// The fields the two arms of a directory entry share, and then the ones each/// arm has of its own. (The p-System's `DIRENTRY`, a variant record on the file/// kind.)const field = struct { /// The first block of the file, or 0 for the volume header. const first_block = 0x00; /// The block one past the last: the directory's is six, a file's is its /// first plus its length in blocks. const next_block = 0x02; /// The kind, in the low four bits of a word. The volume header reads as /// the zeroth kind and is told apart by being the first entry. const kind = 0x04;
/// A file entry from byte six on. const name_length = 0x06; const name = 0x07; /// How many bytes of the last block are the file's; the rest is slack. const last_byte = 0x16; /// When the file was last written, as a packed date. const access_date = 0x18;};
/// The volume header's own fields from byte six on, where a file keeps its/// name.const header = struct { const name_length = 0x06; const name = 0x07; /// How many blocks the volume has, which is `DEOVBLK`. const total_blocks = 0x0e; /// How many files are on it, which is how far the packed directory runs. const num_files = 0x10; /// The time of the last access and the date last set, neither of which /// anything here reads. const load_time = 0x12; const boot_date = 0x14;};
/// What a directory entry says a file is, in the low four bits of its kind/// word. The set is the p-System's, and open because a byte on a disk is/// whatever was put there.pub const FileKind = enum(u4) { untyped = 0, /// A run of blocks the system found bad and fenced off. bad = 1, code = 2, text = 3, info = 4, data = 5, graf = 6, foto = 7, secure_directory = 8, _,};
/// A packed date, as the p-System keeps one: the month in the low four bits,/// the day in the next five, the year in the top seven. A year of zero is what/// an undated file carries.pub const Date = struct { year: u7 = 0, month: u4 = 0, day: u5 = 0,
pub fn from(bits: u16) Date { return .{ .month = @truncate(bits & 0xf), .day = @truncate(bits >> 4 & 0x1f), .year = @truncate(bits >> 9 & 0x7f), }; }
pub fn word(self: Date) u16 { return @as(u16, self.month) | @as(u16, self.day) << 4 | @as(u16, self.year) << 9; }};
/// Where an entry sits in the directory, so that it can be written back after/// being read. Index zero is the volume header; a file is one or more.pub const Slot = struct { index: u8,};
/// A file, as its directory entry describes it.pub const Entry = struct { slot: Slot, first_block: u16, next_block: u16, kind: FileKind, date: Date, /// How many bytes of the last block belong to the file. last_byte: u16, stored: [file_name_length]u8, length: u8,
/// The name, trimmed to its stored length. pub fn name(self: *const Entry) []const u8 { return self.stored[0..self.length]; }
/// How many blocks the file occupies, which is a whole number since a file /// is contiguous. pub fn blocks(self: *const Entry) u16 { return self.next_block - self.first_block; }
/// How many bytes the file holds: whole blocks bar the last, and the last /// block's used count. pub fn size(self: *const Entry) u32 { const count = self.blocks(); if (count == 0) return 0; return (@as(u32, count) - 1) * block_size + self.last_byte; }
fn from(bytes: *const [entry_size]u8, slot: Slot) Entry { var self: Entry = .{ .slot = slot, .first_block = std.mem.readInt(u16, bytes[field.first_block..][0..2], .little), .next_block = std.mem.readInt(u16, bytes[field.next_block..][0..2], .little), .kind = @enumFromInt(@as(u4, @truncate(std.mem.readInt(u16, bytes[field.kind..][0..2], .little)))), .date = Date.from(std.mem.readInt(u16, bytes[field.access_date..][0..2], .little)), .last_byte = std.mem.readInt(u16, bytes[field.last_byte..][0..2], .little), .stored = undefined, .length = @min(bytes[field.name_length], file_name_length), }; @memcpy(&self.stored, bytes[field.name..][0..file_name_length]); return self; }};
/// A p-System volume, held as the plain block image and nothing more. Copy it/// about freely: it is a slice, and every operation writes through it.pub const Volume = struct { image: []u8, /// Whether anything has been written since the volume was opened or last /// saved. `format` leaves it set, since a volume just laid out is not what /// any file holds. dirty: bool = false,
pub const SizeError = error{ NotBlocks, TooSmall, TooLarge }; pub const OpenError = SizeError || error{NotPascal}; pub const NameError = error{BadName}; pub const WriteError = NameError || error{ VolumeFull, DirectoryFull, TooBig }; pub const DeleteError = error{NotFound}; pub const ReadError = error{ NotFound, Damaged } || std.Io.Writer.Error;
/// Lays out an empty volume: the boot blocks and directory zeroed, a volume /// header naming it and saying how many blocks it has, and no files. /// /// The boot blocks are left as they are rather than being zeroed, so that a /// caller who has put a bootstrap there keeps it. pub fn format(image: []u8, volume_name: []const u8) (SizeError || NameError)!Volume { try checkSize(image.len); var stored: [volume_name_length]u8 = undefined; const length = try storeName(volume_name, &stored, volume_name_length);
var self: Volume = .{ .image = image, .dirty = true }; @memset(image[directory_block * block_size .. first_file_block * block_size], 0);
const head = self.entryAt(.{ .index = 0 }); std.mem.writeInt(u16, head[field.first_block..][0..2], 0, .little); std.mem.writeInt(u16, head[field.next_block..][0..2], first_file_block, .little); std.mem.writeInt(u16, head[field.kind..][0..2], 0, .little); head[header.name_length] = length; @memcpy(head[header.name..][0..volume_name_length], &stored); std.mem.writeInt(u16, head[header.total_blocks..][0..2], @intCast(image.len / block_size), .little); std.mem.writeInt(u16, head[header.num_files..][0..2], 0, .little); return self; }
/// Takes an image that already holds a volume, checking that the header /// describes the shape a p-System directory has: a four-block directory /// starting at block two, a name that fits, and a block count that fits the /// image. pub fn open(image: []u8) OpenError!Volume { try checkSize(image.len); const self: Volume = .{ .image = image }; const head = self.entryAt(.{ .index = 0 });
if (std.mem.readInt(u16, head[field.first_block..][0..2], .little) != 0) return error.NotPascal; if (std.mem.readInt(u16, head[field.next_block..][0..2], .little) != first_file_block) return error.NotPascal; const name_length = head[header.name_length]; if (name_length == 0 or name_length > volume_name_length) return error.NotPascal;
const total = std.mem.readInt(u16, head[header.total_blocks..][0..2], .little); if (total < min_blocks or total > image.len / block_size) return error.NotPascal; if (self.numFiles() > max_files) return error.NotPascal; return self; }
/// Reads a whole image off the file system and opens it, the caller owning /// and freeing the buffer. The file is taken as block order: a `.dsk` in /// DOS sector order has to be reordered first. 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 name, trimmed to its stored length. pub fn name(self: *const Volume, buffer: *[volume_name_length]u8) []const u8 { const head = self.entryAt(.{ .index = 0 }); const length = @min(head[header.name_length], volume_name_length); @memcpy(buffer, head[header.name..][0..volume_name_length]); return buffer[0..length]; }
/// How many blocks the header says the volume has. pub fn totalBlocks(self: *const Volume) u16 { return std.mem.readInt(u16, self.entryAt(.{ .index = 0 })[header.total_blocks..][0..2], .little); }
/// How many files are on the volume, which is how far the packed directory /// runs. pub fn numFiles(self: *const Volume) u16 { return std.mem.readInt(u16, self.entryAt(.{ .index = 0 })[header.num_files..][0..2], .little); }
/// How many blocks are not spoken for: the total less the boot blocks, the /// directory, and every file. pub fn freeBlocks(self: *const Volume) u16 { var used: u16 = first_file_block; var files = self.catalog(); while (files.next()) |entry| used += entry.blocks(); const total = self.totalBlocks(); return if (total > used) total - used else 0; }
/// The largest run of free blocks there is, which is the largest file that /// can be written without first shuffling the volume down. pub fn largestFree(self: *const Volume) u16 { var largest: u16 = 0; var next: u16 = first_file_block; const total = self.totalBlocks(); var files = self.catalog(); while (files.next()) |entry| { if (entry.first_block > next) largest = @max(largest, entry.first_block - next); next = entry.next_block; } if (total > next) largest = @max(largest, total - next); return largest; }
/// Every file on the volume, in the order the directory holds them, which /// is ascending order of the block each starts on. pub fn catalog(self: *const Volume) Catalog { return .{ .volume = self, .count = self.numFiles() }; }
/// The entry for a name, or nothing if the volume has no such file. pub fn find(self: *const Volume, wanted: []const u8) ?Entry { const slot = self.findSlot(wanted) orelse return null; return Entry.from(self.entryAt(slot), slot); }
/// Writes a file's bytes out: the whole blocks it holds and the used part /// of its last one, which is where the byte count in the entry comes in. /// /// Nothing is decoded. A text file's two-block editor header and its /// run-compressed lines come out as the bytes they are stored as. pub fn read(self: *const Volume, wanted: []const u8, writer: *std.Io.Writer) ReadError!void { const entry = self.find(wanted) orelse return error.NotFound; const total = self.totalBlocks(); if (entry.first_block < first_file_block or entry.next_block > total or entry.first_block >= entry.next_block) { return error.Damaged; } if (entry.last_byte == 0 or entry.last_byte > block_size) return error.Damaged;
const count = entry.blocks(); for (0..count) |i| { const block = self.blockAt(entry.first_block + @as(u16, @intCast(i))); const take: usize = if (i + 1 == count) entry.last_byte else block_size; try writer.writeAll(block[0..take]); } }
/// Puts a file on the volume, over one of the same name if there is one. /// /// A p-System file is contiguous, so this needs a single run of free blocks /// big enough — the largest gap between the files already there. A volume /// with room enough in total but no gap that big is `error.VolumeFull` all /// the same, since nothing here shuffles the files down to make one; that /// is what the p-System's krunch was for. pub fn write(self: *Volume, wanted: []const u8, kind: FileKind, data: []const u8) WriteError!void { var stored: [file_name_length]u8 = undefined; const length = try storeName(wanted, &stored, file_name_length); if (data.len > @as(usize, max_blocks) * block_size) return error.TooBig;
const need_blocks: u16 = @intCast(@max(1, (data.len + block_size - 1) / block_size)); const last_byte: u16 = if (data.len == 0) block_size else @intCast(data.len - (@as(usize, need_blocks) - 1) * block_size);
// Settle everything that can refuse the write before touching the // volume, so a write that cannot happen leaves what was there. const existing = self.findSlotStored(&stored, length); if (existing == null and self.numFiles() >= max_files) return error.DirectoryFull;
// The gap search treats an existing file of the same name as already // gone, so writing a bigger version into its own place works. const start = self.findGap(need_blocks, existing) orelse return error.VolumeFull;
// Write the data into the run, zeroing the slack in the last block. for (0..need_blocks) |i| { const block = self.blockAt(start + @as(u16, @intCast(i))); const at = i * block_size; const take = @min(block_size, data.len - at); @memcpy(block[0..take], data[at..][0..take]); if (take < block_size) @memset(block[take..], 0); }
if (existing) |slot| self.removeSlot(slot);
var entry: [entry_size]u8 = undefined; @memset(&entry, 0); std.mem.writeInt(u16, entry[field.first_block..][0..2], start, .little); std.mem.writeInt(u16, entry[field.next_block..][0..2], start + need_blocks, .little); std.mem.writeInt(u16, entry[field.kind..][0..2], @intFromEnum(kind), .little); entry[field.name_length] = length; @memcpy(entry[field.name..][0..file_name_length], &stored); std.mem.writeInt(u16, entry[field.last_byte..][0..2], last_byte, .little); std.mem.writeInt(u16, entry[field.access_date..][0..2], 0, .little); self.insert(&entry, start); self.dirty = true; }
/// Takes a file off the volume, giving its blocks back. The blocks /// themselves are left as they were; only the directory changes. pub fn delete(self: *Volume, wanted: []const u8) DeleteError!void { const slot = self.findSlot(wanted) orelse return error.NotFound; self.removeSlot(slot); self.dirty = true; }
/// One block of the image, to read or to write. Nothing written this way /// sets `dirty` or touches the directory: a caller reaching in this far is /// on its own. pub fn blockAt(self: *const Volume, block: u16) *[block_size]u8 { return self.image[@as(usize, block) * block_size ..][0..block_size]; }
fn entryAt(self: *const Volume, slot: Slot) *[entry_size]u8 { const at = directory_block * block_size + @as(usize, slot.index) * entry_size; return self.image[at..][0..entry_size]; }
/// The slot for a name, searched over the files only, or nothing. Names are /// matched without regard to case, the way the p-System does. fn findSlot(self: *const Volume, wanted: []const u8) ?Slot { var stored: [file_name_length]u8 = undefined; const length = storeName(wanted, &stored, file_name_length) catch return null; return self.findSlotStored(&stored, length); }
fn findSlotStored(self: *const Volume, stored: *const [file_name_length]u8, length: u8) ?Slot { const files = self.numFiles(); var index: u8 = 1; while (index <= files) : (index += 1) { const entry = self.entryAt(.{ .index = index }); if (entry[field.name_length] != length) continue; if (std.mem.eql(u8, entry[field.name..][0..length], stored[0..length])) return .{ .index = index }; } return null; }
/// The first free run of at least `need` blocks, treating the file at /// `ignore` (if any) as already gone so it can be written over. Returns the /// starting block, or nothing if no gap is big enough. fn findGap(self: *const Volume, need: u16, ignore: ?Slot) ?u16 { const total = self.totalBlocks(); const files = self.numFiles(); var next: u16 = first_file_block; var index: u8 = 1; while (index <= files) : (index += 1) { if (ignore) |slot| { if (slot.index == index) continue; } const entry = self.entryAt(.{ .index = index }); const first = std.mem.readInt(u16, entry[field.first_block..][0..2], .little); if (first >= next and first - next >= need) return next; const after = std.mem.readInt(u16, entry[field.next_block..][0..2], .little); if (after > next) next = after; } if (total >= next and total - next >= need) return next; return null; }
/// Puts an entry into the directory in ascending order of its first block, /// shifting the entries after it up, and counts one more file. fn insert(self: *Volume, entry: *const [entry_size]u8, start: u16) void { const files = self.numFiles(); var at: u8 = 1; while (at <= files) : (at += 1) { const there = std.mem.readInt(u16, self.entryAt(.{ .index = at })[field.first_block..][0..2], .little); if (start < there) break; } var index: u8 = @intCast(files + 1); while (index > at) : (index -= 1) { @memcpy(self.entryAt(.{ .index = index }), self.entryAt(.{ .index = index - 1 })); } @memcpy(self.entryAt(.{ .index = at }), entry); self.setNumFiles(files + 1); }
/// Takes an entry out, shifting the entries after it down, and counts one /// fewer file. fn removeSlot(self: *Volume, slot: Slot) void { const files = self.numFiles(); var index: u8 = slot.index; while (index < files) : (index += 1) { @memcpy(self.entryAt(.{ .index = index }), self.entryAt(.{ .index = index + 1 })); } @memset(self.entryAt(.{ .index = @intCast(files) }), 0); self.setNumFiles(files - 1); }
fn setNumFiles(self: *Volume, count: u16) void { std.mem.writeInt(u16, self.entryAt(.{ .index = 0 })[header.num_files..][0..2], count, .little); }
fn checkSize(len: usize) SizeError!void { if (len % block_size != 0) return error.NotBlocks; const count = len / block_size; if (count < min_blocks) return error.TooSmall; if (count > max_blocks) return error.TooLarge; }};
/// The files on a volume, in the order the directory holds them.pub const Catalog = struct { volume: *const Volume, count: u16, index: u8 = 0,
pub fn next(self: *Catalog) ?Entry { if (self.index >= self.count) return null; self.index += 1; return Entry.from(self.volume.entryAt(.{ .index = self.index }), .{ .index = self.index }); }};
/// Puts a name into the bytes an entry holds it in, giving back its length.////// The p-System's filenames are not case sensitive and are held in upper case,/// so a lower-case letter is folded up. A few characters are refused because/// the command line gives them a meaning of their own: a blank ends a name, a/// colon marks a volume, an equals or a comma or a question mark drives the/// wildcard matching in the Filer, and a dollar and a bracket go with them.fn storeName(name: []const u8, into: []u8, limit: usize) Volume.NameError!u8 { if (name.len == 0 or name.len > limit) return error.BadName; @memset(into[0..limit], 0); for (name, 0..) |character, i| { if (character < 0x20 or character > 0x7e) return error.BadName; switch (character) { ' ', ':', '=', '?', ',', '$', '[', ']' => return error.BadName, else => {}, } into[i] = std.ascii.toUpper(character); } return @intCast(name.len);}
/// The 5.25-inch disk everything below is a case of: two hundred and eighty/// blocks, which is what a formatted Apple Pascal floppy has.const floppy_blocks = disk2.image_size / block_size;
fn blank(allocator: std.mem.Allocator) !Volume { const image = try allocator.alloc(u8, floppy_blocks * block_size); @memset(image, 0); return Volume.format(image, "BLANK");}
test "a formatted volume has the shape the p-System gives it" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image);
var buffer: [volume_name_length]u8 = undefined; try testing.expectEqualStrings("BLANK", volume.name(&buffer)); try testing.expectEqual(@as(u16, floppy_blocks), volume.totalBlocks()); try testing.expectEqual(@as(u16, 0), volume.numFiles());
// The header points at block six as the block past the directory, and // everything but the boot blocks and the directory is free. const head = volume.entryAt(.{ .index = 0 }); try testing.expectEqual(@as(u16, 0), std.mem.readInt(u16, head[field.first_block..][0..2], .little)); try testing.expectEqual(@as(u16, first_file_block), std.mem.readInt(u16, head[field.next_block..][0..2], .little)); try testing.expectEqual(@as(u16, floppy_blocks - first_file_block), volume.freeBlocks());
var files = volume.catalog(); try testing.expectEqual(@as(?Entry, null), files.next()); _ = try Volume.open(volume.image);}
test "a file comes back the way it went on" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image);
var data: [700]u8 = undefined; for (&data, 0..) |*byte, i| byte.* = @truncate(i * 3 + i / 5); try volume.write("HELLO.CODE", .code, &data);
const entry = volume.find("HELLO.CODE") orelse return error.NotFound; try testing.expectEqualStrings("HELLO.CODE", entry.name()); try testing.expectEqual(FileKind.code, entry.kind); // Seven hundred bytes is two blocks: a full one and a hundred and // eighty-eight bytes of a second. try testing.expectEqual(@as(u16, 2), entry.blocks()); try testing.expectEqual(@as(u16, 700 - block_size), entry.last_byte); try testing.expectEqual(@as(u32, 700), entry.size()); try testing.expectEqual(@as(u16, first_file_block), entry.first_block);
var buffer: [700]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try volume.read("HELLO.CODE", &writer); try testing.expectEqualSlices(u8, &data, writer.buffered());
try testing.expectError(error.NotFound, volume.read("NOTHERE", &writer));}
test "a name is folded to upper case and the awkward ones are refused" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image);
try volume.write("lower.text", .text, "x"); try testing.expect(volume.find("LOWER.TEXT") != null); // The stored form is upper case, and a lookup folds too. try testing.expect(volume.find("Lower.Text") != null);
try testing.expectError(error.BadName, volume.write("", .text, "x")); try testing.expectError(error.BadName, volume.write("A" ** 16, .text, "x")); for ([_][]const u8{ "A B", "A:B", "A=B", "A,B", "A?B", "A$B" }) |bad| { try testing.expectError(error.BadName, volume.write(bad, .text, "x")); } try volume.write("A" ** 15, .text, "x"); try testing.expectEqualStrings("A" ** 15, (volume.find("A" ** 15) orelse return error.NotFound).name());}
test "the directory stays sorted by first block as files come and go" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image);
// Three files laid down one after another. try volume.write("ONE", .data, &[_]u8{1} ** 1000); // 2 blocks: 6,7 try volume.write("TWO", .data, &[_]u8{2} ** 500); // 1 block: 8 try volume.write("THREE", .data, &[_]u8{3} ** 1500); // 3 blocks: 9,10,11
var files = volume.catalog(); try testing.expectEqualStrings("ONE", (files.next() orelse return error.NotFound).name()); try testing.expectEqualStrings("TWO", (files.next() orelse return error.NotFound).name()); try testing.expectEqualStrings("THREE", (files.next() orelse return error.NotFound).name()); try testing.expectEqual(@as(?Entry, null), files.next());
// Taking the middle one out leaves a two-block-wide hole between ONE and // THREE. A new one-block file drops into the front of that hole, so the // directory reads ONE, NEW, THREE — still in block order. try volume.delete("TWO"); try volume.write("NEW", .text, "x"); files = volume.catalog(); try testing.expectEqualStrings("ONE", (files.next() orelse return error.NotFound).name()); const new = files.next() orelse return error.NotFound; try testing.expectEqualStrings("NEW", new.name()); try testing.expectEqual(@as(u16, 8), new.first_block); try testing.expectEqualStrings("THREE", (files.next() orelse return error.NotFound).name());}
test "a file is written over its older self even when it grows" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image);
try volume.write("A", .data, "short"); try volume.write("B", .data, &[_]u8{0xbb} ** 300); const before = volume.freeBlocks();
// Rewriting A bigger cannot fit in its old one block with B right behind // it, so it goes after B and leaves its old block free. It grew by a block, // so one fewer is free than before, and the block it vacated is one of the // free ones — a hole this filesystem will not allocate around. try volume.write("A", .code, &[_]u8{0xaa} ** 900); const entry = volume.find("A") orelse return error.NotFound; try testing.expectEqual(FileKind.code, entry.kind); try testing.expectEqual(@as(u16, 2), entry.blocks()); try testing.expectEqual(before - 1, volume.freeBlocks()); try testing.expect(entry.first_block > (volume.find("B") orelse return error.NotFound).first_block);
var count: usize = 0; var files = volume.catalog(); while (files.next()) |_| count += 1; try testing.expectEqual(@as(usize, 2), count);
var buffer: [900]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try volume.read("A", &writer); try testing.expectEqualSlices(u8, &[_]u8{0xaa} ** 900, writer.buffered());}
test "the free space fills up, and fragmentation refuses what the total would allow" { // A volume exactly ten file blocks big, so filling it and poking holes // leaves nothing but fragments — a wide-open tail cannot hide the gaps. const total = first_file_block + 10; const image = try testing.allocator.alloc(u8, total * block_size); defer testing.allocator.free(image); @memset(image, 0); var volume = try Volume.format(image, "SMALL");
// A file bigger than the volume has room for is refused before anything is // touched. const free_blocks = volume.freeBlocks(); const too_big = try testing.allocator.alloc(u8, (@as(usize, free_blocks) + 1) * block_size); defer testing.allocator.free(too_big); @memset(too_big, 0); try testing.expectError(error.VolumeFull, volume.write("HUGE", .data, too_big)); try testing.expectEqual(free_blocks, volume.freeBlocks()); try testing.expectEqual(@as(?Entry, null), volume.find("HUGE"));
// Fill every block with one-block files, then take out every other one: // five one-block holes, five blocks free, and no run of two anywhere. var name: [8]u8 = undefined; for (0..10) |i| try volume.write(try std.fmt.bufPrint(&name, "F{d}", .{i}), .data, "x"); try testing.expectEqual(@as(u16, 0), volume.freeBlocks()); for (0..10) |i| { if (i % 2 == 0) try volume.delete(try std.fmt.bufPrint(&name, "F{d}", .{i})); } try testing.expectEqual(@as(u16, 5), volume.freeBlocks()); try testing.expectEqual(@as(u16, 1), volume.largestFree()); try testing.expectError(error.VolumeFull, volume.write("PAIR", .data, &[_]u8{0} ** (block_size + 1))); // But a single block still fits one of the holes. try volume.write("SINGLE", .data, "x");}
test "the directory cannot hold more than seventy-seven files" { // A volume big enough that space is not what runs out first. const image = try testing.allocator.alloc(u8, 4096 * block_size); defer testing.allocator.free(image); @memset(image, 0); var volume = try Volume.format(image, "BIG");
var name: [8]u8 = undefined; for (0..max_files) |i| try volume.write(try std.fmt.bufPrint(&name, "F{d}", .{i}), .data, "x"); try testing.expectEqual(@as(u16, max_files), volume.numFiles()); try testing.expectError(error.DirectoryFull, volume.write("ONEMORE", .data, "x"));}
test "a volume says when it has been written to" { var volume = try blank(testing.allocator); defer testing.allocator.free(volume.image); try testing.expect(volume.dirty); volume.dirty = false;
try volume.write("ONE", .text, "x"); try testing.expect(volume.dirty); volume.dirty = false;
// Reading changes nothing. var buffer: [block_size]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try volume.read("ONE", &writer); _ = volume.find("ONE"); _ = volume.freeBlocks(); var files = volume.catalog(); while (files.next()) |_| {} try testing.expect(!volume.dirty);
// A refused write leaves the volume, and its dirtiness, alone. try testing.expectError(error.BadName, volume.write("A,B", .text, "x")); try testing.expectError(error.NotFound, volume.delete("NOTHERE")); try testing.expect(!volume.dirty);
try volume.delete("ONE"); try testing.expect(volume.dirty);}
test "a packed date goes round and comes back" { const date: Date = .{ .year = 84, .month = 11, .day = 27 }; try testing.expectEqual(date, Date.from(date.word()));}
test "an image that holds no p-System volume is not opened" { const image = try testing.allocator.alloc(u8, floppy_blocks * block_size); defer testing.allocator.free(image); @memset(image, 0); try testing.expectError(error.NotPascal, Volume.open(image)); try testing.expectError(error.NotBlocks, Volume.open(image[0 .. image.len - 1])); try testing.expectError(error.TooSmall, Volume.open(image[0 .. min_blocks * block_size - block_size]));}
test "a volume 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, floppy_blocks * block_size); defer testing.allocator.free(image); @memset(image, 0); var made = try Volume.format(image, "MADE"); try made.write("ON.THE.DISK", .code, "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); var buffer: [volume_name_length]u8 = undefined; try testing.expectEqualStrings("MADE", 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());}