diff --git a/README.md b/README.md index 2c0f24f..cfd4c34 100644 --- a/README.md +++ b/README.md @@ -2166,17 +2166,21 @@ trace — it is the commonest thing a `.SHK` is — so it says so in words: zig65: cannot read 'ProDOS 2.0.3.shk': that archive holds files rather than a disk ``` +Reading these, and writing them back, is [`zig-shrinkit`][zig-shrinkit], a +package of its own: the NuFX format and the two LZW compressors inside it, which +used to be reimplemented here and is now the one thing that knows how a +ShrinkIt archive is put together. + A disk that came out of an archive is write protected unless `--writable` says otherwise, as any other disk is. With it, the machine's writes are saved back into the file the disk came out of. Putting a disk back into a ShrinkIt -archive means *writing* NuFX, and writing it **uncompressed** — a stored thread, -which the format allows and every reader takes — rather than running the LZW -compressor in reverse for the sake of a smaller file. The archive that comes -out is larger than the one that went in but is valid, and it is rebuilt from -scratch around the modified disk rather than patched, because the thread it -carries is a different size. Only a **single-record** archive is written back: -the ordinary writable `.SDK` is one disk in one record, and an archive holding -more than that is refused rather than rebuilt lossily. +archive means *writing* NuFX, which `zig-shrinkit` does the way ShrinkIt did — +run-length encoding and then LZW/2 — so the file that goes home is about the +size of the one that came in rather than a larger stored copy. It is rebuilt +from scratch around the modified disk rather than patched, because the thread +it carries is a different size. Only a **single-record** archive is written +back: the ordinary writable `.SDK` is one disk in one record, and an archive +holding more than that is refused rather than rebuilt lossily. The compression is run-length encoding followed by LZW, in four kilobyte chunks — four kilobytes because a track of a 5.25-inch disk is four kilobytes, @@ -2205,7 +2209,7 @@ record of version 3 puts a thread's CRC in the thread header, seeded `$ffff`, over the file's own bytes. LZW/1 keeps its own inside the stream, seeded zero, over the bytes **padded out to a whole four kilobyte chunk**, because that is what the compressor had in its buffer. A stream can have one, the other, both -or neither, and `src/shrinkit.zig` checks whichever it is given. +or neither, and the reader checks whichever it is given. None of this was guessed at twice. It was worked out against twenty-four real archives — nineteen LZW/2 and five LZW/1 — and every one of them decodes and @@ -4107,8 +4111,8 @@ machine around them is not. what most Apple II software is distributed as — is unpacked and the disk inside it used. Writing works and is saved back to the file when asked for — as nibbles for a `.nib`, which is the only file that can hold a track the - machine laid out itself, and as a fresh uncompressed NuFX archive for a - single-disk `.shk` or `.sdk`. + machine laid out itself, and as a fresh NuFX archive, compressed the way + ShrinkIt does, for a single-disk `.shk` or `.sdk`. - **Text video.** Forty columns, and on a IIe eighty, drawn out of both halves of memory the way the hardware reads them, with the alternate character set and both text pages. The switches that move the processor's window about are @@ -6424,7 +6428,6 @@ before. | `src/disk35.zig` | the Apple 3.5-inch drive: its fifteen registers, and 800K of zoned six and two | | `src/woz.zig` | WOZ: a disk as the bits that go past the head | | `src/twomg.zig` | the 2IMG wrapper, which is a disk image that says what it is | -| `src/shrinkit.zig` | ShrinkIt archives: the NuFX format and both of its compressors | | `src/diskfile.zig` | a disk out of whatever file was named: a sector image, a `.2mg`, a `.nib`, a `.woz` or a ShrinkIt archive | | `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 | @@ -7555,6 +7558,7 @@ this does not model. [klaus]: https://github.com/Klaus2m5/6502_65C02_functional_tests [aigrette65]: https://git.jcollie.dev/jeff/aigrette65 [zig-pipewire]: https://git.jcollie.dev/jeff/zig-pipewire +[zig-shrinkit]: https://git.jcollie.dev/jeff/zig-shrinkit [a2audit]: https://github.com/zellyn/a2audit [mb-audit]: https://github.com/tomcw/mb-audit [deadtest]: https://github.com/misterblack1/appleII_deadtest diff --git a/build.zig b/build.zig index 3fe4bb4..140f661 100644 --- a/build.zig +++ b/build.zig @@ -41,12 +41,27 @@ pub fn build(b: *std.Build) void { .optimize = app_optimize, }); + // Reading and writing ShrinkIt archives -- the NuFX format and the two LZW + // compressors inside it -- which src/diskfile.zig and src/writeback.zig use + // to unpack a disk out of a `.SHK`/`.SDK` and to put a modified one back. + // It is the user's own project, and it replaces what used to be an + // uncompressed-only reimplementation here in src/shrinkit.zig. + const shrinkit = b.dependency("shrinkit", .{ + .target = target, + .optimize = optimize, + }); + const shrinkit_shipped = b.dependency("shrinkit", .{ + .target = target, + .optimize = app_optimize, + }); + const zig65 = b.addModule("zig65", .{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "z2d", .module = z2d.module("z2d") }, + .{ .name = "shrinkit", .module = shrinkit.module("shrinkit") }, }, }); @@ -59,6 +74,7 @@ pub fn build(b: *std.Build) void { .optimize = app_optimize, .imports = &.{ .{ .name = "z2d", .module = z2d_shipped.module("z2d") }, + .{ .name = "shrinkit", .module = shrinkit_shipped.module("shrinkit") }, }, }); diff --git a/build.zig.zon b/build.zig.zon index fb2cf96..d6c3e1e 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -50,6 +50,10 @@ .url = "git+https://git.jcollie.dev/jeff/zig-pipewire.git?ref=main#1af83e5134fb72aeb1e3f583a3bc2f87d587ec22", .hash = "pipewire-0.1.0-lH35HusiBACjmg25_hcNJOTjMGFfSKyczRK3_6wSG95i", }, + .shrinkit = .{ + .url = "git+https://git.jcollie.dev/jeff/zig-shrinkit.git#227e1144a3b641dde19e09415077590b562f64d6", + .hash = "shrinkit-0.0.0-GRYwpSwGAwCjR5WiQiq-WDpC1NV9hvglB_UStLrqS4LN", + }, }, .paths = .{ diff --git a/build.zig.zon.nix b/build.zig.zon.nix index 7ce04e1..4eb6cfb 100644 --- a/build.zig.zon.nix +++ b/build.zig.zon.nix @@ -151,6 +151,15 @@ copyFarm name [ unpack = true; }; } + { + name = "shrinkit-0.0.0-GRYwpSwGAwCjR5WiQiq-WDpC1NV9hvglB_UStLrqS4LN"; + path = fetchZigArtifact { + name = "shrinkit"; + url = "git+https://git.jcollie.dev/jeff/zig-shrinkit.git#227e1144a3b641dde19e09415077590b562f64d6"; + hash = "sha256-bjGaYLwOfkbHbihgV0B3RpPuHKsyjh/O2w1Yjh3w68Y="; + unpack = true; + }; + } { name = "uucode-0.2.0-ZZjBPlK5VADj7fdoq7G8LIHzD5o6FSkcBXXrRWr4jnrA"; path = fetchZigArtifact { diff --git a/src/diskfile.zig b/src/diskfile.zig index 39e5388..75ed0eb 100644 --- a/src/diskfile.zig +++ b/src/diskfile.zig @@ -22,10 +22,10 @@ const std = @import("std"); const disk2 = @import("disk2.zig"); const wozfmt = @import("woz.zig"); -const shrinkit = @import("shrinkit.zig"); +const shrinkit = @import("shrinkit"); const twomg = @import("twomg.zig"); -pub const Error = twomg.Error || shrinkit.Error || wozfmt.Error || std.mem.Allocator.Error; +pub const Error = twomg.Error || shrinkit.nufx.Error || wozfmt.Error || std.mem.Allocator.Error; /// A disk, and whatever had to be allocated to get at it. pub const Opened = struct { @@ -59,7 +59,7 @@ pub fn open(gpa: std.mem.Allocator, bytes: []u8, path: []const u8) Error!Opened .blocks = 0, } }; } - if (!shrinkit.looksLike(bytes)) { + if (!shrinkit.nufx.looksLike(bytes)) { var image = try twomg.openOrBare(bytes, path); // A bare file the size of a drive's own idea of a disk is a recording // of the surface rather than a description of the sectors on it. Only @@ -69,7 +69,7 @@ pub fn open(gpa: std.mem.Allocator, bytes: []u8, path: []const u8) Error!Opened return .{ .image = image }; } - const disk = try shrinkit.diskAlloc(gpa, bytes); + const disk = try shrinkit.nufx.diskAlloc(gpa, bytes); errdefer gpa.free(disk); return .{ .owned = disk, @@ -137,19 +137,19 @@ test "a ShrinkIt archive is unpacked, and what it gives back is owned" { var buffer: [1024]u8 = undefined; const disk = "a disk, as far as this is concerned"; @memset(&buffer, 0); - @memcpy(buffer[0..6], &shrinkit.magic); + @memcpy(buffer[0..6], &shrinkit.nufx.magic); std.mem.writeInt(u32, buffer[8..12], 1, .little); - const rec = shrinkit.master_header_size; - @memcpy(buffer[rec..][0..4], &shrinkit.record_magic); + const rec = shrinkit.nufx.master_header_size; + @memcpy(buffer[rec..][0..4], &shrinkit.nufx.record_magic); std.mem.writeInt(u16, buffer[rec + 6 ..][0..2], 60, .little); std.mem.writeInt(u16, buffer[rec + 8 ..][0..2], 3, .little); std.mem.writeInt(u32, buffer[rec + 0x0a ..][0..4], 1, .little); const th = rec + 60; - std.mem.writeInt(u16, buffer[th..][0..2], @intFromEnum(shrinkit.Class.data), .little); - std.mem.writeInt(u16, buffer[th + 4 ..][0..2], @intFromEnum(shrinkit.Kind.disk_image), .little); + std.mem.writeInt(u16, buffer[th..][0..2], @intFromEnum(shrinkit.nufx.Class.data), .little); + std.mem.writeInt(u16, buffer[th + 4 ..][0..2], @intFromEnum(shrinkit.nufx.Kind.disk_image), .little); std.mem.writeInt(u32, buffer[th + 8 ..][0..4], @intCast(disk.len), .little); std.mem.writeInt(u32, buffer[th + 12 ..][0..4], @intCast(disk.len), .little); - const at = th + shrinkit.thread_header_size; + const at = th + shrinkit.nufx.thread_header_size; @memcpy(buffer[at..][0..disk.len], disk); const file = buffer[0 .. at + disk.len]; diff --git a/src/root.zig b/src/root.zig index 06e5fdb..c653a1e 100644 --- a/src/root.zig +++ b/src/root.zig @@ -54,8 +54,10 @@ pub const wav = @import("wav.zig"); /// WOZ: a disk written down as the bits that go past the head. pub const woz = @import("woz.zig"); -/// ShrinkIt archives, which is how an Apple II disk usually arrives. -pub const shrinkit = @import("shrinkit.zig"); +/// ShrinkIt archives, which is how an Apple II disk usually arrives. The +/// user's own `zig-shrinkit` package: `shrinkit.nufx` reads one and +/// `shrinkit.writer` builds one, with the two LZW compressors in between. +pub const shrinkit = @import("shrinkit"); /// A disk out of whatever file somebody named, whichever of the three it is. pub const diskfile = @import("diskfile.zig"); diff --git a/src/shrinkit.zig b/src/shrinkit.zig deleted file mode 100644 index 273a9a2..0000000 --- a/src/shrinkit.zig +++ /dev/null @@ -1,1246 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie -// -// SPDX-License-Identifier: MIT - -//! ShrinkIt archives, which is how an Apple II disk usually arrives. -//! -//! Almost everything on the Apple II archives is a `.SHK` or a `.SDK` rather -//! than a disk image, because ShrinkIt is what people used: Andy Nicholas's -//! archiver from 1989, with compression by Kent Dickey, and the format it -//! writes is NuFX. A `.SDK` is a NuFX archive holding a whole disk; a `.SHK` -//! usually holds files, and sometimes holds a disk as well. Both are the same -//! format and this reads either, hands back the disk if there is one, and says -//! what is in the archive if there is not. A disk archive is also written back -//! to: `reArchive` rebuilds a single-record `.SDK` around a modified disk, so -//! that a machine's writes to it can be saved. See the note under the -//! compression, below, on why what it writes is uncompressed. -//! -//! An archive is a 48 byte master header and then a run of records, each of -//! which is a header, a filename and some number of *threads*. A thread is one -//! stream of bytes with a class saying what it is for — a filename, a comment, -//! a file's data fork, a disk image — and a format saying how it was squeezed. -//! Everything interesting here is the last of those. -//! -//! ## The compression -//! -//! Both of the formats worth reading are run-length encoding followed by LZW, -//! in four kilobyte chunks. Four kilobytes because a track of a 5.25-inch disk -//! is four kilobytes, and this began as a program for compressing disks; the -//! same reason every compressed stream begins with a byte holding a disk's -//! volume number, whether or not there is a disk anywhere near it. -//! -//! The RLE step turns a run into three bytes: a delimiter, the value, and the -//! count less one. The delimiter is named in the stream and is always `$db`. -//! A byte that happens to *be* the delimiter is written as a run of one, which -//! is why the step can make things bigger, and if it does the chunk is stored -//! as it was. -//! -//! The LZW step is ordinary LZW with codes nine to twelve bits wide, packed -//! low bit first, `$100` meaning "start the table again" and the first real -//! entry at `$101`. The width goes up one code *early* — when the next code to -//! be handed out reaches `2^width - 1` rather than `2^width` — which is the -//! one thing about it that no description says and that has to be read off a -//! real archive. -//! -//! The two formats differ only in what survives from one chunk to the next. -//! **LZW/1** starts each chunk fresh, and carries a CRC of the whole stream in -//! front of it. **LZW/2** keeps the table, the code width *and* the last code -//! across chunks, starting again only when the table fills or when a chunk -//! turned out not to be worth compressing. Getting that wrong is not obvious: -//! the first chunk decodes perfectly and everything after it is wrong. -//! -//! None of that is run in reverse. Writing a disk back (`reArchive`) emits an -//! *uncompressed* thread — a format NuFX allows and every reader, this one -//! included, accepts — rather than a DLZW compressor written only to make the -//! file smaller. The archive it produces is larger than the one it read but is -//! valid, and shrinking it again is a follow-up, not a correctness matter. -//! -//! ## The CRCs -//! -//! Both are CRC-16 with the `$1021` polynomial, and they are otherwise not the -//! same, which is worth knowing before spending an evening on it. A record of -//! version 3 carries a thread's CRC in the thread header, seeded `$ffff`, over -//! the file's own bytes. LZW/1 carries its own inside the stream, seeded zero, -//! over the bytes **padded out to a whole four kilobyte chunk** — because that -//! is what the compressor had in its buffer. A stream can therefore have one, -//! the other, both, or neither. Everything here checks whichever it is given. -//! -//! What is here was worked out against twenty-four real archives — nineteen -//! LZW/2 and five LZW/1 — and every one of them now checks against its own -//! CRC. - -const std = @import("std"); - -/// The six bytes at the front of an archive: "NuFile" with the high bit set on -/// every second letter. A NuFX file identifies itself twice over, since each -/// record repeats the trick with "NuFX". -pub const magic = [_]u8{ 'N', 0xf5, 'F', 0xe9, 'l', 0xe5 }; -pub const record_magic = [_]u8{ 'N', 0xf5, 'F', 0xd8 }; - -pub const master_header_size = 48; -pub const thread_header_size = 16; - -/// How big a chunk the compressors work in, which is a track of a 5.25-inch -/// disk and the reason for most of the format's shape. -pub const chunk_size = 4096; - -/// A Binary II file is 128 bytes of header and then whatever it wrapped, which -/// for anything here is a NuFX archive. Files named `.BXY` are these, and so -/// are a good many named `.SHK`. -pub const binary2_magic = [_]u8{ 0x0a, 0x47, 0x4c }; -pub const binary2_header_size = 128; - -/// What a thread is for. -pub const Class = enum(u16) { - message = 0, - control = 1, - data = 2, - filename = 3, - _, -}; - -/// Which of a file's parts a data thread is. A disk image is a thread like any -/// other, which is the whole reason a `.SDK` and a `.SHK` are the same format. -pub const Kind = enum(u16) { - data_fork = 0, - disk_image = 1, - resource_fork = 2, - _, -}; - -/// How a thread was squeezed. -pub const Format = enum(u16) { - /// Not at all. - none = 0, - /// Huffman, from the CP/M world. Rare, and nothing here reads it. - squeeze = 1, - /// Table restarted every chunk. - lzw1 = 2, - /// Table carried between chunks. - lzw2 = 3, - /// Unix `compress`, twelve and sixteen bit. GS/ShrinkIt could write these - /// and hardly ever did. - unix12 = 4, - unix16 = 5, - _, - - pub fn name(self: Format) []const u8 { - return switch (self) { - .none => "stored", - .squeeze => "squeezed", - .lzw1 => "LZW/1", - .lzw2 => "LZW/2", - .unix12 => "Unix compress, 12 bit", - .unix16 => "Unix compress, 16 bit", - _ => "some format this does not know", - }; - } -}; - -pub const Error = error{ - /// The file does not begin with a NuFX master header. - NotAnArchive, - /// It does, and then stops in the middle of something. - Truncated, - /// A thread is squeezed in a way nothing here reads. - UnsupportedFormat, - /// The archive is sound and holds no disk image. - NoDisk, - /// The disk came out and does not match the CRC the archive carries for - /// it, which means the archive is damaged or this is wrong. - BadCrc, - /// The compressed stream asks for something impossible: a code that was - /// never defined, or more bytes than it said it would produce. - Corrupt, - /// The archive holds more than the one disk this can rewrite, so writing - /// it back would drop the rest -- refused rather than done lossily. - Unwritable, -}; - -/// CRC-16 with the `$1021` polynomial, most significant bit first. -/// -/// The seed is the caller's business because this format uses two: `$ffff` for -/// the CRC in a thread header, and zero for the one LZW/1 keeps inside its own -/// stream. -pub fn crc16(seed: u16, data: []const u8) u16 { - var crc = seed; - for (data) |byte| { - crc ^= @as(u16, byte) << 8; - for (0..8) |_| { - crc = if (crc & 0x8000 != 0) (crc << 1) ^ 0x1021 else crc << 1; - } - } - return crc; -} - -/// One thread: what it is, how it was squeezed, and where its bytes are. -pub const Thread = struct { - class: Class, - format: Format, - kind: Kind, - /// What the data should come to. Zero means the archive is not saying, - /// which is allowed and common. - crc: u16, - /// How long the data is once unsqueezed, and how much of the file it takes - /// up squeezed. - eof: u32, - compressed: u32, - /// Where in the archive the squeezed bytes start. - at: usize, - - /// Whether this is the thread a disk lives in. - pub fn isDisk(self: Thread) bool { - return self.class == .data and self.kind == .disk_image; - } -}; - -/// One record, which is one file or one disk. -pub const Record = struct { - version: u16, - file_type: u32, - /// For a disk, how many blocks; for a file, the auxiliary type. - extra_type: u32, - /// For a disk, how big a block is; for a file, how it is stored. - storage_type: u16, - /// The name in the record's own field, which later versions leave empty - /// and put in a thread instead. - name: []const u8, - threads_at: usize, - threads: u32, - /// Where the record's data ends, which is where the next record begins. - end: usize, - - pub fn thread(self: Record, bytes: []const u8, which: u32) Error!Thread { - if (which >= self.threads) return error.Truncated; - const at = self.threads_at + thread_header_size * which; - if (at + thread_header_size > bytes.len) return error.Truncated; - // Every thread's data follows the whole array of thread headers, one - // after another in order, so where this one's bytes are is the sum of - // what came before it. - var data_at = self.threads_at + thread_header_size * self.threads; - for (0..which) |before| { - data_at += read(u32, bytes, self.threads_at + thread_header_size * before + 12); - } - return .{ - .class = @enumFromInt(read(u16, bytes, at)), - .format = @enumFromInt(read(u16, bytes, at + 2)), - .kind = @enumFromInt(read(u16, bytes, at + 4)), - .crc = read(u16, bytes, at + 6), - .eof = read(u32, bytes, at + 8), - .compressed = read(u32, bytes, at + 12), - .at = data_at, - }; - } -}; - -fn read(comptime T: type, bytes: []const u8, at: usize) T { - const size = @sizeOf(T); - if (at + size > bytes.len) return 0; - return std.mem.readInt(T, bytes[at..][0..size], .little); -} - -/// An archive, opened far enough to walk. -pub const Archive = struct { - bytes: []const u8, - /// Where the first record is, which is past the Binary II wrapper if there - /// was one. - from: usize, - records: u32, - - /// Reads the record at `at`, and says where the next one starts. - pub fn record(self: Archive, at: usize) Error!Record { - const bytes = self.bytes; - if (at + 4 > bytes.len or !std.mem.eql(u8, bytes[at..][0..4], &record_magic)) - return error.Truncated; - - const attributes = read(u16, bytes, at + 6); - const version = read(u16, bytes, at + 8); - const threads = read(u32, bytes, at + 0x0a); - if (attributes < 2 or at + attributes > bytes.len) return error.Truncated; - - // The record header runs to `attributes` bytes, the last two of which - // are the length of the filename that follows it. Threads start after - // that. A version 3 record leaves the name empty and puts it in a - // thread of its own instead, which is why this is so often nothing. - const name_len = read(u16, bytes, at + attributes - 2); - const name_at = at + attributes; - if (name_at + name_len > bytes.len) return error.Truncated; - - const threads_at = name_at + name_len; - const headers_end = threads_at + thread_header_size * threads; - if (headers_end > bytes.len) return error.Truncated; - - var end = headers_end; - for (0..threads) |t| { - end += read(u32, bytes, threads_at + thread_header_size * t + 12); - } - if (end > bytes.len) return error.Truncated; - - return .{ - .version = version, - .file_type = read(u32, bytes, at + 0x16), - .extra_type = read(u32, bytes, at + 0x1a), - .storage_type = read(u16, bytes, at + 0x1e), - .name = bytes[name_at..][0..name_len], - .threads_at = threads_at, - .threads = threads, - .end = end, - }; - } -}; - -/// Opens an archive, or says the file is not one. -/// -/// A Binary II wrapper is stepped over rather than refused: it is 128 bytes of -/// ProDOS attributes in front of the archive, and a file with one is still the -/// archive it wraps. -pub fn open(bytes: []const u8) Error!Archive { - var from: usize = 0; - if (bytes.len >= binary2_header_size and - std.mem.eql(u8, bytes[0..3], &binary2_magic) and bytes[18] == 0x02) - { - from = binary2_header_size; - } - if (bytes.len < from + master_header_size) return error.NotAnArchive; - if (!std.mem.eql(u8, bytes[from..][0..6], &magic)) return error.NotAnArchive; - return .{ - .bytes = bytes, - .from = from + master_header_size, - .records = read(u32, bytes, from + 8), - }; -} - -/// Whether this looks like something to open, without committing to it. -pub fn looksLike(bytes: []const u8) bool { - _ = open(bytes) catch return false; - return true; -} - -/// The first disk image in the archive, and which record it was in. -pub fn findDisk(archive: Archive) Error!struct { Record, Thread } { - var at = archive.from; - for (0..archive.records) |_| { - const rec = try archive.record(at); - for (0..rec.threads) |t| { - const th = try rec.thread(archive.bytes, @intCast(t)); - if (th.isDisk()) return .{ rec, th }; - } - at = rec.end; - } - return error.NoDisk; -} - -/// What the archive holds, for saying so when it holds no disk. -pub const Listing = struct { - files: u32 = 0, - disks: u32 = 0, - /// The name of the first thing in it, which is usually enough to recognise - /// an archive by. - first: []const u8 = "", -}; - -/// Walks the archive and counts what is in it. -/// -/// The name is taken from the filename thread when there is one, since a -/// version 3 record leaves its own name field empty. -pub fn list(archive: Archive) Error!Listing { - var out: Listing = .{}; - var at = archive.from; - for (0..archive.records) |_| { - const rec = try archive.record(at); - var name = rec.name; - var is_disk = false; - for (0..rec.threads) |t| { - const th = try rec.thread(archive.bytes, @intCast(t)); - if (th.class == .filename and th.format == .none and name.len == 0) { - const end = @min(th.at + th.eof, archive.bytes.len); - if (th.at <= end) name = archive.bytes[th.at..end]; - } - if (th.isDisk()) is_disk = true; - } - if (is_disk) out.disks += 1 else out.files += 1; - if (out.first.len == 0) out.first = name; - at = rec.end; - } - return out; -} - -/// Reads a thread's bytes into `into`, which must be `thread.eof` long. -/// -/// The CRC is checked when the archive gave one, which is the only way to know -/// this worked: a wrong decompressor does not usually fail, it just produces -/// something else. -pub fn unpack(archive: Archive, thread: Thread, into: []u8) Error!void { - if (into.len != thread.eof) return error.Corrupt; - const end = thread.at + thread.compressed; - if (end > archive.bytes.len) return error.Truncated; - const data = archive.bytes[thread.at..end]; - - switch (thread.format) { - .none => { - if (data.len < into.len) return error.Truncated; - @memcpy(into, data[0..into.len]); - }, - .lzw1 => try unpackLzw(.lzw1, data, into), - .lzw2 => try unpackLzw(.lzw2, data, into), - else => return error.UnsupportedFormat, - } - - // A version 3 record puts the CRC in the thread header, seeded $ffff, over - // the bytes as they are. Zero means the archive did not say. - if (thread.crc != 0 and crc16(0xffff, into) != thread.crc) return error.BadCrc; -} - -/// The disk in the archive, decompressed. -/// -/// Allocated rather than pointed at, since the whole point is that the bytes -/// in the file are not the bytes of the disk. The caller owns what comes back. -pub fn diskAlloc(gpa: std.mem.Allocator, bytes: []const u8) (Error || std.mem.Allocator.Error)![]u8 { - const archive = try open(bytes); - const found = try findDisk(archive); - const record, const thread = found; - - // How long the disk is, which the format manages to say twice. The - // thread's own length is the one to trust; the record's block count times - // its block size is a cross-check, and ShrinkIt versions disagreed about - // both often enough that the file type note says so. - var length: usize = thread.eof; - if (length == 0) length = @as(usize, record.extra_type) * record.storage_type; - if (length == 0) return error.Corrupt; - - const out = try gpa.alloc(u8, length); - errdefer gpa.free(out); - try unpack(archive, thread, out); - return out; -} - -/// Builds a new archive holding `disk`, taking the name and file type from the -/// archive `disk` came out of. This is how a disk written back to a `.SHK` or -/// `.SDK` goes home: the thread is stored uncompressed rather than squeezed -- -/// a valid NuFX that any reader takes, just larger than the original, since -/// nothing here writes ShrinkIt's own compression. The caller owns the result. -/// -/// Only an archive of a single record is rewritten; one holding more than the -/// disk is refused (`error.Unwritable`) rather than rebuilt with the rest of -/// it thrown away. -pub fn reArchive(gpa: std.mem.Allocator, original: []const u8, disk: []const u8) (Error || std.mem.Allocator.Error)![]u8 { - const archive = try open(original); - if (archive.records != 1) return error.Unwritable; - const record, _ = try findDisk(archive); - - // The disk's name: the record's own field, or its filename thread when a - // version 3 record left the field empty. - var name = record.name; - if (name.len == 0) { - for (0..record.threads) |t| { - const th = try record.thread(original, @intCast(t)); - if (th.class == .filename and th.format == .none) { - const end = @min(th.at + th.eof, original.len); - if (th.at <= end) name = original[th.at..end]; - break; - } - } - } - return archiveDisk(gpa, name, record.file_type, disk); -} - -/// Builds a single-record NuFX archive around `disk`, with one stored -/// (uncompressed) disk-image thread named `name` and typed `file_type`. This -/// is what `reArchive` writes once it has read those two from the original, -/// and it is what a test uses to make a `.SDK` from a bare disk image without -/// an archive to start from. The caller owns the result. -pub fn archiveDisk( - gpa: std.mem.Allocator, - name: []const u8, - file_type: u32, - disk: []const u8, -) std.mem.Allocator.Error![]u8 { - const capped = if (name.len > 0xffff) name[0..0xffff] else name; - - const record_header = 60; // through the two-byte filename length at 0x3a - const record_at = master_header_size; - const name_at = record_at + record_header; - const threads_at = name_at + capped.len; - const data_at = threads_at + thread_header_size; - const total = data_at + disk.len; - - const buf = try gpa.alloc(u8, total); - errdefer gpa.free(buf); - @memset(buf, 0); - - // Master header: the magic, one record, and the total size. - @memcpy(buf[0..6], &magic); - std.mem.writeInt(u32, buf[8..12], 1, .little); - std.mem.writeInt(u32, buf[38..42], @intCast(total), .little); - - // Record header: the disk's type and geometry, the name in its own field. - @memcpy(buf[record_at..][0..4], &record_magic); - std.mem.writeInt(u16, buf[record_at + 6 ..][0..2], record_header, .little); // attribute count - std.mem.writeInt(u16, buf[record_at + 8 ..][0..2], 3, .little); // version - std.mem.writeInt(u32, buf[record_at + 10 ..][0..4], 1, .little); // one thread - std.mem.writeInt(u16, buf[record_at + 14 ..][0..2], 1, .little); // ProDOS file system - std.mem.writeInt(u32, buf[record_at + 18 ..][0..4], 0xe3, .little); // access: unlocked - std.mem.writeInt(u32, buf[record_at + 0x16 ..][0..4], file_type, .little); - std.mem.writeInt(u32, buf[record_at + 0x1a ..][0..4], @intCast(disk.len / 512), .little); // blocks - std.mem.writeInt(u16, buf[record_at + 0x1e ..][0..2], 512, .little); // block size - std.mem.writeInt(u16, buf[record_at + 58 ..][0..2], @intCast(capped.len), .little); - @memcpy(buf[name_at..][0..capped.len], capped); - - // The one thread: the disk, stored, with the CRC the reader checks. - std.mem.writeInt(u16, buf[threads_at..][0..2], @intFromEnum(Class.data), .little); - std.mem.writeInt(u16, buf[threads_at + 2 ..][0..2], @intFromEnum(Format.none), .little); - std.mem.writeInt(u16, buf[threads_at + 4 ..][0..2], @intFromEnum(Kind.disk_image), .little); - std.mem.writeInt(u16, buf[threads_at + 6 ..][0..2], crc16(0xffff, disk), .little); - std.mem.writeInt(u32, buf[threads_at + 8 ..][0..4], @intCast(disk.len), .little); - std.mem.writeInt(u32, buf[threads_at + 12 ..][0..4], @intCast(disk.len), .little); - @memcpy(buf[data_at..][0..disk.len], disk); - - // The header and master CRCs, which this reader does not check but other - // tools do: each over the bytes after its own two-byte field. - std.mem.writeInt(u16, buf[record_at + 4 ..][0..2], crc16(0xffff, buf[record_at + 6 .. data_at]), .little); - std.mem.writeInt(u16, buf[6..8], crc16(0xffff, buf[8..master_header_size]), .little); - - return buf; -} - -/// Which of the two chunked formats a stream is. -const Chunked = enum { lzw1, lzw2 }; - -/// The LZW dictionary, and the reading of a chunk's worth of codes out of it. -/// -/// Kept as one thing because LZW/2 carries all of it from one chunk to the -/// next — the table, the width, and the code before this one — and the whole -/// difference between the two formats is which parts survive. -const Lzw = struct { - /// Every code above `$100` is a code before it and one byte after, which - /// is the whole of the dictionary. Four thousand of them is the most - /// twelve bits can name. - prefix: [4096]u16 = undefined, - suffix: [4096]u8 = undefined, - /// How many entries have been made. The next one to be handed out is - /// `first_code + count`. - count: u16 = 0, - /// How many bits a code is now, which grows with the table. - width: u4 = 9, - /// The code before this one, and nothing at the start of a stream. - previous: ?u16 = null, - - const clear_code: u16 = 0x100; - const first_code: u16 = 0x101; - const max_width: u4 = 12; - - fn reset(self: *Lzw) void { - self.count = 0; - self.width = 9; - self.previous = null; - } - - /// Whether the next code needs another bit. - /// - /// One code early — at `2^width - 1` rather than `2^width` — which is the - /// detail no description of this format states and which a real archive - /// settles in one attempt: read it the other way and the first chunk still - /// decodes perfectly and everything after it is wrong. - /// - /// It only looks early from this side. A decoder learns its entry from the - /// code *before* the one it is reading, so its table is always one behind - /// the encoder's; growing one code early is what keeps the two counting - /// the same. From the encoder's side the rule is the ordinary one, which - /// is presumably why nobody writing the format down thought to mention it. - fn grow(self: *Lzw) void { - self.growAt(1); - } - - /// The same, `behind` codes later, which is what an encoder wants. - fn growAt(self: *Lzw, behind: u16) void { - while (self.width < max_width and - first_code + self.count + behind >= @as(u16, 1) << self.width) - { - self.width += 1; - } - } - - /// Writes the bytes a code stands for, and returns how many there were. - /// - /// A code names a code and a byte, so the string comes out backwards and - /// is turned round. The buffer is a chunk long because nothing longer can - /// be needed: a code cannot stand for more than the chunk it was learned - /// in. - fn expand(self: *const Lzw, code: u16, into: *[chunk_size]u8) Error!usize { - var walk = code; - var len: usize = 0; - while (walk >= first_code) { - const index = walk - first_code; - if (index >= self.count or len >= into.len) return error.Corrupt; - into[len] = self.suffix[index]; - len += 1; - walk = self.prefix[index]; - } - if (walk > 0xff or len >= into.len) return error.Corrupt; - into[len] = @intCast(walk); - len += 1; - std.mem.reverse(u8, into[0..len]); - return len; - } - - fn learn(self: *Lzw, prefix: u16, suffix: u8) void { - if (self.count >= self.prefix.len) return; - self.prefix[self.count] = prefix; - self.suffix[self.count] = suffix; - self.count += 1; - } -}; - -/// Codes packed low bit first, which is the other thing a real archive has to -/// settle: read most significant bit first and the very first code of a stream -/// is already impossible. -const Bits = struct { - data: []const u8, - at: usize = 0, - bit: u3 = 0, - - fn take(self: *Bits, width: u4) ?u16 { - var value: u16 = 0; - for (0..width) |i| { - if (self.at >= self.data.len) return null; - const one: u16 = (self.data[self.at] >> self.bit) & 1; - value |= one << @intCast(i); - if (self.bit == 7) { - self.bit = 0; - self.at += 1; - } else self.bit += 1; - } - return value; - } - - /// How many bytes have been touched, which is where the next chunk starts - /// in a format that does not say. - fn used(self: Bits) usize { - return self.at + @as(usize, if (self.bit != 0) 1 else 0); - } -}; - -/// Turns a chunk's run-length encoding back into the four kilobytes it stands -/// for: a delimiter, the value, and the count less one. -fn expandRuns(data: []const u8, delimiter: u8, into: []u8) Error!usize { - var out: usize = 0; - var at: usize = 0; - while (at < data.len) { - if (data[at] != delimiter) { - if (out >= into.len) return error.Corrupt; - into[out] = data[at]; - out += 1; - at += 1; - continue; - } - if (at + 2 >= data.len) return error.Corrupt; - const value = data[at + 1]; - const count = @as(usize, data[at + 2]) + 1; - if (out + count > into.len) return error.Corrupt; - @memset(into[out..][0..count], value); - out += count; - at += 3; - } - return out; -} - -/// Unsqueezes a whole thread of either chunked format. -/// -/// The two are the same walk with different bookkeeping, so they are one -/// function: what differs is the four bytes in front, the shape of each -/// chunk's header, and whether anything survives from one chunk to the next. -fn unpackLzw(comptime which: Chunked, data: []const u8, into: []u8) Error!void { - var at: usize = 0; - var delimiter: u8 = 0xdb; - var stated_crc: ?u16 = null; - - switch (which) { - .lzw1 => { - // A CRC of the whole stream, a volume number, and the delimiter. - if (data.len < 4) return error.Truncated; - stated_crc = std.mem.readInt(u16, data[0..2], .little); - delimiter = data[3]; - at = 4; - }, - .lzw2 => { - // A volume number and the delimiter. The CRC moved to the thread - // header when this format was introduced. - if (data.len < 2) return error.Truncated; - delimiter = data[1]; - at = 2; - }, - } - - var lzw: Lzw = .{}; - var chunk: [chunk_size]u8 = undefined; - var packed_chunk: [chunk_size * 2]u8 = undefined; - var run_crc: u16 = 0; - var done: usize = 0; - - while (done < into.len) { - // How long the chunk is after the run-length step, and whether LZW was - // used on top of that. Four kilobytes means the runs did not help and - // the chunk is the plain bytes. - var after_runs: usize = 0; - var used_lzw = false; - var chunk_end: ?usize = null; - - switch (which) { - .lzw1 => { - if (at + 3 > data.len) return error.Truncated; - after_runs = std.mem.readInt(u16, data[at..][0..2], .little); - used_lzw = data[at + 2] != 0; - at += 3; - }, - .lzw2 => { - if (at + 2 > data.len) return error.Truncated; - const header = std.mem.readInt(u16, data[at..][0..2], .little); - after_runs = header & 0x1fff; - used_lzw = header & 0x8000 != 0; - if (used_lzw) { - if (at + 4 > data.len) return error.Truncated; - const total = std.mem.readInt(u16, data[at + 2 ..][0..2], .little); - if (total < 4 or at + total > data.len) return error.Truncated; - chunk_end = at + total; - at += 4; - } else { - at += 2; - } - }, - } - if (after_runs > packed_chunk.len) return error.Corrupt; - - const squeezed: []const u8 = if (used_lzw) blk: { - // LZW/1 starts every chunk with an empty table; LZW/2 keeps what - // it learned, and with it the code width and the code before this - // one. - if (which == .lzw1) lzw.reset(); - - const from = if (chunk_end) |e| data[at..e] else data[at..]; - var bits: Bits = .{ .data = from }; - var out: usize = 0; - var string: [chunk_size]u8 = undefined; - - while (out < after_runs) { - const code = bits.take(lzw.width) orelse return error.Truncated; - if (code == Lzw.clear_code) { - lzw.reset(); - continue; - } - var len: usize = undefined; - if (code < Lzw.clear_code) { - string[0] = @intCast(code); - len = 1; - } else if (code - Lzw.first_code < lzw.count) { - len = try lzw.expand(code, &string); - } else if (lzw.previous) |previous| { - // The one case a code can name itself: the string it is - // about to stand for, followed by its own first byte. - len = try lzw.expand(previous, &string); - if (len >= string.len) return error.Corrupt; - string[len] = string[0]; - len += 1; - } else return error.Corrupt; - - if (out + len > packed_chunk.len) return error.Corrupt; - @memcpy(packed_chunk[out..][0..len], string[0..len]); - out += len; - - if (lzw.previous) |previous| lzw.learn(previous, string[0]); - lzw.previous = code; - lzw.grow(); - } - if (out < after_runs) return error.Corrupt; - at = chunk_end orelse (at + bits.used()); - break :blk packed_chunk[0..after_runs]; - } else blk: { - // Not compressed, and so nothing to learn from: LZW/2 starts again - // after a chunk it could not squeeze. - if (at + after_runs > data.len) return error.Truncated; - lzw.reset(); - const stored = data[at..][0..after_runs]; - at += after_runs; - break :blk stored; - }; - - // And the runs, unless there were none to put back. - const length = if (after_runs < chunk_size) - try expandRuns(squeezed, delimiter, &chunk) - else length: { - @memcpy(chunk[0..squeezed.len], squeezed); - break :length squeezed.len; - }; - if (length != chunk_size) return error.Corrupt; - - // The last chunk is a whole chunk with nothing much at the end of it, - // since the compressor filled its buffer with zeroes before starting. - // The CRC LZW/1 carries covers that padding, because that is what was - // in front of the compressor; the one in the thread header does not. - run_crc = crc16(run_crc, &chunk); - const wanted = @min(chunk_size, into.len - done); - @memcpy(into[done..][0..wanted], chunk[0..wanted]); - done += wanted; - } - - if (stated_crc) |wanted| { - if (run_crc != wanted) return error.BadCrc; - } -} - -const testing = std.testing; - -test "the two CRCs are the same polynomial and not the same number" { - // Both are $1021 and most significant bit first; the seed is the whole of - // the difference, and using one where the other belongs is a mistake that - // costs an evening. - const data = "123456789"; - try testing.expectEqual(@as(u16, 0x31c3), crc16(0x0000, data)); - try testing.expectEqual(@as(u16, 0x29b1), crc16(0xffff, data)); -} - -test "runs come back as the bytes they stand for" { - var out: [64]u8 = undefined; - - // A delimiter, the value, and the count less one — so $db $a0 $05 is six - // high-ASCII spaces, which is what a directory full of padding looks like. - const length = try expandRuns(&.{ 'h', 0xdb, 0xa0, 0x05, 'i' }, 0xdb, &out); - try testing.expectEqualStrings("h\xa0\xa0\xa0\xa0\xa0\xa0i", out[0..length]); - - // A run of one is how a byte that happens to be the delimiter is written, - // which is why the step can make a chunk longer than it started. - const escaped = try expandRuns(&.{ 0xdb, 0xdb, 0x00 }, 0xdb, &out); - try testing.expectEqualSlices(u8, &.{0xdb}, out[0..escaped]); - - // And the longest run there is: a count byte of $ff means 256, which is - // the count less one and is why a run cannot be 257 bytes. - var big: [512]u8 = undefined; - const longest = try expandRuns(&.{ 0xdb, 0x00, 0xff }, 0xdb, &big); - try testing.expectEqual(@as(usize, 256), longest); -} - -test "a run that would not fit is refused rather than written past the end" { - var out: [4]u8 = undefined; - try testing.expectError(error.Corrupt, expandRuns(&.{ 0xdb, 0x00, 0xff }, 0xdb, &out)); - // And a delimiter with nothing after it. - try testing.expectError(error.Corrupt, expandRuns(&.{ 'a', 0xdb }, 0xdb, &out)); -} - -test "codes are packed low bit first" { - // Which is the first thing a real archive settles: taken the other way - // round, the first nine bits of a stream come to $1b1, and a stream cannot - // open with a code that nothing has defined. - var bits: Bits = .{ .data = &.{ 0xd8, 0xd0, 0x34 } }; - try testing.expectEqual(@as(u16, 0xd8), bits.take(9).?); - try testing.expectEqual(@as(usize, 2), bits.used()); - - // And it runs out rather than reading off the end of the stream. - var short: Bits = .{ .data = &.{0x00} }; - try testing.expectEqual(@as(?u16, null), short.take(9)); -} - -test "the code width goes up one code early" { - var lzw: Lzw = .{}; - try testing.expectEqual(@as(u4, 9), lzw.width); - - // Nine bits name codes up to $1ff, and the width goes up when the *next* - // code to be handed out reaches $1ff rather than $200. The first entry is - // $101, so that is after $fe of them. - while (Lzw.first_code + lzw.count < 0x1fe) lzw.learn(0, 0); - lzw.grow(); - try testing.expectEqual(@as(u4, 9), lzw.width); - lzw.learn(0, 0); - lzw.grow(); - try testing.expectEqual(@as(u4, 10), lzw.width); - - // And it stops at twelve, which is as wide as a code gets. - while (lzw.count < 4095) lzw.learn(0, 0); - lzw.grow(); - try testing.expectEqual(@as(u4, 12), lzw.width); -} - -test "a code stands for the code before it and one byte" { - var lzw: Lzw = .{}; - var into: [chunk_size]u8 = undefined; - - // $101 is "A" then "B", and $102 is that then "C". - lzw.learn('A', 'B'); - lzw.learn(0x101, 'C'); - try testing.expectEqual(@as(usize, 2), try lzw.expand(0x101, &into)); - try testing.expectEqualStrings("AB", into[0..2]); - try testing.expectEqual(@as(usize, 3), try lzw.expand(0x102, &into)); - try testing.expectEqualStrings("ABC", into[0..3]); - - // A plain byte is itself, and a code nobody defined is refused rather than - // read out of whatever happened to be in the table. - try testing.expectEqual(@as(usize, 1), try lzw.expand('Z', &into)); - try testing.expectError(error.Corrupt, lzw.expand(0x103, &into)); -} - -/// Builds an archive around one thread, for the tests that want a whole file. -fn testArchive( - into: []u8, - class: Class, - format: Format, - kind: Kind, - crc: u16, - eof: u32, - data: []const u8, -) []u8 { - @memset(into, 0); - @memcpy(into[0..6], &magic); - std.mem.writeInt(u32, into[8..12], 1, .little); // one record - std.mem.writeInt(u16, into[0x1c..0x1e], 2, .little); // master version - - const rec = master_header_size; - @memcpy(into[rec..][0..4], &record_magic); - std.mem.writeInt(u16, into[rec + 6 ..][0..2], 60, .little); // attribute count - std.mem.writeInt(u16, into[rec + 8 ..][0..2], 3, .little); // record version - std.mem.writeInt(u32, into[rec + 0x0a ..][0..4], 1, .little); // one thread - std.mem.writeInt(u32, into[rec + 0x1a ..][0..4], 280, .little); // blocks - std.mem.writeInt(u16, into[rec + 0x1e ..][0..2], 512, .little); // block size - // The last two bytes of the header are the length of the name after it. - std.mem.writeInt(u16, into[rec + 58 ..][0..2], 0, .little); - - const th = rec + 60; - std.mem.writeInt(u16, into[th..][0..2], @intFromEnum(class), .little); - std.mem.writeInt(u16, into[th + 2 ..][0..2], @intFromEnum(format), .little); - std.mem.writeInt(u16, into[th + 4 ..][0..2], @intFromEnum(kind), .little); - std.mem.writeInt(u16, into[th + 6 ..][0..2], crc, .little); - std.mem.writeInt(u32, into[th + 8 ..][0..4], eof, .little); - std.mem.writeInt(u32, into[th + 12 ..][0..4], @intCast(data.len), .little); - - const at = th + thread_header_size; - @memcpy(into[at..][0..data.len], data); - std.mem.writeInt(u32, into[0x26..0x2a], @intCast(at + data.len), .little); - return into[0 .. at + data.len]; -} - -test "an archive says how many records it has and where they are" { - var buffer: [256]u8 = undefined; - const file = testArchive(&buffer, .data, .none, .disk_image, 0, 8, "12345678"); - - const archive = try open(file); - try testing.expectEqual(@as(u32, 1), archive.records); - try testing.expectEqual(@as(usize, master_header_size), archive.from); - - const rec = try archive.record(archive.from); - try testing.expectEqual(@as(u16, 3), rec.version); - try testing.expectEqual(@as(u32, 1), rec.threads); - try testing.expectEqual(@as(u32, 280), rec.extra_type); - try testing.expectEqual(@as(u16, 512), rec.storage_type); - - const thread = try rec.thread(file, 0); - try testing.expect(thread.isDisk()); - try testing.expectEqual(Format.none, thread.format); - try testing.expectEqual(@as(u32, 8), thread.eof); -} - -test "a file that is not an archive says so" { - var bare: [256]u8 = @splat(0); - try testing.expectError(error.NotAnArchive, open(&bare)); - try testing.expect(!looksLike(&bare)); - - // Too short to hold a master header at all. - try testing.expectError(error.NotAnArchive, open("NuFile")); -} - -test "a Binary II wrapper is stepped over rather than refused" { - // A .BXY is 128 bytes of ProDOS attributes and then the archive, and a - // good many files named .SHK are one. - var buffer: [512]u8 = undefined; - var inner: [256]u8 = undefined; - const file = testArchive(&inner, .data, .none, .disk_image, 0, 4, "disk"); - - @memset(&buffer, 0); - @memcpy(buffer[0..3], &binary2_magic); - buffer[18] = 0x02; - @memcpy(buffer[binary2_header_size..][0..file.len], file); - - const archive = try open(buffer[0 .. binary2_header_size + file.len]); - try testing.expectEqual(@as(usize, binary2_header_size + master_header_size), archive.from); - const rec, const thread = try findDisk(archive); - _ = rec; - try testing.expectEqual(@as(u32, 4), thread.eof); -} - -test "the disk comes out of a stored thread" { - var buffer: [1024]u8 = undefined; - const disk = "a disk, as far as this is concerned"; - const file = testArchive( - &buffer, - .data, - .none, - .disk_image, - crc16(0xffff, disk), - @intCast(disk.len), - disk, - ); - - const out = try diskAlloc(testing.allocator, file); - defer testing.allocator.free(out); - try testing.expectEqualStrings(disk, out); -} - -test "a wrong CRC is an error rather than a disk full of noise" { - var buffer: [1024]u8 = undefined; - const disk = "a disk, as far as this is concerned"; - const file = testArchive(&buffer, .data, .none, .disk_image, 0x1234, @intCast(disk.len), disk); - try testing.expectError(error.BadCrc, diskAlloc(testing.allocator, file)); -} - -test "an archive of files says it has no disk in it" { - // Which is what most .SHK files are: ShrinkIt was an archiver first and a - // disk copier second, and telling somebody their archive holds files is - // more use than failing to open it. - var buffer: [1024]u8 = undefined; - const file = testArchive(&buffer, .data, .none, .data_fork, 0, 5, "hello"); - - const archive = try open(file); - try testing.expectError(error.NoDisk, findDisk(archive)); - try testing.expectError(error.NoDisk, diskAlloc(testing.allocator, file)); - - const listing = try list(archive); - try testing.expectEqual(@as(u32, 1), listing.files); - try testing.expectEqual(@as(u32, 0), listing.disks); -} - -test "a format nothing here reads is refused by name" { - var buffer: [1024]u8 = undefined; - const file = testArchive(&buffer, .data, .squeeze, .disk_image, 0, 8, "squeezed"); - try testing.expectError(error.UnsupportedFormat, diskAlloc(testing.allocator, file)); - try testing.expectEqualStrings("squeezed", Format.squeeze.name()); -} - -test "a truncated archive is refused rather than read past" { - var buffer: [1024]u8 = undefined; - const file = testArchive(&buffer, .data, .none, .disk_image, 0, 64, "short"); - // The thread says it holds sixty-four bytes and five were written. - try testing.expectError(error.Truncated, diskAlloc(testing.allocator, file)); -} - -/// One chunk of LZW/2, as ShrinkIt would write it for data that neither step -/// could improve: the runs made it no smaller, so the chunk is stored. -fn storedChunk(into: []u8, data: []const u8) []u8 { - into[0] = 0x00; // volume - into[1] = 0xdb; // delimiter - std.mem.writeInt(u16, into[2..4], @intCast(data.len), .little); - @memcpy(into[4..][0..data.len], data); - return into[0 .. 4 + data.len]; -} - -/// The run-length step, the way ShrinkIt does it: four or more of the same -/// byte become a delimiter, the value and the count less one, and a byte that -/// happens to be the delimiter is written as a run of one. -/// -/// Only the tests need this — nothing here writes an archive — but a decoder -/// tested against its own encoder over real-looking data is worth more than -/// one tested against three bytes typed out by hand. -fn packRuns(data: []const u8, delimiter: u8, into: []u8) usize { - var out: usize = 0; - var at: usize = 0; - while (at < data.len) { - var run: usize = 1; - while (at + run < data.len and data[at + run] == data[at] and run < 256) run += 1; - if (run > 3 or data[at] == delimiter) { - into[out] = delimiter; - into[out + 1] = data[at]; - into[out + 2] = @intCast(run - 1); - out += 3; - at += run; - } else { - into[out] = data[at]; - out += 1; - at += 1; - } - } - return out; -} - -test "a stored chunk of LZW/2 is the bytes it holds, runs put back" { - var packed_bytes: [chunk_size * 2]u8 = undefined; - var stream: [chunk_size * 3]u8 = undefined; - - // Four kilobytes of a disk: mostly zeroes, some text, and a run of high - // ASCII spaces, which is roughly what the front of a ProDOS volume looks - // like and exactly the shape the run-length step was written for. - var expected: [chunk_size]u8 = @splat(0); - @memcpy(expected[512..][0..6], "PRODOS"); - @memset(expected[600..][0..40], 0xa0); - expected[700] = 0xdb; // the delimiter itself, which has to be escaped - - const length = packRuns(&expected, 0xdb, &packed_bytes); - try testing.expect(length < chunk_size); // or ShrinkIt would have stored it - - const data = storedChunk(&stream, packed_bytes[0..length]); - var out: [chunk_size]u8 = undefined; - try unpackLzw(.lzw2, data, &out); - try testing.expectEqualSlices(u8, &expected, &out); -} - -test "a chunk the runs could not shrink is stored as it stands" { - // Four kilobytes with nothing repeated in it: the run-length step would - // make it longer, so ShrinkIt writes the bytes and says the length is a - // whole chunk, which is how a decoder knows not to expand anything. - var expected: [chunk_size]u8 = undefined; - for (&expected, 0..) |*byte, i| byte.* = @intCast((i *% 7) & 0xff); - // Nothing that could be mistaken for a run marker. - for (&expected) |*byte| { - if (byte.* == 0xdb) byte.* = 0xdc; - } - - var stream: [chunk_size * 3]u8 = undefined; - const data = storedChunk(&stream, &expected); - var out: [chunk_size]u8 = undefined; - try unpackLzw(.lzw2, data, &out); - try testing.expectEqualSlices(u8, &expected, &out); -} - -/// The LZW step, the way the decoder above expects to find it. -/// -/// Only the tests use this. It is worth being clear about what a round trip -/// through it does and does not prove: an encoder written to match a decoder -/// agrees with it whether or not either matches ShrinkIt. What settles that is -/// real archives, and the two dozen this was built against all check out -/// against their own CRCs. What this catches is the next change to the decoder -/// quietly breaking the code width or the packing. -fn packLzw(data: []const u8, into: []u8) usize { - var out: usize = 0; - var bit: u3 = 0; - var lzw: Lzw = .{}; - // The encoder's table, looked up the slow way, which is fine for a test. - var previous: ?u16 = null; - - const put = struct { - fn code(buffer: []u8, at: *usize, shift: *u3, width: u4, value: u16) void { - for (0..width) |i| { - if (shift.* == 0) buffer[at.*] = 0; - const one: u8 = @intCast((value >> @intCast(i)) & 1); - buffer[at.*] |= one << shift.*; - if (shift.* == 7) { - shift.* = 0; - at.* += 1; - } else shift.* += 1; - } - } - }.code; - - for (data) |byte| { - if (previous) |prefix| { - // Is prefix+byte already known? - var found: ?u16 = null; - for (0..lzw.count) |i| { - if (lzw.prefix[i] == prefix and lzw.suffix[i] == byte) { - found = @intCast(Lzw.first_code + i); - break; - } - } - if (found) |code| { - previous = code; - continue; - } - put(into, &out, &bit, lzw.width, prefix); - lzw.learn(prefix, byte); - // The ordinary rule, not the decoder's: this side is the one that - // is a code ahead. - lzw.growAt(0); - } - previous = byte; - } - if (previous) |last| put(into, &out, &bit, lzw.width, last); - if (bit != 0) out += 1; - return out; -} - -test "an LZW chunk goes round and comes back the same" { - // Long enough and varied enough to run the table past 254 entries, which - // is where the code width first goes up and where getting it wrong stops - // being invisible. - var original: [chunk_size]u8 = undefined; - var seed: u32 = 12345; - for (&original, 0..) |*byte, i| { - seed = seed *% 1103515245 +% 12345; - // Repetitive enough for LZW to learn from, varied enough to fill the - // table: runs of a few bytes drawn from a small alphabet. - byte.* = if (i % 7 < 3) @intCast((seed >> 16) & 0x1f) else @intCast(i & 0x3f); - } - - var coded: [chunk_size * 2]u8 = undefined; - const length = packLzw(&original, &coded); - - // Wrapped as one LZW/2 chunk: volume, delimiter, then the chunk's header - // saying how long it is after the run-length step — which here is the - // whole chunk, since nothing was run-length encoded — and that LZW was - // used, and how long the whole thing is. - var stream: [chunk_size * 3]u8 = undefined; - stream[0] = 0x00; - stream[1] = 0xdb; - std.mem.writeInt(u16, stream[2..4], 0x8000 | chunk_size, .little); - std.mem.writeInt(u16, stream[4..6], @intCast(4 + length), .little); - @memcpy(stream[6..][0..length], coded[0..length]); - - var out: [chunk_size]u8 = undefined; - try unpackLzw(.lzw2, stream[0 .. 6 + length], &out); - try testing.expectEqualSlices(u8, &original, &out); -} - -test "a code that names itself is the one case LZW has to be told about" { - // The encoder can emit a code it is defining in the same breath, when the - // string repeats immediately: "aaaa" out of "a" alone. A decoder that does - // not handle it reads a code that is not in its table yet. - var original: [chunk_size]u8 = @splat('a'); - @memset(original[0..16], 'b'); - - var coded: [chunk_size * 2]u8 = undefined; - const length = packLzw(&original, &coded); - - var stream: [chunk_size * 3]u8 = undefined; - stream[0] = 0x00; - stream[1] = 0xdb; - std.mem.writeInt(u16, stream[2..4], 0x8000 | chunk_size, .little); - std.mem.writeInt(u16, stream[4..6], @intCast(4 + length), .little); - @memcpy(stream[6..][0..length], coded[0..length]); - - var out: [chunk_size]u8 = undefined; - try unpackLzw(.lzw2, stream[0 .. 6 + length], &out); - try testing.expectEqualSlices(u8, &original, &out); -} - -test "a disk written back to an archive comes out of it again" { - const gpa = testing.allocator; - var block: [512]u8 = @splat(0xa5); - var buffer: [1024]u8 = undefined; - const file = testArchive(&buffer, .data, .none, .disk_image, 0, 512, &block); - - // Unpack it, change it, and write it back into a fresh archive. - const disk = try diskAlloc(gpa, file); - defer gpa.free(disk); - try testing.expectEqual(@as(u8, 0xa5), disk[0]); - disk[0] = 0x5a; - disk[511] = 0x42; - - const rebuilt = try reArchive(gpa, file, disk); - defer gpa.free(rebuilt); - - // The result re-opens, and the disk comes back with the change on it. - const back = try diskAlloc(gpa, rebuilt); - defer gpa.free(back); - try testing.expectEqual(@as(usize, 512), back.len); - try testing.expectEqual(@as(u8, 0x5a), back[0]); - try testing.expectEqual(@as(u8, 0x42), back[511]); - - // The thread carries a real CRC over the stored bytes, which the reader - // checks -- a wrong one would have been refused. - const archive = try open(rebuilt); - _, const thread = try findDisk(archive); - try testing.expectEqual(crc16(0xffff, back), thread.crc); -} - -test "an archive of more than one record is refused for writing" { - const gpa = testing.allocator; - var block: [512]u8 = @splat(0); - var buffer: [1024]u8 = undefined; - const file = testArchive(&buffer, .data, .none, .disk_image, 0, 512, &block); - std.mem.writeInt(u32, buffer[8..12], 2, .little); // claim a second record - var disk: [512]u8 = @splat(0); - try testing.expectError(error.Unwritable, reArchive(gpa, file, &disk)); -} diff --git a/src/system_tests.zig b/src/system_tests.zig index b153d5e..490a125 100644 --- a/src/system_tests.zig +++ b/src/system_tests.zig @@ -52,7 +52,7 @@ const dos33 = @import("dos33.zig"); const pascal = @import("pascal.zig"); const woz = @import("woz.zig"); const writeback = @import("writeback.zig"); -const shrinkit = @import("shrinkit.zig"); +const shrinkit = @import("shrinkit"); const scsi = @import("scsi.zig"); /// The two catalogues, under the home directory: one of ROMs, one of disk and @@ -922,7 +922,7 @@ test "an Apple IIgs writes a file to a disk that came out of a ShrinkIt archive, { const source = try diskfile.open(alloc, source_file, "system.2mg"); defer source.deinit(alloc); - const sdk = try shrinkit.archiveDisk(alloc, "SYSTEM", 0, source.image.data); + const sdk = try shrinkit.writer.diskAlloc(alloc, .{ .name = "SYSTEM", .data = source.image.data }, .{}); defer alloc.free(sdk); try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = sdk }); } @@ -969,7 +969,7 @@ test "an Apple IIgs writes a file to a disk that came out of a ShrinkIt archive, // that comes out of it has the file the machine wrote. const back_out = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, alloc, .limited(writeback.file_limit)); defer alloc.free(back_out); - _ = try shrinkit.open(back_out); + _ = try shrinkit.nufx.open(back_out); const reopened = try diskfile.open(alloc, back_out, path); defer reopened.deinit(alloc); diff --git a/src/writeback.zig b/src/writeback.zig index e6885b9..91a6e44 100644 --- a/src/writeback.zig +++ b/src/writeback.zig @@ -21,7 +21,7 @@ const disk35 = @import("disk35.zig"); const diskfile = @import("diskfile.zig"); const twomg = @import("twomg.zig"); const woz = @import("woz.zig"); -const shrinkit = @import("shrinkit.zig"); +const shrinkit = @import("shrinkit"); /// How big a disk file is allowed to be. The largest thing any of these /// drives reads, plus room for a wrapper. @@ -59,7 +59,7 @@ fn replace( // failure there -- an archive holding more than the one disk -- is a // refusal, the same as a disk that did not match. if (opened.owned) |disk| { - const archived = shrinkit.reArchive(alloc, file, disk) catch return error.NotTheSameDisk; + const archived = reArchive(alloc, file, disk) catch return error.NotTheSameDisk; defer alloc.free(archived); return moveIntoPlace(io, alloc, path, archived); } @@ -71,6 +71,25 @@ fn replace( return moveIntoPlace(io, alloc, path, file); } +/// Rebuilds a single-record archive around a disk written back to it, taking +/// the disk's name and block size from the archive it came out of. The +/// `zig-shrinkit` writer squeezes it the way ShrinkIt did -- LZW/2 by default +/// -- so the file that goes home is about the size of the one that came in, +/// not the larger stored copy this used to write. +/// +/// Only an archive of a single record is rewritten; one holding more than the +/// disk is refused rather than rebuilt with the rest of it thrown away. +fn reArchive(alloc: std.mem.Allocator, original: []const u8, disk: []const u8) ![]u8 { + const archive = try shrinkit.nufx.open(original); + if (archive.records != 1) return error.Unwritable; + const record, _ = try shrinkit.nufx.findDisk(archive); + return shrinkit.writer.diskAlloc(alloc, .{ + .name = record.filename(original), + .data = disk, + .block_size = if (record.storage_type == 0) 512 else record.storage_type, + }, .{}); +} + /// Writes `contents` beside `path` and moves it over the top. pub fn moveIntoPlace(io: std.Io, alloc: std.mem.Allocator, path: []const u8, contents: []const u8) Error!void { const temporary = std.fmt.allocPrint(alloc, "{s}.tmp", .{path}) catch return error.CannotWrite; @@ -227,3 +246,46 @@ test "a disk written back keeps the wrapper it came in" { try testing.expectEqualStrings("2IMG", back[0..4]); try testing.expectEqualStrings("BLOCK", back[header..][0..5]); } + +test "a disk written back to an archive keeps its change and stays a NuFX" { + const alloc = testing.allocator; + + // A small disk, and a `.SDK` around it the way a source archive comes. + const original = try alloc.alloc(u8, 512 * 4); + defer alloc.free(original); + @memset(original, 0); + @memcpy(original[0..5], "FIRST"); + const sdk = try shrinkit.writer.diskAlloc(alloc, .{ .name = "MYDISK", .data = original }, .{}); + defer alloc.free(sdk); + + // What the machine wrote onto it instead. + const changed = try alloc.dupe(u8, original); + defer alloc.free(changed); + @memcpy(changed[0..5], "AFTER"); + + const rebuilt = try reArchive(alloc, sdk, changed); + defer alloc.free(rebuilt); + + // One record still, the name kept, and the disk inside it is the change. + const archive = try shrinkit.nufx.open(rebuilt); + try testing.expectEqual(@as(u32, 1), archive.records); + const record, _ = try shrinkit.nufx.findDisk(archive); + try testing.expectEqualStrings("MYDISK", record.filename(rebuilt)); + const back = try shrinkit.nufx.diskAlloc(alloc, rebuilt); + defer alloc.free(back); + try testing.expectEqualSlices(u8, changed, back); +} + +test "an archive holding more than the disk is refused rather than rebuilt lossily" { + const alloc = testing.allocator; + + var builder: shrinkit.writer.Builder = .init(alloc, .{}); + defer builder.deinit(); + const disk = [_]u8{0} ** 512; + try builder.addDisk(.{ .name = "DISK", .data = &disk }); + try builder.addFile(.{ .name = "NOTES", .data = "and a file beside it" }); + const multi = try builder.toOwnedSlice(); + defer alloc.free(multi); + + try testing.expectError(error.Unwritable, reArchive(alloc, multi, &disk)); +}