rz-archive 0.15.0

Multi-format archive tool — tar, zip, 7z with a unified CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use std::cell::RefCell;

use camino::{Utf8Path, Utf8PathBuf};
use sevenz_rust2::encoder_options::{AesEncoderOptions, Lzma2Options};
use sevenz_rust2::{ArchiveEntry, EncoderConfiguration, EncoderMethod, Password};

use crate::error::{Error, Result};
use crate::{ArchiveInfo, CompressOpts, DecompressOpts, Entry};

// ── Compress ──────────────────────────────────────────────────────────────────

pub fn compress(inputs: &[Utf8PathBuf], output: &Utf8Path, opts: &CompressOpts<'_>) -> Result<()> {
    let inputs = crate::filter::validate_inputs(inputs, opts)?;
    let result = compress_validated(&inputs, output, opts);
    if result.is_err() {
        // A failure part-way through leaves a truncated, unreadable archive
        // at the output path — same cleanup the zip path does.
        let _ = fs_err::remove_file(output);
    }
    result
}

fn compress_validated(
    inputs: &[Utf8PathBuf],
    output: &Utf8Path,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    let mut writer = sevenz_rust2::ArchiveWriter::create(output)?;

    // Resolve the compression method from the requested level: 0 (or `--store`,
    // which main.rs maps to level 0) selects COPY (no compression); 1..=9 map to
    // LZMA2 presets (higher values are clamped to 9 by lzma-rust2); None keeps
    // sevenz-rust2's default LZMA2.
    let comp_cfg: Option<EncoderConfiguration> = match opts.level {
        Some(0) => Some(EncoderConfiguration::new(EncoderMethod::COPY)),
        Some(level) => Some(Lzma2Options::from_level(level).into()),
        None => None,
    };

    // The method vec mirrors the 7z encoder pipeline: each element wraps the
    // output of the previous one, so AES at index 0 is the OUTERMOST layer in
    // the archive (the first thing a reader must peel off), wrapping the
    // compression method beneath it.
    if let Some(pwd) = &opts.password {
        let aes_cfg: EncoderConfiguration =
            AesEncoderOptions::new(Password::from(pwd.as_str())).into();
        let comp_cfg = comp_cfg.unwrap_or_else(|| EncoderConfiguration::new(EncoderMethod::LZMA2));
        writer.set_content_methods(vec![aes_cfg, comp_cfg]);
    } else if let Some(comp_cfg) = comp_cfg {
        writer.set_content_methods(vec![comp_cfg]);
    }

    // Explicit walk via filter::walk_dir — the same traversal and naming tar
    // and zip use (`<input-name>/<relative>` for directory inputs), replacing
    // sevenz-rust2's own `push_source_path` walk, which stripped the input
    // directory's name (rz-made 7z archives tar-bombed on extraction and
    // equal-named children of multiple inputs silently collided), never
    // surfaced symlinks, and ignored `follow_symlinks` entirely.  Excludes
    // now match archive-relative names, also like tar and zip.
    for input in inputs {
        let meta = crate::filter::input_metadata(input, opts.follow_symlinks)?;
        let name = crate::filter::input_base_name(input)?;
        if opts.excludes.is_match(&name) {
            continue;
        }
        let link_meta = fs_err::symlink_metadata(input)?;
        if !opts.follow_symlinks && link_meta.file_type().is_symlink() {
            push_symlink_entry(&mut writer, input, &name, &link_meta, opts)?;
        } else if meta.is_dir() {
            if opts.no_recursion {
                push_dir_entry(&mut writer, input, &name, &meta)?;
            } else {
                push_dir_walked(&mut writer, input, &name, opts)?;
            }
        } else if !crate::filter::skip_unarchivable_special(&meta, &name) {
            push_file_entry(&mut writer, input, &name, &meta, opts)?;
        }
    }
    let file = writer.finish()?;
    file.sync_all()?;
    Ok(())
}

// ── p7zip Unix attribute encoding ────────────────────────────────────────────

/// 7-Zip's marker that the high 16 bits of the attributes word carry a Unix
/// `st_mode` (`FILE_ATTRIBUTE_UNIX_EXTENSION` in the p7zip source).
const ATTR_UNIX_EXTENSION: u32 = 0x8000;
const ATTR_READONLY: u32 = 0x1;
const ATTR_DIRECTORY: u32 = 0x10;
const ATTR_ARCHIVE: u32 = 0x20;

/// Encode a Unix mode the way p7zip's `Get_WinAttribPosix_From_PosixMode`
/// does — DOS directory/archive flag (plus read-only when no write bit is
/// set), the extension marker, and the full `st_mode` (type bits included)
/// shifted into the high half — so 7-Zip itself restores modes from rz
/// archives and vice versa.
#[cfg(unix)]
fn unix_attributes(mode: u32) -> u32 {
    let mut low = if mode & 0xF000 == 0o040000 {
        ATTR_DIRECTORY
    } else {
        ATTR_ARCHIVE
    };
    if mode & 0o222 == 0 {
        low |= ATTR_READONLY;
    }
    low | ATTR_UNIX_EXTENSION | ((mode & 0xFFFF) << 16)
}

/// Stamp `meta`'s Unix mode onto the entry's attribute word.  A no-op on
/// non-Unix hosts, which keeps whatever `from_path` left (nothing).
fn apply_unix_attributes(entry: &mut ArchiveEntry, meta: &std::fs::Metadata) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        entry.windows_attributes = unix_attributes(meta.mode());
        entry.has_windows_attributes = true;
    }
    #[cfg(not(unix))]
    {
        let _ = (entry, meta);
    }
}

/// Decode the Unix mode from an entry's attribute word, when present.
fn entry_unix_mode(entry: &ArchiveEntry) -> Option<u32> {
    (entry.has_windows_attributes && entry.windows_attributes & ATTR_UNIX_EXTENSION != 0)
        .then_some((entry.windows_attributes >> 16) & 0xFFFF)
}

// ── Compress-side entry writers ──────────────────────────────────────────────

fn push_dir_walked(
    writer: &mut sevenz_rust2::ArchiveWriter<std::fs::File>,
    dir: &Utf8Path,
    prefix: &str,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    crate::filter::walk_dir(dir, prefix, opts, &mut |entry| {
        let link_meta = fs_err::symlink_metadata(&entry.fs_path)?;
        if !opts.follow_symlinks && link_meta.file_type().is_symlink() {
            push_symlink_entry(writer, &entry.fs_path, &entry.archive_name, &link_meta, opts)
        } else if entry.is_dir {
            let meta = crate::filter::input_metadata(&entry.fs_path, opts.follow_symlinks)?;
            push_dir_entry(writer, &entry.fs_path, &entry.archive_name, &meta)
        } else {
            let meta = crate::filter::input_metadata(&entry.fs_path, opts.follow_symlinks)?;
            if crate::filter::skip_unarchivable_special(&meta, &entry.archive_name) {
                return Ok(());
            }
            push_file_entry(writer, &entry.fs_path, &entry.archive_name, &meta, opts)
        }
    })
}

fn push_file_entry(
    writer: &mut sevenz_rust2::ArchiveWriter<std::fs::File>,
    fs_path: &Utf8Path,
    archive_name: &str,
    meta: &std::fs::Metadata,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    let mut entry = ArchiveEntry::from_path(fs_path.as_std_path(), archive_name.to_owned());
    apply_unix_attributes(&mut entry, meta);
    let file = fs_err::File::open(fs_path)?;
    writer.push_archive_entry(entry, Some(file))?;
    opts.progress.set_entry(archive_name);
    opts.progress.inc(meta.len());
    Ok(())
}

fn push_dir_entry(
    writer: &mut sevenz_rust2::ArchiveWriter<std::fs::File>,
    fs_path: &Utf8Path,
    archive_name: &str,
    meta: &std::fs::Metadata,
) -> Result<()> {
    let mut entry = ArchiveEntry::from_path(fs_path.as_std_path(), archive_name.to_owned());
    apply_unix_attributes(&mut entry, meta);
    writer.push_archive_entry::<std::fs::File>(entry, None)?;
    Ok(())
}

/// Store a symlink the way p7zip does: a regular-looking entry whose content
/// is the raw target path and whose attribute word carries `S_IFLNK` in the
/// mode bits.  Built by hand rather than via `from_path`, which follows the
/// link (and fails to stat a dangling one).
fn push_symlink_entry(
    writer: &mut sevenz_rust2::ArchiveWriter<std::fs::File>,
    fs_path: &Utf8Path,
    archive_name: &str,
    link_meta: &std::fs::Metadata,
    opts: &CompressOpts<'_>,
) -> Result<()> {
    let target = fs_err::read_link(fs_path)?;
    let target_str = target
        .to_str()
        .ok_or_else(|| Error::InvalidUtf8Path(target.display().to_string()))?
        .to_owned();

    let mut entry = ArchiveEntry::new_file(archive_name);
    if let Ok(modified) = link_meta.modified()
        && let Ok(date) = sevenz_rust2::NtTime::try_from(modified)
    {
        entry.last_modified_date = date;
        entry.has_last_modified_date = u64::from(date) > 0;
    }
    apply_unix_attributes(&mut entry, link_meta);
    let len = target_str.len() as u64;
    writer.push_archive_entry(entry, Some(std::io::Cursor::new(target_str.into_bytes())))?;
    opts.progress.set_entry(archive_name);
    opts.progress.inc(len);
    Ok(())
}

// ── Decompress ────────────────────────────────────────────────────────────────

pub fn decompress(input: &Utf8Path, output: &Utf8Path, opts: &DecompressOpts<'_>) -> Result<()> {
    if opts.strip_components > 0 {
        return Err(Error::StripComponentsUnsupported("7z".to_owned()));
    }
    // sevenz-rust2 entries do not expose reliable mtime metadata, so we
    // can't implement --keep-newer with real newness semantics; refuse
    // rather than silently degrading to "skip existing".
    if opts.keep_newer {
        return Err(Error::KeepNewerUnsupported("7z".to_owned()));
    }
    let file = fs_err::File::open(input)?;
    let password = opts
        .password
        .as_deref()
        .map_or_else(Password::empty, Password::from);

    // sevenz-rust2's error type cannot carry one of ours, and forcing ours
    // through `io::Error` would relabel every failure as an I/O error, so the
    // real error is parked here and rethrown once the walk unwinds.
    let parked: RefCell<Option<Error>> = RefCell::new(None);
    let deferred_dirs: RefCell<Vec<(Utf8PathBuf, u32)>> = RefCell::new(Vec::new());

    let walked = sevenz_rust2::decompress_with_extract_fn_and_password(
        file,
        output,
        password,
        |entry, reader, _entry_dest| {
            match extract_entry(entry, reader, output, opts, &deferred_dirs) {
                Ok(keep_walking) => Ok(keep_walking),
                Err(e) => {
                    let msg = e.to_string();
                    *parked.borrow_mut() = Some(e);
                    Err(sevenz_rust2::Error::Io(
                        std::io::Error::other(msg),
                        entry.name.clone().into(),
                    ))
                }
            }
        },
    );

    if let Some(e) = parked.into_inner() {
        return Err(e);
    }
    walked?;

    // Directory modes recorded under -P are applied children-first after the
    // walk, so a read-only directory entry can't block extraction of its own
    // contents — the same deferral the tar path uses.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut dirs = deferred_dirs.into_inner();
        dirs.sort_by(|a, b| b.0.as_str().cmp(a.0.as_str()));
        for (path, mode) in dirs {
            fs_err::set_permissions(&path, std::fs::Permissions::from_mode(mode & 0o7777))?;
        }
    }
    #[cfg(not(unix))]
    drop(deferred_dirs);
    Ok(())
}

/// Resolve one 7z entry against the output root and write it out.
///
/// sevenz-rust2 hands the extract callback `<output>/<entry name>` — the
/// entry's own destination, derived from the raw archive name with no traversal
/// filtering — rather than the output root.  Every path is therefore resolved
/// against `output` here, and `default_entry_extract_fn` is never delegated to:
/// it would re-derive the destination from the unrewritten name, ignoring
/// `--rename`/`--prefix` and the overwrite guards below.
///
/// The returned bool tells sevenz-rust2 the entry is fully handled; a skipped
/// entry still counts as handled, so this is always `true`.
fn extract_entry(
    entry: &sevenz_rust2::ArchiveEntry,
    reader: &mut dyn std::io::Read,
    output: &Utf8Path,
    opts: &DecompressOpts<'_>,
    deferred_dirs: &RefCell<Vec<(Utf8PathBuf, u32)>>,
) -> Result<bool> {
    crate::filter::safe_entry_path(&entry.name)?;

    if !crate::filter::should_extract(&entry.name, &opts.includes, &opts.excludes) {
        return skip_entry(reader);
    }
    if opts.no_directory && entry.is_directory {
        return skip_entry(reader);
    }

    let base_name = if opts.no_directory {
        match Utf8Path::new(&entry.name).file_name() {
            Some(name) => Utf8PathBuf::from(name),
            None => return skip_entry(reader),
        }
    } else {
        Utf8PathBuf::from(&entry.name)
    };

    let dest_path =
        match crate::filter::apply_path_rewrites(base_name, &opts.renames, opts.prefix.as_deref())?
        {
            p if p.as_str().is_empty() => return skip_entry(reader),
            p => p,
        };

    let out_path = output.join(&dest_path);

    if entry.is_directory {
        fs_err::create_dir_all(&out_path)?;
        if opts.preserve_permissions
            && let Some(mode) = entry_unix_mode(entry)
            && mode & 0xF000 == 0o040000
        {
            deferred_dirs.borrow_mut().push((out_path, mode));
        }
        return Ok(true);
    }

    if let Some(parent) = out_path.parent() {
        fs_err::create_dir_all(parent)?;
    }

    let existed = fs_err::symlink_metadata(&out_path).is_ok();
    if existed {
        if let Some(suffix) = &opts.backup_suffix {
            let backup = Utf8PathBuf::from(format!("{out_path}{suffix}"));
            fs_err::rename(&out_path, &backup)?;
        } else if opts.no_overwrite {
            return skip_entry(reader);
        } else if !opts.force {
            return Err(Error::FileExists(out_path));
        }
    }

    // Symlink entries carry S_IFLNK in the attribute word and the target
    // path as their content (p7zip's convention).
    if let Some(mode) = entry_unix_mode(entry)
        && mode & 0xF000 == 0o120000
    {
        return extract_symlink_entry(reader, &out_path, &dest_path, opts);
    }

    // If overwriting an existing symlink, remove it first so the new file
    // replaces the link rather than the link's target.  Re-stat instead of
    // reusing `existed`: the backup branch renames the original away.
    if fs_err::symlink_metadata(&out_path)
        .is_ok_and(|m| m.file_type().is_symlink())
    {
        fs_err::remove_file(&out_path)?;
    }
    let mut out_file = fs_err::File::create(&out_path)?;
    let written = std::io::copy(reader, &mut out_file)?;
    restore_mtime(&out_file, entry);
    // Only S_IFREG modes get chmod'd: an attribute word forged as exactly
    // 0x8000 (unix marker, no type bits) decodes to mode 0, and applying it
    // would leave the extracted file at 0o000.
    #[cfg(unix)]
    if opts.preserve_permissions
        && let Some(mode) = entry_unix_mode(entry)
        && mode & 0xF000 == 0o100000
    {
        use std::os::unix::fs::PermissionsExt;
        fs_err::set_permissions(&out_path, std::fs::Permissions::from_mode(mode & 0o7777))?;
    }
    opts.progress.set_entry(dest_path.as_str());
    opts.progress.inc(written);
    Ok(true)
}

/// Upper bound on a symlink target this crate is willing to read — same
/// rationale as the zip path: PATH_MAX is 4096, so anything past 8 KiB is a
/// hostile entry, not a link.
const MAX_SYMLINK_TARGET: u64 = 8 * 1024;

/// Recreate a 7z symlink entry (content = target path) as a real symlink,
/// with the same structural target validation the tar and zip paths apply.
/// Presence at `out_path` is re-checked before removal — the backup branch
/// may have renamed the original away since the caller's stat.
fn extract_symlink_entry(
    reader: &mut dyn std::io::Read,
    out_path: &Utf8Path,
    dest_path: &Utf8Path,
    opts: &DecompressOpts<'_>,
) -> Result<bool> {
    let mut target_bytes = Vec::new();
    let read = std::io::copy(
        &mut std::io::Read::take(&mut *reader, MAX_SYMLINK_TARGET),
        &mut target_bytes,
    )?;
    if read >= MAX_SYMLINK_TARGET {
        return Err(Error::SymlinkTargetTooLong {
            path: dest_path.to_owned(),
            max: MAX_SYMLINK_TARGET,
        });
    }
    let target = std::str::from_utf8(&target_bytes)
        .map_err(|_| Error::InvalidUtf8Path(dest_path.to_string()))?;

    crate::filter::safe_link_target(dest_path.as_str(), target)?;

    if fs_err::symlink_metadata(out_path).is_ok() {
        fs_err::remove_file(out_path)?;
    }
    #[cfg(unix)]
    std::os::unix::fs::symlink(target, out_path)?;
    #[cfg(not(unix))]
    fs_err::write(out_path, &target_bytes)?;

    opts.progress.set_entry(dest_path.as_str());
    opts.progress.inc(target_bytes.len() as u64);
    Ok(true)
}

/// Consume an entry's payload without writing it anywhere.
///
/// Entry readers are bounded views over one shared solid-block stream, so an
/// entry that is filtered out still has to be read to its end: leaving bytes
/// behind makes every following entry in the block decode from a misaligned
/// offset and fail its CRC check.
fn skip_entry(reader: &mut dyn std::io::Read) -> Result<bool> {
    std::io::copy(reader, &mut std::io::sink())?;
    Ok(true)
}

/// Best-effort mtime restoration, matching what sevenz-rust2's default
/// extractor does.  A filesystem that refuses the timestamp must not fail an
/// otherwise-complete extraction.
fn restore_mtime(file: &fs_err::File, entry: &sevenz_rust2::ArchiveEntry) {
    if !entry.has_last_modified_date {
        return;
    }
    let times = std::fs::FileTimes::new().set_modified(entry.last_modified_date.into());
    let _ = file.file().set_times(times);
}

// ── Decompress to writer ─────────────────────────────────────────────────────

pub fn decompress_to_writer<W: std::io::Write>(
    input: &Utf8Path,
    writer: &mut W,
    opts: &DecompressOpts<'_>,
) -> Result<()> {
    if opts.strip_components > 0 {
        return Err(Error::StripComponentsUnsupported("7z".to_owned()));
    }
    let file = fs_err::File::open(input)?;
    let password = opts
        .password
        .as_deref()
        .map(Password::from)
        .unwrap_or_else(Password::empty);
    sevenz_rust2::decompress_with_extract_fn_and_password(
        file,
        ".",
        password,
        |entry, reader, _dest| {
            // Reject entries that attempt path traversal.
            crate::filter::safe_entry_path(&entry.name).map_err(|e| {
                sevenz_rust2::Error::Io(
                    std::io::Error::other(e.to_string()),
                    entry.name.clone().into(),
                )
            })?;

            if entry.is_directory {
                return Ok(true);
            }
            if !crate::filter::should_extract(&entry.name, &opts.includes, &opts.excludes) {
                return Ok(true);
            }
            if opts.no_directory {
                let display_name = Utf8Path::new(&entry.name)
                    .file_name()
                    .unwrap_or(&entry.name);
                opts.progress.set_entry(display_name);
            } else {
                opts.progress.set_entry(&entry.name);
            }
            std::io::copy(reader, writer)
                .map_err(|e| sevenz_rust2::Error::Io(e, "decompress to writer".into()))?;
            Ok(true) // skip default extraction
        },
    )?;
    Ok(())
}

// ── Test ──────────────────────────────────────────────────────────────────────

pub fn test(
    input: &Utf8Path,
    password: Option<&str>,
    progress: &dyn crate::progress::ProgressReport,
) -> Result<()> {
    let file = fs_err::File::open(input)?;
    let pwd = password.map_or_else(Password::empty, Password::from);
    sevenz_rust2::decompress_with_extract_fn_and_password(
        file,
        ".",
        pwd,
        |entry, reader, _dest| {
            progress.set_entry(&entry.name);
            let written = std::io::copy(reader, &mut std::io::sink())
                .map_err(|e| sevenz_rust2::Error::Io(e, "test: reading entry".into()))?;
            progress.inc(written);
            Ok(true) // skip default extraction
        },
    )?;
    Ok(())
}

// ── List ──────────────────────────────────────────────────────────────────────

pub fn list(input: &Utf8Path) -> Result<Vec<Entry>> {
    let archive = sevenz_rust2::Archive::open(input)?;
    let mut entries = Vec::new();
    for file in &archive.files {
        let path = Utf8PathBuf::from(&file.name);
        let mtime = if file.has_last_modified_date {
            let st: std::time::SystemTime = file.last_modified_date.into();
            st.duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0)
        } else {
            0
        };
        entries.push(Entry {
            path,
            size: file.size,
            mtime,
            // Full st_mode from the p7zip unix extension, matching what the
            // zip module reports from its external attributes.
            mode: entry_unix_mode(file).unwrap_or(0),
            is_dir: file.is_directory,
            // A 7z symlink's target is its entry content inside the solid
            // stream; listing must not decode data blocks, so it stays
            // unknown here and gets validated at extraction time instead.
            link_target: None,
        });
    }
    Ok(entries)
}

// ── Info ──────────────────────────────────────────────────────────────────────

pub fn info(input: &Utf8Path) -> Result<ArchiveInfo> {
    let compressed_size = fs_err::metadata(input)?.len();
    let archive = sevenz_rust2::Archive::open(input)?;

    Ok(ArchiveInfo {
        format: "7z",
        entry_count: archive.files.len(),
        // Saturating fold — `Iterator::sum` on u64 panics on overflow in
        // debug and wraps in release; either is a bad outcome for a
        // potentially adversarial archive.
        total_uncompressed: archive
            .files
            .iter()
            .fold(0u64, |acc, f| acc.saturating_add(f.size)),
        compressed_size,
    })
}