zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! `zexc` CLI — compress, decompress, archive, test, bench, train-dict
//!
//! Named **zexc** (not `zex`) to avoid conflicting with package-manager binaries.
//!
//! SPDX-License-Identifier: GPL-3.0-only
//! Copyright (C) 2026 Ali Zain <alizain@zainiumdynamics.tech>
//! Website: https://zainiumdynamics.tech

use clap::Parser;
use memmap2::Mmap;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use zexc::archive::{ARCHIVE_MAGIC, create_from_paths, extract_to_dir, is_archive, list_archive};
use zexc::cli::args::{ArchiveCmd, Cli, Commands};
use zexc::core::frame::FrameReader;
use zexc::format::header::HEADER_SIZE;
use zexc::utils::simd;
use zexc::{
    CompressOptions, DecompressOptions, Dictionary, SecurityPolicy, ZEX_VERSION, compress,
    decompress, decompress_with_options,
};

#[cfg(feature = "encryption")]
use zexc::EncryptionKey;

fn main() {
    if let Err(e) = run() {
        eprintln!("zexc: error: {e}");
        std::process::exit(1);
    }
}

fn configure_threads(n: usize) {
    if n > 0 {
        // Best-effort: rayon global pool (ignore if already init)
        let _ = rayon::ThreadPoolBuilder::new()
            .num_threads(n)
            .build_global();
    }
}

fn run() -> anyhow::Result<()> {
    let cli = Cli::parse();
    configure_threads(cli.threads);
    let quiet = cli.quiet;

    match cli.command {
        Commands::Compress {
            input,
            output,
            level,
            mode,
            no_checksum,
            secure,
            password,
            dict,
            block_size_kib,
            rm,
        } => cmd_compress(
            input,
            output,
            level,
            mode.into(),
            !no_checksum,
            secure,
            password,
            dict,
            cli.threads == 0 || cli.threads > 1,
            block_size_kib,
            rm,
            quiet,
        ),
        Commands::Decompress {
            input,
            output,
            no_check,
            secure,
            password,
            dict,
            rm,
        } => cmd_decompress(
            input,
            output,
            !no_check,
            secure,
            password,
            dict,
            cli.threads == 0 || cli.threads > 1,
            rm,
            quiet,
        ),
        Commands::Info { input } => cmd_info(input),
        Commands::Test {
            input,
            password,
            dict,
        } => cmd_test(input, password, dict, quiet),
        Commands::TrainDict {
            samples,
            output,
            max_size,
            simple,
            d,
        } => cmd_train_dict(samples, output, max_size, simple, d),
        Commands::SeekCompress {
            input,
            output,
            frame_kib,
            level,
            mode,
        } => cmd_seek_compress(input, output, frame_kib, level, mode.into(), quiet),
        Commands::Archive { action } => cmd_archive(action, quiet),
        Commands::Bench {
            input,
            level,
            mode,
            iters,
        } => cmd_bench(input, level, mode.into(), iters, quiet),
    }
}

fn is_stdio(p: &Path) -> bool {
    p.as_os_str() == "-"
}

fn read_input(path: &Path) -> anyhow::Result<Vec<u8>> {
    if is_stdio(path) {
        let mut buf = Vec::new();
        io::stdin().read_to_end(&mut buf)?;
        return Ok(buf);
    }
    let f = File::open(path)?;
    let meta = f.metadata()?;
    if meta.len() == 0 {
        return Ok(Vec::new());
    }
    let mmap = unsafe { Mmap::map(&f)? };
    Ok(mmap[..].to_vec())
}

fn write_output(path: &Path, data: &[u8]) -> anyhow::Result<()> {
    if is_stdio(path) {
        let mut out = io::stdout().lock();
        out.write_all(data)?;
        out.flush()?;
        return Ok(());
    }
    std::fs::write(path, data)?;
    Ok(())
}

fn load_dict(path: Option<PathBuf>) -> anyhow::Result<Option<Dictionary>> {
    match path {
        None => Ok(None),
        Some(p) => Ok(Some(Dictionary::from_bytes(std::fs::read(&p)?)?)),
    }
}

fn progress(quiet: bool, msg: &str) {
    if !quiet {
        eprintln!("zexc: {msg}");
    }
}

#[allow(clippy::too_many_arguments)]
fn cmd_compress(
    input: PathBuf,
    output: Option<PathBuf>,
    level: u8,
    mode: zexc::CompressionMode,
    checksum: bool,
    secure: bool,
    password: Option<String>,
    dict_path: Option<PathBuf>,
    threads: bool,
    block_size_kib: u32,
    rm: bool,
    quiet: bool,
) -> anyhow::Result<()> {
    let src = read_input(&input)?;
    let out_path = match output {
        Some(p) => p,
        None => {
            if is_stdio(&input) {
                PathBuf::from("-")
            } else {
                let mut p = input.clone();
                let ext = match p.extension() {
                    Some(e) => {
                        let mut os = e.to_os_string();
                        os.push(".zex");
                        os
                    }
                    None => "zex".into(),
                };
                p.set_extension(ext);
                p
            }
        }
    };
    if !quiet && src.len() > 8 * 1024 * 1024 {
        progress(quiet, &format!("compressing {} bytes…", src.len()));
    }

    let mut opts = CompressOptions {
        mode,
        level: level.clamp(1, 22),
        block_size: block_size_kib.saturating_mul(1024).max(1024),
        checksum,
        threads,
        independent: true,
        dictionary: load_dict(dict_path)?,
        security: SecurityPolicy::default(),
        #[cfg(feature = "encryption")]
        encryption: None,
    };
    if secure {
        opts = opts.secure();
    }
    #[cfg(feature = "encryption")]
    if let Some(pw) = password {
        opts = opts.encrypt(EncryptionKey::parse_cli(&pw)?);
    }
    #[cfg(not(feature = "encryption"))]
    if password.is_some() {
        anyhow::bail!("encryption feature disabled in this build");
    }

    let t0 = Instant::now();
    let compressed = compress(&src, &opts)?;
    let dt = t0.elapsed();
    write_output(&out_path, &compressed)?;

    if !quiet {
        let ratio = if src.is_empty() {
            0.0
        } else {
            compressed.len() as f64 / src.len() as f64 * 100.0
        };
        let mbps = if dt.as_secs_f64() > 0.0 {
            (src.len() as f64 / (1024.0 * 1024.0)) / dt.as_secs_f64()
        } else {
            0.0
        };
        let h = zexc::ZexHeader::from_bytes(&compressed).ok();
        eprintln!(
            "zexc: {} → {} ({:.1}%, l{}, {}, {:.1} MiB/s, simd={}, enc={}, dict={}) [v{}]",
            path_label(&input),
            path_label(&out_path),
            ratio,
            opts.level,
            mode,
            mbps,
            simd::simd_enabled(),
            h.as_ref().map(|h| h.is_encrypted()).unwrap_or(false),
            h.as_ref().map(|h| h.dictionary_id != 0).unwrap_or(false),
            ZEX_VERSION
        );
    }

    if rm && !is_stdio(&input) && !is_stdio(&out_path) {
        let _ = std::fs::remove_file(&input);
    }
    Ok(())
}

fn path_label(p: &Path) -> String {
    if is_stdio(p) {
        "-".into()
    } else {
        p.display().to_string()
    }
}

#[allow(clippy::too_many_arguments)]
fn cmd_decompress(
    input: PathBuf,
    output: Option<PathBuf>,
    verify: bool,
    secure: bool,
    password: Option<String>,
    dict_path: Option<PathBuf>,
    threads: bool,
    rm: bool,
    quiet: bool,
) -> anyhow::Result<()> {
    let src = read_input(&input)?;
    let out_path = match output {
        Some(p) => p,
        None => {
            if is_stdio(&input) {
                PathBuf::from("-")
            } else {
                let mut p = input.clone();
                let has_zex_ext = p.extension().is_some_and(|e| e == "zex");
                if has_zex_ext {
                    p.set_extension("");
                } else {
                    let ext = match p.extension() {
                        Some(e) => {
                            let mut os = e.to_os_string();
                            os.push(".decoded");
                            os
                        }
                        None => "decoded".into(),
                    };
                    p.set_extension(ext);
                }
                p
            }
        }
    };

    let mut opts = DecompressOptions {
        verify_checksum: verify,
        threads,
        security: if secure {
            SecurityPolicy::strict()
        } else {
            SecurityPolicy::default()
        },
        dictionary: load_dict(dict_path)?,
        #[cfg(feature = "encryption")]
        encryption: None,
    };
    #[cfg(feature = "encryption")]
    if let Some(pw) = password {
        opts.encryption = Some(EncryptionKey::parse_cli(&pw)?);
    }
    #[cfg(not(feature = "encryption"))]
    if password.is_some() {
        anyhow::bail!("encryption feature disabled");
    }

    let t0 = Instant::now();
    let plain = decompress_with_options(&src, &opts)?;
    let dt = t0.elapsed();
    write_output(&out_path, &plain)?;

    if !quiet {
        let mbps = if dt.as_secs_f64() > 0.0 {
            (plain.len() as f64 / (1024.0 * 1024.0)) / dt.as_secs_f64()
        } else {
            0.0
        };
        eprintln!(
            "zexc: {} → {} ({} bytes, {:.1} MiB/s)",
            path_label(&input),
            path_label(&out_path),
            plain.len(),
            mbps
        );
    }
    if rm && !is_stdio(&input) && !is_stdio(&out_path) {
        let _ = std::fs::remove_file(&input);
    }
    Ok(())
}

fn cmd_test(
    input: PathBuf,
    password: Option<String>,
    dict_path: Option<PathBuf>,
    quiet: bool,
) -> anyhow::Result<()> {
    let src = read_input(&input)?;
    let mut opts = DecompressOptions {
        verify_checksum: true,
        threads: true,
        security: SecurityPolicy::default(),
        dictionary: load_dict(dict_path)?,
        #[cfg(feature = "encryption")]
        encryption: None,
    };
    #[cfg(feature = "encryption")]
    if let Some(pw) = password {
        opts.encryption = Some(EncryptionKey::parse_cli(&pw)?);
    }
    #[cfg(not(feature = "encryption"))]
    let _ = password;

    let plain = decompress_with_options(&src, &opts)?;
    // Re-compress not required; successful decode + CRC is enough
    if !quiet {
        eprintln!(
            "zexc: {}: OK ({} bytes decompressed)",
            path_label(&input),
            plain.len()
        );
    }
    Ok(())
}

fn cmd_info(input: PathBuf) -> anyhow::Result<()> {
    let data = read_input(&input)?;
    if is_archive(&data) {
        println!("File:           {}", path_label(&input));
        println!("Type:           ZEXA archive");
        println!(
            "Magic:          {}",
            String::from_utf8_lossy(&ARCHIVE_MAGIC)
        );
        let items = list_archive(&data)?;
        println!("Entries:        {}", items.len());
        for (i, it) in items.iter().enumerate() {
            println!(
                "  [{i}] {}  unc={}  frame={}",
                it.name, it.uncompressed_size, it.frame_size
            );
        }
        return Ok(());
    }

    let header = zexc::ZexHeader::from_bytes(&data)?;
    println!("File:           {}", path_label(&input));
    println!("Magic:          ZEX1");
    println!(
        "Codec:          ZEX native (SIMD={}, turbo levels≤2)",
        simd::simd_enabled()
    );
    println!("Version:        {}", header.version);
    println!("Profile:        {}", header.mode);
    println!("Level:          {}", header.level);
    println!("Block size:     {} bytes", header.block_size);
    if header.content_size == u64::MAX {
        println!("Content size:   unknown");
    } else {
        println!("Content size:   {} bytes", header.content_size);
    }
    println!("Dictionary ID:  {:#x}", header.dictionary_id);
    println!("Checksum:       {}", header.has_checksum());
    println!("Encrypted:      {}", header.is_encrypted());
    println!("Independent:    {}", header.independent_blocks());
    println!("Header size:    {HEADER_SIZE} bytes");

    if header.is_encrypted() {
        println!("(encrypted — block stats unavailable)");
        return Ok(());
    }
    let info = FrameReader::new(std::io::Cursor::new(&data)).info()?;
    println!("Blocks:         {}", info.block_count);
    println!(
        "  raw / zex:     {} / {}",
        info.type_counts[0], info.type_counts[1]
    );
    println!("Payload bytes:  {}", info.compressed_payload);
    Ok(())
}

fn cmd_train_dict(
    samples: Vec<PathBuf>,
    output: PathBuf,
    max_size: usize,
    simple: bool,
    d: usize,
) -> anyhow::Result<()> {
    // Support both: train-dict out.dict s1 s2  AND  train-dict s1 s2 -o out (legacy was output first)
    if samples.is_empty() {
        anyhow::bail!("usage: zexc train-dict OUT.dict SAMPLE [SAMPLE...]");
    }
    let mut bufs = Vec::new();
    for p in &samples {
        let b = std::fs::read(p)?;
        if !b.is_empty() {
            bufs.push(b);
        }
    }
    let refs: Vec<&[u8]> = bufs.iter().map(|b| b.as_slice()).collect();
    let dict = if simple {
        Dictionary::train_simple(&refs, max_size)?
    } else {
        zexc::train_cover(
            &refs,
            zexc::CoverParams {
                d,
                dict_size: max_size,
                ..Default::default()
            },
        )?
    };
    std::fs::write(&output, &dict.data)?;
    eprintln!(
        "zexc: trained {} dict {} bytes id={:#x} → {}",
        if simple { "simple" } else { "COVER" },
        dict.data.len(),
        dict.id,
        output.display()
    );
    Ok(())
}

fn cmd_seek_compress(
    input: PathBuf,
    output: PathBuf,
    frame_kib: u32,
    level: u8,
    mode: zexc::CompressionMode,
    quiet: bool,
) -> anyhow::Result<()> {
    let src = read_input(&input)?;
    let out_path = output;
    let opts = CompressOptions::default()
        .mode(mode)
        .level(level)
        .threads(true);
    let frame_size = (frame_kib as usize).saturating_mul(1024).max(4096);
    let blob = zexc::compress_seekable(&src, frame_size, &opts)?;
    write_output(&out_path, &blob)?;
    if !quiet {
        let table = zexc::SeekTable::from_trailer(&blob)?;
        eprintln!(
            "zexc: seekable {} → {} ({} frames, {} bytes)",
            path_label(&input),
            path_label(&out_path),
            table.entries.len(),
            blob.len()
        );
    }
    Ok(())
}

fn cmd_archive(action: ArchiveCmd, quiet: bool) -> anyhow::Result<()> {
    match action {
        ArchiveCmd::Create {
            files,
            output,
            level,
            mode,
        } => {
            if files.is_empty() {
                anyhow::bail!("usage: zexc archive create OUT.zexa FILE [FILE...]");
            }
            let opts = CompressOptions::default()
                .mode(mode.into())
                .level(level)
                .threads(true);
            if !quiet {
                progress(quiet, &format!("archiving {} files…", files.len()));
            }
            let arc = create_from_paths(&files, &opts)?;
            std::fs::write(&output, &arc)?;
            if !quiet {
                eprintln!(
                    "zexc: created {} ({} bytes, {} members)",
                    output.display(),
                    arc.len(),
                    files.len()
                );
            }
        }
        ArchiveCmd::List { archive } => {
            let data = std::fs::read(&archive)?;
            let items = list_archive(&data)?;
            println!("{} — {} entries", archive.display(), items.len());
            for it in items {
                println!(
                    "  {:8}  {:8}  {}",
                    it.uncompressed_size, it.frame_size, it.name
                );
            }
        }
        ArchiveCmd::Extract { archive, dir } => {
            let data = std::fs::read(&archive)?;
            let names = extract_to_dir(&data, &dir, &DecompressOptions::default())?;
            if !quiet {
                eprintln!("zexc: extracted {} files → {}", names.len(), dir.display());
            }
        }
    }
    Ok(())
}

// Note: archive create argument order is: OUTPUT then FILES (see ArchiveCmd::Create)

fn cmd_bench(
    input: PathBuf,
    level: u8,
    mode: zexc::CompressionMode,
    iters: u32,
    quiet: bool,
) -> anyhow::Result<()> {
    let src = std::fs::read(&input)?;
    let opts = CompressOptions::default()
        .mode(mode)
        .level(level)
        .threads(false);
    let iters = iters.max(1);

    // Warmup
    let _ = compress(&src, &opts)?;

    let t0 = Instant::now();
    let mut last = Vec::new();
    for _ in 0..iters {
        last = compress(&src, &opts)?;
    }
    let ct = t0.elapsed().as_secs_f64() / f64::from(iters);

    let t1 = Instant::now();
    for _ in 0..iters {
        let _ = decompress(&last)?;
    }
    let dt = t1.elapsed().as_secs_f64() / f64::from(iters);

    let mb = src.len() as f64 / (1024.0 * 1024.0);
    if !quiet {
        println!("file:     {}", input.display());
        println!("size:     {} bytes", src.len());
        println!("level:    {level}  mode: {mode}");
        println!("iters:    {iters}");
        println!(
            "compress: {:.3} s  ({:.1} MiB/s)  → {} bytes ({:.2}%)",
            ct,
            mb / ct.max(1e-9),
            last.len(),
            100.0 * last.len() as f64 / src.len().max(1) as f64
        );
        println!("decompress: {:.3} s  ({:.1} MiB/s)", dt, mb / dt.max(1e-9));
    }
    Ok(())
}