fcoreutils 0.22.0

High-performance GNU coreutils replacement with SIMD and parallelism
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
use std::io::{self, BufRead, BufReader, BufWriter, Write};
#[cfg(unix)]
use std::mem::ManuallyDrop;
#[cfg(unix)]
use std::os::unix::io::FromRawFd;
use std::path::Path;
use std::process;

use coreutils_rs::common::io_error_msg;
use coreutils_rs::hash;

const TOOL_NAME: &str = "b2sum";

struct Cli {
    binary: bool,
    check: bool,
    ignore_missing: bool,
    length: usize,
    quiet: bool,
    status: bool,
    strict: bool,
    text: bool,
    tag: bool,
    warn: bool,
    zero: bool,
    files: Vec<String>,
}

/// Hand-rolled argument parser — eliminates clap's ~100-200µs initialization.
fn parse_args() -> Cli {
    let mut cli = Cli {
        binary: false,
        check: false,
        ignore_missing: false,
        length: 0,
        quiet: false,
        status: false,
        strict: false,
        text: false,
        tag: false,
        warn: false,
        zero: false,
        files: Vec::new(),
    };

    let mut args = std::env::args_os().skip(1);
    let mut saw_dashdash = false;
    #[allow(clippy::while_let_on_iterator)]
    while let Some(arg) = args.next() {
        let bytes = arg.as_encoded_bytes();
        if saw_dashdash {
            cli.files.push(arg.to_string_lossy().into_owned());
            continue;
        }
        if bytes == b"--" {
            saw_dashdash = true;
            continue;
        }
        if bytes.starts_with(b"--") {
            if bytes.starts_with(b"--length=") {
                let val = std::str::from_utf8(&bytes[9..]).unwrap_or("0");
                cli.length = val.parse().unwrap_or_else(|_| {
                    eprintln!("{}: invalid length: '{}'", TOOL_NAME, val);
                    process::exit(1);
                });
            } else {
                match bytes {
                    b"--binary" => cli.binary = true,
                    b"--check" => cli.check = true,
                    b"--ignore-missing" => cli.ignore_missing = true,
                    b"--length" => {
                        if let Some(v) = args.next() {
                            let s = v.to_string_lossy();
                            cli.length = s.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid length: '{}'", TOOL_NAME, s);
                                process::exit(1);
                            });
                        } else {
                            eprintln!("{}: option '--length' requires an argument", TOOL_NAME);
                            process::exit(1);
                        }
                    }
                    b"--quiet" => cli.quiet = true,
                    b"--status" => cli.status = true,
                    b"--strict" => cli.strict = true,
                    b"--text" => cli.text = true,
                    b"--tag" => cli.tag = true,
                    b"--warn" => cli.warn = true,
                    b"--zero" => cli.zero = true,
                    b"--help" => {
                        print!(
                            "Usage: {} [OPTION]... [FILE]...\n\
                            Print or check BLAKE2b (512-bit) checksums.\n\n\
                            With no FILE, or when FILE is -, read standard input.\n\n\
                            \x20 -b, --binary         read in binary mode\n\
                            \x20 -c, --check          read checksums from the FILEs and check them\n\
                            \x20 -l, --length=BITS    digest length in bits; must not exceed 512\n\
                            \x20                        and must be a multiple of 8\n\
                            \x20     --tag             create a BSD-style checksum\n\
                            \x20 -t, --text           read in text mode (default)\n\
                            \x20 -z, --zero           end each output line with NUL, not newline\n\n\
                            The following five options are useful only when verifying checksums:\n\
                            \x20     --ignore-missing  don't fail or report status for missing files\n\
                            \x20     --quiet           don't print OK for each successfully verified file\n\
                            \x20     --status          don't output anything, status code shows success\n\
                            \x20     --strict          exit non-zero for improperly formatted checksum lines\n\
                            \x20 -w, --warn           warn about improperly formatted checksum lines\n\n\
                            \x20     --help            display this help and exit\n\
                            \x20     --version         output version information and exit\n",
                            TOOL_NAME
                        );
                        process::exit(0);
                    }
                    b"--version" => {
                        println!("{} (fcoreutils) {}", TOOL_NAME, env!("CARGO_PKG_VERSION"));
                        process::exit(0);
                    }
                    _ => {
                        eprintln!(
                            "{}: unrecognized option '{}'",
                            TOOL_NAME,
                            arg.to_string_lossy()
                        );
                        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                        process::exit(1);
                    }
                }
            }
        } else if bytes.len() > 1 && bytes[0] == b'-' {
            let mut i = 1;
            while i < bytes.len() {
                match bytes[i] {
                    b'b' => cli.binary = true,
                    b'c' => cli.check = true,
                    b't' => cli.text = true,
                    b'w' => cli.warn = true,
                    b'z' => cli.zero = true,
                    b'l' => {
                        if i + 1 < bytes.len() {
                            let val = std::str::from_utf8(&bytes[i + 1..]).unwrap_or("0");
                            cli.length = val.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid length: '{}'", TOOL_NAME, val);
                                process::exit(1);
                            });
                            i = bytes.len();
                            continue;
                        } else if let Some(v) = args.next() {
                            let s = v.to_string_lossy();
                            cli.length = s.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid length: '{}'", TOOL_NAME, s);
                                process::exit(1);
                            });
                        } else {
                            eprintln!("{}: option requires an argument -- 'l'", TOOL_NAME);
                            process::exit(1);
                        }
                    }
                    _ => {
                        eprintln!("{}: invalid option -- '{}'", TOOL_NAME, bytes[i] as char);
                        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                        process::exit(1);
                    }
                }
                i += 1;
            }
        } else {
            cli.files.push(arg.to_string_lossy().into_owned());
        }
    }

    cli
}

/// Check if a filename needs escaping (contains backslash or newline).
#[inline]
fn needs_escape(name: &str) -> bool {
    name.bytes().any(|b| b == b'\\' || b == b'\n')
}

/// Escape a filename: replace `\` with `\\` and `\n` with `\n` (literal).
fn escape_filename(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 8);
    for b in name.bytes() {
        match b {
            b'\\' => out.push_str("\\\\"),
            b'\n' => out.push_str("\\n"),
            _ => out.push(b as char),
        }
    }
    out
}

/// Unescape a checksum-line filename: `\\` -> `\`, `\n` -> newline.
fn unescape_filename(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('\\') => out.push('\\'),
                Some('n') => out.push('\n'),
                Some(other) => {
                    out.push('\\');
                    out.push(other);
                }
                None => out.push('\\'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Enlarge pipe buffers on Linux for higher throughput.
#[cfg(target_os = "linux")]
fn enlarge_pipes() {
    const PIPE_SIZE: i32 = 8 * 1024 * 1024;
    unsafe {
        libc::fcntl(0, libc::F_SETPIPE_SZ, PIPE_SIZE);
        libc::fcntl(1, libc::F_SETPIPE_SZ, PIPE_SIZE);
    }
}

fn main() {
    coreutils_rs::common::reset_sigpipe();

    #[cfg(target_os = "linux")]
    enlarge_pipes();

    let cli = parse_args();

    // -l 0 means use default (512), matching GNU behavior
    let length = if cli.length == 0 { 512 } else { cli.length };

    // GNU caps at 512 silently for values > 512
    let length = if length > 512 { 512 } else { length };

    if length % 8 != 0 {
        eprintln!("{}: invalid length: '{}'", TOOL_NAME, cli.length);
        eprintln!("{}: length is not a multiple of 8", TOOL_NAME);
        process::exit(1);
    }

    // Validate flag combinations
    if cli.tag && cli.check {
        eprintln!(
            "{}: the --tag option is meaningless when verifying checksums",
            TOOL_NAME
        );
        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
        process::exit(1);
    }

    let output_bytes = length / 8;
    let files = if cli.files.is_empty() {
        vec!["-".to_string()]
    } else {
        cli.files.clone()
    };

    // Raw fd stdout on Unix for zero-overhead writes
    #[cfg(unix)]
    let mut raw = unsafe { ManuallyDrop::new(std::fs::File::from_raw_fd(1)) };
    #[cfg(unix)]
    let mut out = BufWriter::new(&mut *raw);
    #[cfg(not(unix))]
    let stdout = io::stdout();
    #[cfg(not(unix))]
    let mut out = BufWriter::new(stdout.lock());

    let had_error = if cli.check {
        run_check_mode(&cli, &files, &mut out)
    } else {
        run_hash_mode(&cli, &files, output_bytes, &mut out)
    };

    let _ = out.flush();
    if had_error {
        process::exit(1);
    }
}

fn run_hash_mode(cli: &Cli, files: &[String], output_bytes: usize, out: &mut impl Write) -> bool {
    let mut had_error = false;
    let has_stdin = files.iter().any(|f| f == "-");

    if has_stdin || files.len() == 1 {
        // Sequential for stdin or single file
        for filename in files {
            let hash_result = if filename == "-" {
                hash::blake2b_hash_stdin(output_bytes)
            } else {
                hash::blake2b_hash_file(Path::new(filename), output_bytes)
            };

            match hash_result {
                Ok(h) => {
                    let name = if filename == "-" {
                        "-"
                    } else {
                        filename.as_str()
                    };
                    write_output(out, cli, &h, name, output_bytes);
                }
                Err(e) => {
                    let _ = out.flush();
                    eprintln!("{}: {}: {}", TOOL_NAME, filename, io_error_msg(&e));
                    had_error = true;
                }
            }
        }
    } else {
        // Multi-file: use multi-core parallel hashing with work-stealing.
        // Each worker uses blake2b_hash_file which includes I/O pipelining
        // for large files on Linux.
        let paths: Vec<_> = files.iter().map(|f| Path::new(f.as_str())).collect();
        let results = hash::blake2b_hash_files_parallel(&paths, output_bytes);

        for (filename, result) in files.iter().zip(results) {
            match result {
                Ok(h) => {
                    write_output(out, cli, &h, filename, output_bytes);
                }
                Err(e) => {
                    let _ = out.flush();
                    eprintln!("{}: {}: {}", TOOL_NAME, filename, io_error_msg(&e));
                    had_error = true;
                }
            }
        }
    }

    had_error
}

#[inline]
fn write_output(
    out: &mut impl Write,
    cli: &Cli,
    hash_hex: &str,
    filename: &str,
    output_bytes: usize,
) {
    let bits = output_bytes * 8;
    if cli.tag {
        if cli.zero {
            let _ = hash::print_hash_tag_b2sum_zero(out, hash_hex, filename, bits);
        } else {
            let _ = hash::print_hash_tag_b2sum(out, hash_hex, filename, bits);
        }
    } else if cli.zero {
        // GNU defaults to binary mode on Linux; only -t (text) uses space
        let _ = hash::print_hash_zero(
            out,
            hash_hex,
            filename,
            cli.binary || (!cli.text && cfg!(windows)),
        );
    } else if needs_escape(filename) {
        let escaped = escape_filename(filename);
        let mode_char = if cli.binary || (!cli.text && cfg!(windows)) {
            '*'
        } else {
            ' '
        };
        let _ = writeln!(out, "\\{} {}{}", hash_hex, mode_char, escaped);
    } else {
        let _ = hash::print_hash(
            out,
            hash_hex,
            filename,
            cli.binary || (!cli.text && cfg!(windows)),
        );
    }
}

fn run_check_mode(cli: &Cli, files: &[String], out: &mut impl Write) -> bool {
    let mut had_error = false;
    let mut _total_ok: usize = 0;
    let mut total_fail: usize = 0;
    let mut total_fmt_errors: usize = 0;
    let mut total_read_errors: usize = 0;

    for filename in files {
        let reader: Box<dyn BufRead> = if filename == "-" {
            Box::new(BufReader::new(io::stdin().lock()))
        } else {
            match std::fs::File::open(filename) {
                Ok(f) => Box::new(BufReader::new(f)),
                Err(e) => {
                    eprintln!("{}: {}: {}", TOOL_NAME, filename, io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        };

        let display_name = if filename == "-" {
            "standard input".to_string()
        } else {
            filename.clone()
        };

        let (file_ok, file_fail, file_fmt, file_read, file_ignored) =
            check_one(cli, reader, &display_name, out);

        _total_ok += file_ok;
        total_fail += file_fail;
        total_fmt_errors += file_fmt;
        total_read_errors += file_read;

        if file_fail > 0 || file_read > 0 {
            had_error = true;
        }
        if cli.strict && file_fmt > 0 {
            had_error = true;
        }

        // "no properly formatted checksum lines found"
        if file_ok == 0 && file_fail == 0 && file_read == 0 && file_ignored == 0 && file_fmt > 0 {
            if !cli.status {
                let _ = out.flush();
                eprintln!(
                    "{}: {}: no properly formatted BLAKE2b checksum lines found",
                    TOOL_NAME, display_name
                );
            }
            // Subtract these from total so summary doesn't double-count
            total_fmt_errors -= file_fmt;
            had_error = true;
        }

        // GNU compat: when --ignore-missing is used and no file was verified
        if cli.ignore_missing && file_ok == 0 && file_fail == 0 && file_ignored > 0 {
            if !cli.status {
                let _ = out.flush();
                eprintln!("{}: {}: no file was verified", TOOL_NAME, display_name);
            }
            had_error = true;
        }
    }

    // Flush stdout before printing stderr warnings
    let _ = out.flush();

    // Print GNU-style summary warnings to stderr
    if !cli.status {
        if total_fail > 0 {
            let word = if total_fail == 1 {
                "computed checksum did NOT match"
            } else {
                "computed checksums did NOT match"
            };
            eprintln!("{}: WARNING: {} {}", TOOL_NAME, total_fail, word);
        }

        if total_read_errors > 0 {
            let word = if total_read_errors == 1 {
                "listed file could not be read"
            } else {
                "listed files could not be read"
            };
            eprintln!("{}: WARNING: {} {}", TOOL_NAME, total_read_errors, word);
        }

        if total_fmt_errors > 0 {
            let word = if total_fmt_errors == 1 {
                "line is"
            } else {
                "lines are"
            };
            eprintln!(
                "{}: WARNING: {} {} improperly formatted",
                TOOL_NAME, total_fmt_errors, word
            );
        }
    }

    if total_fail > 0 {
        had_error = true;
    }
    if cli.strict && total_fmt_errors > 0 {
        had_error = true;
    }

    had_error
}

/// Check checksums from one input source. Returns (ok, fail, fmt_errors, read_errors, ignored_missing).
fn check_one(
    cli: &Cli,
    reader: Box<dyn BufRead>,
    display_name: &str,
    out: &mut impl Write,
) -> (usize, usize, usize, usize, usize) {
    let mut ok_count: usize = 0;
    let mut mismatch_count: usize = 0;
    let mut format_errors: usize = 0;
    let mut read_errors: usize = 0;
    let mut ignored_missing: usize = 0;
    let mut line_num: usize = 0;

    for line_result in reader.lines() {
        line_num += 1;
        let line = match line_result {
            Ok(l) => l,
            Err(e) => {
                eprintln!("{}: {}: {}", TOOL_NAME, display_name, io_error_msg(&e));
                break;
            }
        };
        let line = line.trim_end();

        if line.is_empty() {
            continue;
        }

        // Handle backslash-escaped lines
        let line_content = line.strip_prefix('\\').unwrap_or(line);

        // Try parsing: standard format, then BSD tag format
        let (expected_hash, check_filename) =
            if let Some((h, f)) = hash::parse_check_line(line_content) {
                (h.to_string(), f.to_string())
            } else if let Some((h, f, _bits)) = hash::parse_check_line_tag(line_content) {
                (h.to_string(), f.to_string())
            } else {
                format_errors += 1;
                if cli.warn {
                    let _ = out.flush();
                    eprintln!(
                        "{}: {}: {}: improperly formatted BLAKE2b checksum line",
                        TOOL_NAME, display_name, line_num
                    );
                }
                continue;
            };

        // Validate hash: must be valid hex, even length, max 128 hex chars (64 bytes = 512 bits)
        if expected_hash.is_empty()
            || expected_hash.len() % 2 != 0
            || expected_hash.len() > 128
            || !expected_hash.bytes().all(|b| b.is_ascii_hexdigit())
        {
            format_errors += 1;
            if cli.warn {
                let _ = out.flush();
                eprintln!(
                    "{}: {}: {}: improperly formatted BLAKE2b checksum line",
                    TOOL_NAME, display_name, line_num
                );
            }
            continue;
        }
        let hash_bytes = expected_hash.len() / 2;

        // Unescape filename if original line was backslash-prefixed
        let check_filename = if line.starts_with('\\') {
            unescape_filename(&check_filename)
        } else {
            check_filename
        };

        // Hash the file with inferred length
        let actual = match hash::blake2b_hash_file(Path::new(&check_filename), hash_bytes) {
            Ok(h) => h,
            Err(e) => {
                if cli.ignore_missing && e.kind() == io::ErrorKind::NotFound {
                    ignored_missing += 1;
                    continue;
                }
                read_errors += 1;
                if !cli.status {
                    let _ = out.flush();
                    eprintln!("{}: {}: {}", TOOL_NAME, check_filename, io_error_msg(&e));
                    let _ = writeln!(out, "{}: FAILED open or read", check_filename);
                }
                continue;
            }
        };

        if actual.eq_ignore_ascii_case(&expected_hash) {
            ok_count += 1;
            if !cli.quiet && !cli.status {
                let _ = writeln!(out, "{}: OK", check_filename);
            }
        } else {
            mismatch_count += 1;
            if !cli.status {
                let _ = writeln!(out, "{}: FAILED", check_filename);
            }
        }
    }

    (
        ok_count,
        mismatch_count,
        format_errors,
        read_errors,
        ignored_missing,
    )
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fb2sum");
        Command::new(path)
    }
    #[cfg(unix)]
    #[test]
    fn test_hash_stdin() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"hello\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stdout = stdout.trim();
        assert!(stdout.contains("  -"), "Should contain filename marker");
    }

    #[test]
    fn test_hash_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("test.txt"));
    }

    #[test]
    fn test_check_mode() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        let checksum_line = String::from_utf8_lossy(&output.stdout);
        let checksums = dir.path().join("checksums.txt");
        std::fs::write(&checksums, checksum_line.as_ref()).unwrap();
        let output = cmd()
            .args(["--check", checksums.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("OK"));
    }

    #[test]
    fn test_tag_format() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd()
            .args(["--tag", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("BLAKE2b"));
    }

    #[cfg(unix)]
    #[test]
    fn test_length_option() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd()
            .args(["--length=256", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stdout = stdout.trim();
        // 256 bits = 64 hex chars
        let hash = stdout.split_whitespace().next().unwrap();
        assert_eq!(hash.len(), 64, "256-bit hash should be 64 hex chars");
    }

    #[cfg(unix)]
    #[test]
    fn test_empty_file_hash() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("empty.txt");
        std::fs::write(&file, "").unwrap();
        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stdout = stdout.trim();
        let hash = stdout.split_whitespace().next().unwrap();
        // BLAKE2b-512 of empty input is well-known
        assert_eq!(hash.len(), 128, "512-bit hash should be 128 hex chars");
    }

    #[test]
    fn test_empty_stdin_hash() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
    }

    #[test]
    fn test_multiple_files() {
        let dir = tempfile::tempdir().unwrap();
        let f1 = dir.path().join("a.txt");
        let f2 = dir.path().join("b.txt");
        std::fs::write(&f1, "aaa\n").unwrap();
        std::fs::write(&f2, "bbb\n").unwrap();
        let output = cmd()
            .args([f1.to_str().unwrap(), f2.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.lines().collect();
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn test_nonexistent_file() {
        let output = cmd().arg("/nonexistent/file.txt").output().unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_check_tampered() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "original\n").unwrap();
        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        let checksums = dir.path().join("checksums.txt");
        std::fs::write(&checksums, String::from_utf8_lossy(&output.stdout).as_ref()).unwrap();
        // Tamper with the file
        std::fs::write(&file, "tampered\n").unwrap();
        let check_output = cmd()
            .args(["--check", checksums.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(!check_output.status.success());
        let stdout = String::from_utf8_lossy(&check_output.stdout);
        assert!(stdout.contains("FAILED"));
    }

    #[test]
    fn test_check_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let checksums = dir.path().join("checksums.txt");
        std::fs::write(
            &checksums,
            "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890  nonexistent.txt\n",
        )
        .unwrap();
        let output = cmd()
            .args(["--check", checksums.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_invalid_length_not_multiple_of_8() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd()
            .args(["--length=7", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_tag_and_check_conflict() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("checksums.txt");
        std::fs::write(&file, "dummy\n").unwrap();
        let output = cmd()
            .args(["--tag", "--check", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_zero_terminated() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd().args(["-z", file.to_str().unwrap()]).output().unwrap();
        assert!(output.status.success());
        assert!(output.stdout.ends_with(&[0u8]));
    }

    #[test]
    fn test_binary_mode_flag() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello\n").unwrap();
        let output = cmd().args(["-b", file.to_str().unwrap()]).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains(" *"), "binary mode should use * marker");
    }

    #[test]
    fn test_invalid_option() {
        let output = cmd().arg("--invalid-flag").output().unwrap();
        assert!(!output.status.success());
    }
}