Guides

Embed in Swift

Link libpeel_ffi, wrap the C calls in one small Swift file, and list, read and extract archives in-process with typed errors and cancellation.

Peel 1.4.0 · Snack Studio · Updated

Peel’s Mac app calls Rind this way. The engine runs inside your process, so there is no child process to start and no output to parse. Every call takes paths, returns a JSON string, and is synchronous. If you would rather not link a library, run the peel command from Swift and read its JSON instead (see Scripts and CI).

Repository access needed to build. The engine source is private, so libpeel_ffi and include/peel.h come from a checkout of the Peel repository. The released library is not published as a package. Peel.app carries its own copy at Contents/Frameworks/libpeel_ffi.dylib, for the app’s use.

From a checkout, build it. This is the same command the C library page uses:

TerminalShell
cargo build --release -p peel-ffi
# target/release/libpeel_ffi.a   target/release/libpeel_ffi.dylib   include/peel.h

include/ holds only peel.h. To import it from Swift, add a module map beside it:

include/module.modulemapText
module CPeel {
    header "peel.h"
    export *
}

Then compile with the include folder on the import path. Dynamic:

TerminalShell
swiftc -parse-as-library Rind.swift Demo.swift -I include \
  -L target/release -lpeel_ffi -Xlinker -rpath -Xlinker $PWD/target/release -o demo

Static:

TerminalShell
swiftc -parse-as-library Rind.swift Demo.swift -I include \
  target/release/libpeel_ffi.a -lz -lbz2 -llzma -lc++ -liconv -o demo

Both lines built and ran the examples below. The dylib records its build path as its install name, so to ship it beside your program run install_name_tool -id @rpath/libpeel_ffi.dylib libpeel_ffi.dylib and link with -Wl,-rpath,@executable_path. In an Xcode project you can instead put #import "peel.h" in a bridging header; the module map above was the only route tested here.

Who frees what

The rules are the C library’s. In Swift they become three habits.

You receive Free it with
char * from any function peel_string_free
unsigned char * from a member read peel_bytes_free(ptr, len)
PeelSession * peel_session_close
PeelCancelToken * peel_cancel_token_free, after the call has returned
A file descriptor from peel_read_member_fd close, or let a FileHandle do it

Never use free(). The memory comes from Rust’s allocator. Put the free in a defer the moment you hold the pointer, copy the bytes into a String or Data, and let the pointer go. Strings you pass in are borrowed for the call only, which is what withCString gives you.

Errors and decoding

A string-returning call returns either its result or {"error": "<kind>", "detail": "…"}. The kinds are the same on every surface; see Errors. Model them as an enum, and let anything unknown fall back to other:

Rind.swiftkinds, errors and result typesSwift
import CPeel
import Foundation

/// The error kinds Rind reports. Unknown kinds map to `.other`.
enum RindErrorKind: String {
    case damaged, wrongPassword = "wrong_password", passwordRequired = "password_required"
    case notEnoughSpace = "not_enough_space", unsupported
    case permissionDenied = "permission_denied", decompressionBomb = "decompression_bomb"
    case tooLarge = "too_large", cancelled, io, notFound = "not_found"
    case invalidName = "invalid_name", unsafeEntry = "unsafe_entry"
    case alreadyExists = "already_exists", other, panic
}

struct RindError: Error {
    let kind: RindErrorKind
    let detail: String          // engine text: log it, never show it
}

private struct ErrorBody: Decodable {
    let error: String
    let detail: String?
}

struct Entry: Decodable {
    let name: String
    let size: UInt64
    let isDir: Bool
    enum CodingKeys: String, CodingKey { case name, size, isDir = "is_dir" }
}

struct Listing: Decodable {
    let entries: [Entry]
    let maxEntries: UInt32
    let truncated: Bool
    enum CodingKeys: String, CodingKey { case entries, truncated, maxEntries = "max_entries" }
}

struct ExtractResult: Decodable {
    let format: String
    let destination: String
    let extracted: [String]
    let skipped: [String]
}

peel_list returns a bare array. peel_list_limited and its variants return an object with entries, max_entries, truncated and path, so Listing above matches the second. peel_extract_with_password returns format, destination, extracted, skipped and sources; the type above keeps four of them.

not_enough_space adds needed and available, and too_large adds size and max (for one member). Decode them as optional fields if you want to show them. Show people your own sentence for each kind. detail is the engine’s text: it can hold paths and member names, so log it privately and keep it out of the interface.

The helpers that take a string, check for an error and free it:

Rind.swiftownership helpersSwift
/// Takes ownership of a string the engine returned: decode it, then free it.
private func take<T: Decodable>(_ type: T.Type, _ raw: UnsafeMutablePointer<CChar>?) throws -> T {
    guard let raw else { throw RindError(kind: .other, detail: "no result") }
    defer { peel_string_free(raw) }
    let data = Data(bytes: raw, count: strlen(raw))
    if let body = try? JSONDecoder().decode(ErrorBody.self, from: data) {
        throw RindError(kind: RindErrorKind(rawValue: body.error) ?? .other, detail: body.detail ?? "")
    }
    return try JSONDecoder().decode(T.self, from: data)
}

/// The error JSON from an out-parameter, freed, as a Swift error.
private func takeError(_ raw: UnsafeMutablePointer<CChar>?) -> RindError {
    guard let raw else { return RindError(kind: .other, detail: "no error text") }
    defer { peel_string_free(raw) }
    let body = try? JSONDecoder().decode(ErrorBody.self, from: Data(bytes: raw, count: strlen(raw)))
    return RindError(kind: RindErrorKind(rawValue: body?.error ?? "") ?? .other, detail: body?.detail ?? "")
}

/// `body` with a C string for `s`, or with NULL for nil.
private func withOptionalCString<R>(_ s: String?, _ body: (UnsafePointer<CChar>?) throws -> R) rethrows -> R {
    guard let s else { return try body(nil) }
    return try s.withCString(body)
}

takeError does the same for the error out-parameter that session and descriptor calls fill. A panic inside the engine never unwinds into your process. It comes back as the panic kind, which means that archive could not be read.

Passwords

Use the *_with_password functions. They take the password as UTF-8, copy it once, wipe their copy before returning, and never read the environment. Pass nil for none. The older calls (peel_extract, peel_extract_to, peel_read_member and others) still read PEEL_PASSWORD; do not set it, because any process of the same user can read your environment.

A Swift String cannot be wiped, so keep the password’s lifetime short: fetch it when you call, pass it, drop it. The wrapper below takes password: String? on every call. A wrong password and a missing one are different kinds, so you can ask again only when it is wrong.

Cancel with a Task

A PeelCancelToken stops one call and only that call. Call peel_cancel_token_cancel from any thread; the call returns cancelled and leaves no partial file. The engine call blocks, so run it on a dispatch queue and let Task cancellation flip the token:

Rind.swiftthe token and the async bridgeSwift
/// One cancel token for one call. Freed when the last reference goes,
/// which is after the call has returned because the call closure holds it.
final class CancelToken: @unchecked Sendable {
    fileprivate let raw: OpaquePointer = peel_cancel_token_new()
    func cancel() { peel_cancel_token_cancel(raw) }
    deinit { peel_cancel_token_free(raw) }
}

/// Run a blocking engine call off the caller's thread; cancelling the Task
/// cancels the token, which stops the call.
func cancellable<T: Sendable>(_ work: @escaping @Sendable (CancelToken) throws -> T) async throws -> T {
    let token = CancelToken()
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { cont in
            DispatchQueue.global(qos: .userInitiated).async {
                cont.resume(with: Result { try work(token) })
            }
        }
    } onCancel: {
        token.cancel()
    }
}

The token is a class so that its deinit frees it. Both the work closure and the onCancel closure hold a reference, so it outlives the call. Each call gets its own token; never share one between two calls.

The process-wide flag (peel_cancel, peel_cancel_clear) stops anything that has no token of its own, so avoid it in a library. If you call peel_extract_entry, which does not clear the flag, call peel_cancel_clear() first.

List and extract

Rind.swiftlist and extractSwift
enum Rind {
    static func list(_ path: String, maxEntries: UInt32 = 10_000, password: String? = nil) async throws -> Listing {
        try await cancellable { token in
            try path.withCString { p in
                try withOptionalCString(password) { pw in
                    try take(Listing.self, peel_list_limited_with_password(p, maxEntries, token.raw, pw))
                }
            }
        }
    }

    static func extract(_ path: String, to destination: String, password: String? = nil) throws -> ExtractResult {
        try path.withCString { p in
            try destination.withCString { d in
                try withOptionalCString(password) { pw in
                    // collision 2 = rename, enclosing 0 = when_needed
                    try take(ExtractResult.self, peel_extract_with_password(p, d, 2, 0, pw))
                }
            }
        }
    }
}

collision 2 renames, and enclosing 0 adds an enclosing folder only when the archive needs one. The other values are 0=error 1=overwrite 2=rename 3=skip and 0=when_needed 1=always 2=never. peel_extract takes the same three fields as a PeelPolicy struct, which Swift can build once the header is imported. Extraction applies Rind’s safety rules: an entry that climbs out of the destination is refused before anything is written.

Read one member

To read several members of one archive, open it once. A ZIP keeps its directory in memory, so each read skips the open and the scan. If the file changes after the session opened, reads fail with an io error instead of answering from a stale index; open a new session.

Rind.swifta sessionSwift
/// An archive opened once for many reads.
final class RindSession: @unchecked Sendable {
    fileprivate let raw: OpaquePointer

    init(_ path: String, password: String? = nil) throws {
        var err: UnsafeMutablePointer<CChar>?
        let s = path.withCString { p in withOptionalCString(password) { pw in peel_session_open(p, pw, &err) } }
        guard let s else { throw takeError(err) }
        raw = s
    }

    deinit { peel_session_close(raw) }

    /// One member in memory. `maxBytes` of 0 means no cap.
    func read(_ member: String, maxBytes: UInt64, token: CancelToken? = nil) throws -> Data {
        var len = 0
        var err: UnsafeMutablePointer<CChar>?
        let buf = member.withCString { m in
            withExtendedLifetime(token) {
                peel_session_read_member(raw, m, maxBytes, token?.raw, &len, &err)
            }
        }
        guard let buf else { throw takeError(err) }
        defer { peel_bytes_free(buf, len) }
        return Data(bytes: buf, count: len)   // copies; an empty member gives an empty Data
    }
}

maxBytes caps the member size accepted; 0 means no cap, and a larger member is too_large. A symlink is not read (unsupported). Names containing .. or a leading / are refused. An empty member gives a non-NULL pointer and a length of 0, which becomes empty Data.

For a window of a member, peel_session_read_member_range returns bytes [offset, offset + length). The size comes back when the format records it before the data and is UInt64.max otherwise. A compressed member is decoded from its start, so a deep offset costs the read up to it. Memory is bounded by length, which must be 1 to 1 GiB.

Rind.swifta ranged readSwift
extension RindSession {
    /// Bytes [offset, offset + length) of one member, and the member's size
    /// when the format records it before the data.
    func read(_ member: String, offset: UInt64, length: UInt64) throws -> (data: Data, totalSize: UInt64?) {
        var len = 0
        var total: UInt64 = 0
        var err: UnsafeMutablePointer<CChar>?
        let buf = member.withCString { m in
            peel_session_read_member_range(raw, m, offset, length, nil, &len, &total, &err)
        }
        guard let buf else { throw takeError(err) }
        defer { peel_bytes_free(buf, len) }
        return (Data(bytes: buf, count: len), total == UInt64.max ? nil : total)
    }
}

To a file descriptor

peel_read_member_fd decrypts or inflates one member into an unnamed file and returns an open descriptor at byte 0, close-on-exec. No path ever names it, so no other process can open it, but you can hand it to one. It reads one archive by path; it does not use a session.

Rind.swifta descriptorSwift
/// One member as an open descriptor on an unlinked file. The handle closes it.
func readMemberFD(_ path: String, member: String, maxBytes: UInt64, password: String? = nil) throws -> FileHandle {
    var err: UnsafeMutablePointer<CChar>?
    let fd = path.withCString { p in
        member.withCString { m in
            withOptionalCString(password) { pw in peel_read_member_fd(p, m, maxBytes, nil, pw, &err) }
        }
    }
    guard fd >= 0 else { throw takeError(err) }
    return FileHandle(fileDescriptor: fd, closeOnDealloc: true)
}

FileHandle(fileDescriptor:closeOnDealloc:) takes ownership. To write the member somewhere, read the handle in chunks (read(upToCount:)) into a file you created; the descriptor is not a path, so you cannot move it.

Threading

Run it

This is the program that exercised everything above. It runs in a folder holding the demo files demo.zip, locked.zip, hostile.zip and photos.7z.

Demo.swiftSwift
import Foundation

@main struct Demo {
    static func main() async {
        do {
            let listing = try await Rind.list("demo.zip")
            for e in listing.entries where !e.isDir { print(e.name, e.size) }

            let session = try RindSession("demo.zip")
            let data = try session.read("project/src/main.rs", maxBytes: 1 << 20)
            print(String(decoding: data, as: UTF8.self), terminator: "")
            let part = try session.read("project/src/main.rs", offset: 3, length: 4)
            print(String(decoding: part.data, as: UTF8.self), part.totalSize as Any)

            let handle = try readMemberFD("demo.zip", member: "project/README.md", maxBytes: 0)
            print((try handle.readToEnd() ?? Data()).count, "bytes through the descriptor")

            do { _ = try session.read("nope.txt", maxBytes: 0) }
            catch let e as RindError { print("kind:", e.kind) }
            do { _ = try Rind.extract("locked.zip", to: "out", password: "wrong") }
            catch let e as RindError { print("kind:", e.kind) }
            do { _ = try Rind.extract("hostile.zip", to: "out") }
            catch let e as RindError { print("kind:", e.kind) }

            let task = Task {
                while !Task.isCancelled { await Task.yield() }   // wait until we are cancelled
                return try await Rind.list("photos.7z")
            }
            task.cancel()
            do { _ = try await task.value }
            catch let e as RindError { print("kind:", e.kind) }
        } catch {
            print("failed:", error)
        }
    }
}
OutputText
project/README.md 47
project/docs/chapter-1.md 5411
project/docs/chapter-2.md 5411
project/docs/chapter-3.md 5411
project/docs/chapter-4.md 5411
project/docs/chapter-5.md 5411
project/docs/chapter-6.md 5411
project/src/main.rs 37
fn main() {
    println!("hello");
}
main Optional(37)
47 bytes through the descriptor
kind: notFound
kind: wrongPassword
kind: unsafeEntry
kind: cancelled

The cancelled task never calls the engine until it has been cancelled, so the output is the same on every run. A real caller cancels from a button or a timeout, and the call stops within one read buffer.

How Peel does it

Peel’s own code is the reference for what survives contact with a shipping app.

Next: the full function list is on the C library page, the error kinds on Errors, and the Rust crate on the Rust library page.