Rust library

The peel-core API in the order you use it: detect, inspect, extract, read a member, open a session, create, verify and recover.

Peel 1.4.0 · Snack Studio · Updated

peel-core is the engine as a Rust crate. Functions take paths and return typed values; results that you might send over the wire (ArchiveSummary, TestReport, RecoveryAssessment, ExtractResult) derive serde::Serialize. Add the dependency as shown on Install.

Everything below is re-exported at the crate root: use peel_core::…. Errors are peel_core::PeelError, with a stable .kind() and a .report() that serialises as {"error", "detail"}. peel_core::Result<T> is the matching alias.

Understand an archive

Rust
use peel_core::{
    capabilities_for, detect_format, inspect_archive, list_archive, ResourceBudget,
};
use std::path::Path;

let path = Path::new("upload.zip");

let format = detect_format(path)?;                       // Format::Zip
let caps = capabilities_for(format);                     // what Rind can do with it

let summary = inspect_archive(path, &ResourceBudget::default())?;
for e in &summary.entries {
    println!("{:<8} {:>10}  {}", format!("{:?}", e.kind), e.size.unwrap_or(0), e.name);
}

let listing = list_archive(path)?;                       // Vec<ArchiveEntry>: name, is_dir, size
FunctionReturns
detect_format(&Path)Format: sniffed from content, not the extension. detect_bytes(&[u8]) does the same for a buffer.
inspect_archive(&Path, &ResourceBudget)ArchiveSummary: format, format_family, zip_kind, entries: Vec<ArchiveEntryInfo>, total_uncompressed_bytes, total_compressed_bytes, has_encrypted_entries, comment, is_solid. entry_count() is a convenience. inspect_bytes takes a buffer.
list_archive(&Path)Vec<ArchiveEntry>. Also list_archive_with_password, list_archive_limited (stops at a count and says whether it was cut short) and list_archive_expanded.
capabilities_for(Format)FormatCapabilities: support level for list, extract, create, password and multipart, plus notes. all_format_capabilities() lists every format.

Each ArchiveEntryInfo has name, kind (File, Dir or Symlink), size, compressed_size, is_encrypted and, when the format records them, modified_unix, mode, uid, gid, symlink_target, compression_method and crc32. A missing optional field means the format does not carry it.

Extract

peel(archive, &policy) extracts everything and extract_archive is the same call under its longer name. Both take an ExtractPolicy.

Rust
use peel_core::{peel, Collision, EnclosingDirectory, ExtractPolicy, ResourceBudget, Secret};

let policy = ExtractPolicy {
    destination: Some("out".into()),                 // default: beside the archive
    collision: Collision::Rename,                    // Error | Overwrite | Rename | Skip
    enclosing_directory: EnclosingDirectory::WhenNeeded, // | Always | Never
    password: None,                                  // Option<Secret>
    budget: ResourceBudget::default(),               // entry, size and path-length limits
    selection: Some(vec!["docs/*.md".into()]),       // None = everything
    delete_source: false,
    expand_payload: true,                            // .pkg Payload and Scripts
};
let result = peel(path, &policy)?;                   // ExtractResult
println!("{} written, {} skipped", result.extracted.len(), result.skipped.len());

ExtractPolicy::default() renames on collision, adds an enclosing folder only when the archive needs one, and uses the default ResourceBudget. Set the fields you care about and use ..ExtractPolicy::default() for the rest. ExtractPolicy::overwrite() is a shortcut for replacing existing files.

Progress and cancellation

extract_archive_with_hooks takes ExtractHooks: a CancelFlag you can set from another thread, and a callback that receives ProgressEvents. A cancelled extract returns PeelError::Cancelled and leaves nothing behind.

Rust
use peel_core::{extract_archive_with_hooks, CancelFlag, ExtractHooks, ExtractPolicy};

let cancel = CancelFlag::new();
let c2 = cancel.clone();
std::thread::spawn(move || { /* …user pressed Stop… */ c2.cancel(); });

let mut on_progress = |ev| eprintln!("{ev:?}");
let hooks = ExtractHooks { cancel: Some(&cancel), on_progress: Some(&mut on_progress) };
extract_archive_with_hooks(path, &ExtractPolicy::default(), hooks)?;

Read one member

FunctionUse
extract_entry(archive, name, dest_dir, max_bytes, password, &cancelled)Write one entry, by its exact listed name, under dest_dir. Returns EntryRead::File or EntryRead::Symlink. max_bytes == 0 means no cap. A failed or cancelled read leaves no file behind.
read_entry_bytes(archive, name, max_bytes, password, &cancelled)Read one entry into memory. Returns EntryBytes::Data { data } or EntryBytes::Symlink { target }. Most formats need no scratch file.
read_entry_range(archive, name, offset, length, password, &cancelled)Read bytes [offset, offset + length) of one entry. Returns EntryRangeBytes::Data { data, total_size } or EntryRangeBytes::Symlink { target }; fewer bytes than asked means the entry ended. length is at most MAX_RANGE_BYTES (1 GiB), so memory stays bounded however large the entry is. A compressed or solid entry is decoded from its start, so a deep offset costs the read up to it.
read_entry_to_anon_file(archive, name, max_bytes, password, &cancelled)Read one entry into an unlinked temporary file and return it open at byte 0, so the bytes can be handed to another process without ever having a name on disk. A symlink is refused.
Rust
use peel_core::{read_entry_bytes, EntryBytes};

match read_entry_bytes(path, "META-INF/container.xml", 1 << 20, None, &|| false)? {
    EntryBytes::Data { data } => println!("{} bytes", data.len()),
    EntryBytes::Symlink { target } => println!("link to {target}"),
}

The cancelled argument is any &(dyn Fn() -> bool + Sync). It is polled during the copy; return true to stop. &|| false never cancels.

Open once, read many

OpenArchive keeps an archive open for repeated member reads. A ZIP holds its central directory in memory, so each read skips the open and the scan. Other formats keep the handle (format, password, change detection) but still open the file for each read. It is safe to share between threads; reads on one session run one at a time. If the file changes after it was opened, reads fail with an I/O error instead of answering from a stale index.

Rust
use peel_core::{OpenArchive, SessionState};

let archive = OpenArchive::open(path, None)?;       // a damaged ZIP fails here, not on first read
assert_eq!(archive.state(), SessionState::Open);

for name in ["page-001.jpg", "page-002.jpg"] {
    let bytes = archive.read_entry_bytes(name, 32 << 20, &|| false)?;
    // hand `bytes` to your media pipeline
}
archive.close();                                    // state() is now Closed

archive.read_entry_range(name, offset, length, &cancelled) is the ranged read on a session. A multi-frame .tar.zst or multi-block .tar.xz builds a member table on its first read and then decodes only the units that hold the member. format() and path() describe the open archive. SessionState is Open, Invalidated (the file changed) or Closed.

Create

Rust
use peel_core::{create_archive_with, create_archive_opts, CreateOptions};
use std::path::PathBuf;

let inputs = vec![PathBuf::from("public"), PathBuf::from("README.md")];

// Format from the output extension. overwrite = false refuses to replace a file.
let made = create_archive_with("site.zip".as_ref(), &inputs, None, false)?;
println!("{} entries in {}", made.entries, made.output);

// Password (AES-256 for ZIP and 7z), volumes and zstd tuning.
let opts = CreateOptions {
    password: Some("correct horse".into()),
    volume_size: Some(100 << 20),                   // site.zip.001, .002, …
    ..Default::default()
};
create_archive_opts("site.zip".as_ref(), &inputs, &opts)?;

create_archive(output, inputs, password) replaces an existing output; create_archive_with takes an overwrite flag; create_archive_split and create_archive_opts add volumes and zstd options. The archive is written to a hidden temporary file and renamed into place, so output is either the old file or the whole new one.

Verify and recover

Rust
use peel_core::{assess_archive, salvage, test_archive, repair_par2, verify_par2};

// Read every entry to the end.
let report = test_archive(path, None, &|| false)?;       // TestReport
if !report.ok() {
    for f in &report.failures { eprintln!("{}: {}", f.name, f.error); }
}

// A locked archive: what is realistic, without trying a password.
let a = assess_archive(path)?;                           // RecoveryAssessment
println!("{:?}", a.feasibility);

// A damaged ZIP or tar: carve out what is readable.
let s = salvage(path, "recovered".as_ref())?;            // SalvageReport
println!("{} recovered, {} partial", s.recovered, s.partial);
FunctionWhat it does
test_archiveEntry-by-entry integrity check. TestReport { format, entries, verified, unchecked, failures }.
assess_archiveRecoveryAssessment: encryption, metadata visibility, volumes, feasibility, techniques, notes.
salvageZIP by local-header scan, the tar family keeping whole entries up to a truncation. Also salvage_zip, salvage_tar, salvage_bzip2, salvage_stream.
verify_par2, repair_par2, find_par2_setPAR2 parity verify and repair.
find_originals, assemble_originals, recover_zipcryptoThe find-originals and unlock steps: locate copies of a locked ZIP’s files, then recover a ZipCrypto archive from them.
generate_candidates, test_candidates, measure_check_rateThe building blocks behind recover.
diagnose_archiveA privacy-safe diagnostic report.

Errors

Rust
use peel_core::{peel, ErrorKind, ExtractPolicy};

match peel(path, &ExtractPolicy::default()) {
    Ok(r) => println!("{} files", r.extracted.len()),
    Err(e) => match e.kind() {
        ErrorKind::PasswordRequired | ErrorKind::WrongPassword => { /* ask the user */ }
        ErrorKind::NotEnoughSpace => { /* e.report().needed / .available */ }
        ErrorKind::Damaged => { /* offer salvage */ }
        _ => eprintln!("{}", serde_json::to_string(&e.report()).unwrap()),
    },
}

ErrorKind::exit_code() is the CLI’s exit status for that kind and as_str() the stable code (wrong_password, …). The list is on the overview.

Safety helpers

If you write extraction code of your own, reuse the same primitives: sanitize_entry_name, safe_destination, assert_tree_contained, copy_bounded and ResourceBudget. Passwords travel as Secret, which is wiped when dropped; resolve_password reads the explicit value or PEEL_PASSWORD.