A Rust engine behind a SwiftUI app
Why the part of Peel that touches hostile bytes is Rust, and what it costs to hand it to Swift.
An archive is a pile of bytes a stranger made. Somewhere in that pile is a header field announcing how long something is, and the easy way to write a reader is to believe it: to trust the file's own account of itself. Feed that kind of reader a length no honest file would ever claim and the naive version doesn't show an error; it reaches past the end of what it actually has and falls over. No dialog, only a process that was there and then wasn't.
Once you've watched that happen a few times, you stop thinking of the engine as "the part that does archive things" and start thinking of it as "the part that reads strangers' bytes." Those need different furniture.
The three crates
Peel is a Cargo workspace with three crates, and the split is the most useful decision in the whole codebase.
- **
peel-core** is the engine. Detection, listing, extraction, the safety policy, creating archives, recovery. Every format lives here, one module per format family. It has no idea a window exists. - **
peel-cli** builds thepeelcommand-line tool and, in the same binary, an MCP server. - **
peel-ffi** builds a C-callable library. The Quick Look, Spotlight and PeelFS extensions load or link it and call into the engine in-process. The app also drives the bundledpeelbinary for extraction.
The app side is SwiftUI, plus a small Swift wrapper (PeelFfi.swift) around the C interface so the rest of the code never sees a raw pointer, and a shared Swift package, PeelKit, for everything else the app and extensions have in common. For the extensions the chain, top to bottom, is: Swift wrapper, C ABI, engine.
I'll say up front that this isn't a language war. Swift is the right tool for everything the user can see, and I wouldn't want to build the UI in anything else on a Mac. The question was only what to put underneath it.
Why Rust under the UI
Three reasons, in the order they actually mattered to me.
Untrusted input. An archive is a file somebody else made, and a reader's job is to follow lengths, offsets and counts that the file itself supplies. That's the textbook shape of a memory-safety bug. In Rust, the ordinary mistake (an index past the end) becomes a panic or a returned error instead of a read from somewhere it shouldn't. It doesn't make a parser correct, and I'll spend the next article on how I try to make them correct. But it changes the failure from "undefined behaviour in a process that may hold your files" to "a loud, local, catchable failure." For code whose entire input is adversarial, I wanted that default.
Performance without ceremony. Decompression is tight loops over bytes, and some of the formats I read are unusually demanding. Rust gives me predictable performance, real threads, and control over allocation without a garbage collector to schedule around. When extraction has to share a disk budget across several writer threads, or a seek-capable decoder has to avoid re-reading a stream, I'm describing it to the compiler, not negotiating with a runtime.
The ecosystem, and the freedom to leave it. Plenty of codecs and container formats already have solid Rust crates, and I use them where they hold up. Where they don't, I've vendored or patched a crate, and for the oldest and strangest formats I wrote readers myself. Having one language for both "pull in a library" and "write a bit-level decoder from a spec" is quietly valuable.
One more reason sits outside those three: the engine runs inside other people's processes. Quick Look and Spotlight load it into system-managed hosts, with time and size limits and no patience for a crash. That raised the bar on how the library behaves when something goes wrong, which leads to the boundary.
The boundary
The C ABI is the awkward part, and I'd rather describe the awkwardness than pretend it away.
The shape I settled on is deliberately boring. Functions take C strings and small structs, and they return heap-allocated UTF-8 strings of JSON. The Swift side decodes the JSON into proper types. Whatever the engine returns, the caller frees with one dedicated call. It isn't elegant, but it's debuggable: I can print what crossed the boundary and read it.
Some of the details that took thought:
- A panic must not cross it. Unwinding out of an
extern "C"function aborts the process, which is the exact vanishing act I started this post with, now in a Quick Look host. So each export runs its body inside a guard that catches a panic and turns it into an ordinary error result. The caller reports "couldn't read this archive" and carries on. This is the single most important line of defensive code in the FFI crate. - Errors are data, not exceptions. Errors come back as JSON whose
errorfield is one of the engine's error kinds (damaged, wrong password, unsupported, not enough space, cancelled, and so on) plus a detail string meant for logs, not for people. The UI decides the wording. That way "wrong password" and "corrupt file" can look different to the user without Swift parsing a message. - Cancellation is cooperative and explicit. A long extraction needs to stop when someone presses Cancel, even in the middle of one huge entry. The engine polls a cancel flag, and the FFI exposes cancel tokens the caller can create, trip and free. Ownership of that little object is on the Swift side, which is another place the boundary asks for care.
- Passwords get their own path. There are dedicated exports that take a password, copy it once, wipe the engine's copy when the call returns, and never log it. The older route through an environment variable still exists for compatibility, but I avoid it, because mutating the environment of a running process is a worse place to keep a secret than an argument.
- The header is checked. The C header and the Rust exports are two descriptions of one interface, and they drift. There's a script that compares names and signatures between them, and it runs in the release gate, because a mismatch there fails at runtime in a way you don't enjoy debugging.
What's still awkward: JSON across the boundary means every call serializes and parses, which is fine for listing and extraction and would be wrong for something chatty. Memory ownership rules (who frees what) live in documentation and discipline rather than in a type system that spans both languages. And I have to keep two mental models, Swift's and Rust's, for what "a string" is. I accept all of that. The alternative of a richer binding layer would be more code to get wrong at precisely the place where I most want less.
What you get almost for free
Here is the accident I'm happiest about. Once the engine is a library with no UI assumptions, a command-line tool is a thin shell around it. peel lists, inspects, extracts and creates archives from a terminal, with the same detection and the same safety policy the app uses, because it's the same code.
# illustrative
peel list backup.7z
peel inspect mystery.bin
peel cat archive.zip notes/todo.txt
That tool turned out to be the best test harness I own. A bug report that says "this file looks wrong in the app" becomes a one-line command I can run in a loop, diff, and script, without launching a window. It also lets me work on the engine without touching the Finder session I'm using for everything else.
The MCP server came from the same place. peel mcp speaks the Model Context Protocol over stdio, so any client that speaks it can inspect an archive, list entries, read a single member, and extract or create within folders it has been explicitly allowed to touch. It exposes the engine's operations with typed inputs, and that's about all there is to it. Extraction and creation are confined to allowed roots, and creating never overwrites unless asked. I didn't design a second product. I put a protocol in front of functions that already existed, and the work was mostly deciding what to refuse.
I'm wary of overselling it. It's a convenience and a good forcing function: if an operation is awkward to expose cleanly over a CLI or a protocol, it was probably tangled into the UI in a way worth fixing.
What I'd tell myself at the start
Keep the engine ignorant of the app. Every time I've been tempted to let a UI concept leak into the core (a selection, a progress view, a window), it has cost me later, in the CLI, in the extensions, or in tests.
Keep the boundary dull. JSON strings, one free function, errors as data, panics caught at the door. Cleverness at an FFI boundary is a debt that the other side collects.
And be honest about what Rust does and doesn't buy. It turned my vanishing-app bug into an error message, which is a real improvement, but it didn't make my readers right. A decoder written in a safe language can still decode the wrong bytes, cleanly, with no complaint. Safety kept the process alive. Correctness is a separate problem, and the next post is about that one.
Peel is free for macOS 13 or later. Get Peel, or install it with brew install --cask snackstudio/tap/peel.
Next in the series: Exactness gates: keeping an archive reader honest