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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
// fbase32 — Base32 encode/decode data (GNU base32 replacement, RFC 4648)

use std::io::{self, Read, Write};
use std::process;

/// Write buffer directly to fd 1, bypassing BufWriter overhead.
#[cfg(unix)]
fn write_all_fd1(buf: &[u8]) -> bool {
    let mut pos = 0;
    while pos < buf.len() {
        let ret = unsafe {
            libc::write(
                1,
                buf[pos..].as_ptr() as *const libc::c_void,
                (buf.len() - pos) as _,
            )
        };
        if ret > 0 {
            pos += ret as usize;
        } else if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return false;
        } else {
            return false;
        }
    }
    true
}

#[cfg(not(unix))]
fn write_all_fd1(buf: &[u8]) -> bool {
    use std::io::Write;
    std::io::stdout().lock().write_all(buf).is_ok()
}

const TOOL_NAME: &str = "base32";
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Base32 alphabet per RFC 4648 (used only in test encode helper)
#[cfg(test)]
const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

/// Build a decoding table: maps ASCII byte -> 5-bit value (0-31), 0xFF for invalid.
const fn build_decode_table() -> [u8; 256] {
    let mut table = [0xFFu8; 256];
    let alpha = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    let mut i = 0;
    while i < 32 {
        table[alpha[i] as usize] = i as u8;
        // Also accept lowercase
        if alpha[i] >= b'A' && alpha[i] <= b'Z' {
            table[(alpha[i] - b'A' + b'a') as usize] = i as u8;
        }
        i += 1;
    }
    table
}

const DECODE_TABLE: [u8; 256] = build_decode_table();

struct Cli {
    decode: bool,
    ignore_garbage: bool,
    wrap: usize,
    file: Option<String>,
}

fn parse_args() -> Cli {
    let mut cli = Cli {
        decode: false,
        ignore_garbage: false,
        wrap: 76,
        file: None,
    };

    let mut args = std::env::args_os().skip(1);
    #[allow(clippy::while_let_on_iterator)]
    while let Some(arg) = args.next() {
        let bytes = arg.as_encoded_bytes();
        if bytes == b"--" {
            if let Some(f) = args.next() {
                cli.file = Some(f.to_string_lossy().into_owned());
            }
            break;
        }
        if bytes.starts_with(b"--") {
            if bytes.starts_with(b"--wrap=") {
                let val = std::str::from_utf8(&bytes[7..]).unwrap_or("76");
                cli.wrap = val.parse().unwrap_or_else(|_| {
                    eprintln!("{}: invalid wrap size: '{}'", TOOL_NAME, val);
                    process::exit(1);
                });
            } else {
                match bytes {
                    b"--decode" => cli.decode = true,
                    b"--ignore-garbage" => cli.ignore_garbage = true,
                    b"--wrap" => {
                        if let Some(v) = args.next() {
                            let s = v.to_string_lossy();
                            cli.wrap = s.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid wrap size: '{}'", TOOL_NAME, s);
                                process::exit(1);
                            });
                        } else {
                            eprintln!("{}: option '--wrap' requires an argument", TOOL_NAME);
                            process::exit(1);
                        }
                    }
                    b"--help" => {
                        print!(
                            "Usage: {tool} [OPTION]... [FILE]\n\
                             Base32 encode or decode FILE, or standard input, to standard output.\n\n\
                             With no FILE, or when FILE is -, read standard input.\n\n\
                             Mandatory arguments to long options are mandatory for short options too.\n\
                             \x20 -d, --decode          decode data\n\
                             \x20 -i, --ignore-garbage  when decoding, ignore non-alphabet characters\n\
                             \x20 -w, --wrap=COLS       wrap encoded lines after COLS character (default 76).\n\
                             \x20                         Use 0 to disable line wrapping\n\
                             \x20     --help             display this help and exit\n\
                             \x20     --version          output version information and exit\n\n\
                             The data are encoded as described for the base32 alphabet in RFC 4648.\n\
                             When decoding, the input may contain newlines in addition to the bytes of\n\
                             the formal base32 alphabet.  Use --ignore-garbage to attempt to recover\n\
                             from any other non-alphabet bytes in the encoded stream.\n",
                            tool = TOOL_NAME
                        );
                        process::exit(0);
                    }
                    b"--version" => {
                        println!("{} (fcoreutils) {}", TOOL_NAME, 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'd' => cli.decode = true,
                    b'i' => cli.ignore_garbage = true,
                    b'w' => {
                        if i + 1 < bytes.len() {
                            let val = std::str::from_utf8(&bytes[i + 1..]).unwrap_or("76");
                            cli.wrap = val.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid wrap size: '{}'", TOOL_NAME, val);
                                process::exit(1);
                            });
                            i = bytes.len();
                            continue;
                        } else if let Some(v) = args.next() {
                            let s = v.to_string_lossy();
                            cli.wrap = s.parse().unwrap_or_else(|_| {
                                eprintln!("{}: invalid wrap size: '{}'", TOOL_NAME, s);
                                process::exit(1);
                            });
                        } else {
                            eprintln!("{}: option requires an argument -- 'w'", 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.file = Some(arg.to_string_lossy().into_owned());
        }
    }

    cli
}

/// Encode binary data to Base32 bytes (used only by tests; streaming path uses encode_5_to_8).
#[cfg(test)]
fn base32_encode(data: &[u8]) -> Vec<u8> {
    if data.is_empty() {
        return Vec::new();
    }

    let out_len = data.len().div_ceil(5) * 8;
    let mut result = Vec::with_capacity(out_len);

    let full_chunks = data.len() / 5;
    let remainder = data.len() % 5;

    // Process all full 5-byte chunks without branch overhead
    let full_end = full_chunks * 5;
    let full_data = &data[..full_end];
    for chunk in full_data.chunks_exact(5) {
        let b0 = chunk[0];
        let b1 = chunk[1];
        let b2 = chunk[2];
        let b3 = chunk[3];
        let b4 = chunk[4];

        result.extend_from_slice(&[
            BASE32_ALPHABET[(b0 >> 3) as usize],
            BASE32_ALPHABET[((b0 & 0x07) << 2 | b1 >> 6) as usize],
            BASE32_ALPHABET[((b1 >> 1) & 0x1F) as usize],
            BASE32_ALPHABET[((b1 & 0x01) << 4 | b2 >> 4) as usize],
            BASE32_ALPHABET[((b2 & 0x0F) << 1 | b3 >> 7) as usize],
            BASE32_ALPHABET[((b3 >> 2) & 0x1F) as usize],
            BASE32_ALPHABET[((b3 & 0x03) << 3 | b4 >> 5) as usize],
            BASE32_ALPHABET[(b4 & 0x1F) as usize],
        ]);
    }

    // Handle the last partial chunk with padding
    if remainder > 0 {
        let chunk = &data[full_end..];
        let mut buf = [0u8; 5];
        buf[..chunk.len()].copy_from_slice(chunk);
        let b0 = buf[0];
        let b1 = buf[1];
        let b2 = buf[2];
        let b3 = buf[3];
        let b4 = buf[4];

        result.push(BASE32_ALPHABET[(b0 >> 3) as usize]);
        result.push(BASE32_ALPHABET[((b0 & 0x07) << 2 | b1 >> 6) as usize]);
        match remainder {
            1 => result.extend_from_slice(b"======"),
            2 => {
                result.push(BASE32_ALPHABET[((b1 >> 1) & 0x1F) as usize]);
                result.push(BASE32_ALPHABET[((b1 & 0x01) << 4 | b2 >> 4) as usize]);
                result.extend_from_slice(b"====");
            }
            3 => {
                result.push(BASE32_ALPHABET[((b1 >> 1) & 0x1F) as usize]);
                result.push(BASE32_ALPHABET[((b1 & 0x01) << 4 | b2 >> 4) as usize]);
                result.push(BASE32_ALPHABET[((b2 & 0x0F) << 1 | b3 >> 7) as usize]);
                result.extend_from_slice(b"===");
            }
            4 => {
                result.push(BASE32_ALPHABET[((b1 >> 1) & 0x1F) as usize]);
                result.push(BASE32_ALPHABET[((b1 & 0x01) << 4 | b2 >> 4) as usize]);
                result.push(BASE32_ALPHABET[((b2 & 0x0F) << 1 | b3 >> 7) as usize]);
                result.push(BASE32_ALPHABET[((b3 >> 2) & 0x1F) as usize]);
                result.push(BASE32_ALPHABET[((b3 & 0x03) << 3 | b4 >> 5) as usize]);
                result.push(b'=');
            }
            _ => unreachable!(),
        }
    }

    result
}

/// Decode Base32 string back to binary data.
/// Single-pass fused filter+decode with 8-byte-at-a-time fast path.
fn base32_decode(input: &[u8], ignore_garbage: bool) -> Result<Vec<u8>, String> {
    let mut result = Vec::with_capacity(input.len() * 5 / 8 + 5);
    let mut vals = [0u8; 8];
    let mut n = 0usize; // valid (non-padding) chars in current group
    let mut pos = 0usize; // total position in group (valid + padding)
    let mut i = 0usize;

    while i < input.len() {
        // Fast path: batch-decode consecutive 8-byte groups without newlines.
        // Stays in this tight loop as long as all 8 bytes are valid base32 chars.
        if pos == 0 {
            while i + 8 <= input.len() {
                let chunk = &input[i..i + 8];
                let v0 = DECODE_TABLE[chunk[0] as usize];
                let v1 = DECODE_TABLE[chunk[1] as usize];
                let v2 = DECODE_TABLE[chunk[2] as usize];
                let v3 = DECODE_TABLE[chunk[3] as usize];
                let v4 = DECODE_TABLE[chunk[4] as usize];
                let v5 = DECODE_TABLE[chunk[5] as usize];
                let v6 = DECODE_TABLE[chunk[6] as usize];
                let v7 = DECODE_TABLE[chunk[7] as usize];

                if (v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7) <= 0x1F {
                    result.extend_from_slice(&[
                        (v0 << 3) | (v1 >> 2),
                        (v1 << 6) | (v2 << 1) | (v3 >> 4),
                        (v3 << 4) | (v4 >> 1),
                        (v4 << 7) | (v5 << 2) | (v6 >> 3),
                        (v6 << 5) | v7,
                    ]);
                    i += 8;
                } else {
                    break;
                }
            }
            if i >= input.len() {
                break;
            }
        }

        // Slow path: process byte by byte
        let b = input[i];
        i += 1;

        if b == b'\n' || b == b'\r' {
            continue;
        }
        if b == b'=' {
            pos += 1;
            if pos == 8 {
                if n >= 2 {
                    result.push((vals[0] << 3) | (vals[1] >> 2));
                }
                if n >= 4 {
                    result.push((vals[1] << 6) | (vals[2] << 1) | (vals[3] >> 4));
                }
                if n >= 5 {
                    result.push((vals[3] << 4) | (vals[4] >> 1));
                }
                if n >= 7 {
                    result.push((vals[4] << 7) | (vals[5] << 2) | (vals[6] >> 3));
                }
                n = 0;
                pos = 0;
            }
            continue;
        }
        let v = DECODE_TABLE[b as usize];
        if v == 0xFF {
            if !ignore_garbage {
                return Err(format!("{}: invalid input", TOOL_NAME));
            }
            continue;
        }
        vals[pos] = v;
        n += 1;
        pos += 1;
        if pos == 8 {
            result.extend_from_slice(&[
                (vals[0] << 3) | (vals[1] >> 2),
                (vals[1] << 6) | (vals[2] << 1) | (vals[3] >> 4),
                (vals[3] << 4) | (vals[4] >> 1),
                (vals[4] << 7) | (vals[5] << 2) | (vals[6] >> 3),
                (vals[6] << 5) | vals[7],
            ]);
            n = 0;
            pos = 0;
        }
    }

    // Trailing partial group
    if n >= 2 {
        result.push((vals[0] << 3) | (vals[1] >> 2));
    }
    if n >= 4 {
        result.push((vals[1] << 6) | (vals[2] << 1) | (vals[3] >> 4));
    }
    if n >= 5 {
        result.push((vals[3] << 4) | (vals[4] >> 1));
    }
    if n >= 7 {
        result.push((vals[4] << 7) | (vals[5] << 2) | (vals[6] >> 3));
    }
    if n >= 8 {
        result.push((vals[6] << 5) | vals[7]);
    }

    Ok(result)
}

/// Map a 5-bit index (0-31) to its base32 ASCII character.
/// A-Z = 0-25, 2-7 = 26-31. Pure arithmetic, no table lookup.
#[inline(always)]
const fn b32_char(idx: u8) -> u8 {
    if idx < 26 {
        idx + b'A'
    } else {
        idx - 26 + b'2'
    }
}

/// Encode 5 bytes into 8 base32 characters directly into output buffer.
/// SWAR approach: packs 5 bytes into a u64, extracts 8 groups of 5 bits,
/// and converts each to a base32 character via arithmetic (no table lookup).
#[inline(always)]
fn encode_5_to_8(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, out: &mut [u8]) {
    let val: u64 =
        (b0 as u64) << 32 | (b1 as u64) << 24 | (b2 as u64) << 16 | (b3 as u64) << 8 | (b4 as u64);

    out[0] = b32_char(((val >> 35) & 0x1F) as u8);
    out[1] = b32_char(((val >> 30) & 0x1F) as u8);
    out[2] = b32_char(((val >> 25) & 0x1F) as u8);
    out[3] = b32_char(((val >> 20) & 0x1F) as u8);
    out[4] = b32_char(((val >> 15) & 0x1F) as u8);
    out[5] = b32_char(((val >> 10) & 0x1F) as u8);
    out[6] = b32_char(((val >> 5) & 0x1F) as u8);
    out[7] = b32_char((val & 0x1F) as u8);
}

/// Encode and write with line wrapping using raw fd1 writes.
/// Two-phase approach: batch-encode raw base32 chars, then insert newlines.
/// Eliminates per-5-byte copy_with_wrap overhead (was 2M calls for 10MB).
fn encode_streaming(data: &[u8], wrap: usize) -> io::Result<()> {
    if data.is_empty() {
        return Ok(());
    }

    let full_chunks = data.len() / 5;
    let remainder = data.len() % 5;
    let full_end = full_chunks * 5;

    // Process in 1MB input batches to amortize per-batch overhead
    const BATCH_INPUT: usize = 1024 * 1024;
    // Align batch to 5 bytes
    let batch_input = BATCH_INPUT / 5 * 5;
    // Output per batch: batch_input/5*8 raw + batch_input/5*8/wrap newlines + margin
    let batch_output_raw = batch_input / 5 * 8;
    let batch_output_wrapped = if wrap > 0 {
        batch_output_raw + batch_output_raw / wrap + 16
    } else {
        batch_output_raw + 16
    };
    let mut raw_buf = vec![0u8; batch_output_raw + 16];
    let mut wrap_buf = if wrap > 0 {
        vec![0u8; batch_output_wrapped]
    } else {
        Vec::new()
    };
    let mut col = 0usize;

    let mut input_pos = 0usize;
    while input_pos < full_end {
        let batch_end = (input_pos + batch_input).min(full_end);
        let batch = &data[input_pos..batch_end];

        // Encode batch into raw_buf
        let mut raw_offset = 0usize;
        for chunk in batch.chunks_exact(5) {
            encode_5_to_8(
                chunk[0],
                chunk[1],
                chunk[2],
                chunk[3],
                chunk[4],
                &mut raw_buf[raw_offset..],
            );
            raw_offset += 8;
        }

        if wrap == 0 {
            if !write_all_fd1(&raw_buf[..raw_offset]) {
                return Ok(());
            }
        } else {
            // Insert newlines in a single pass
            let written = insert_newlines(&raw_buf[..raw_offset], &mut wrap_buf, wrap, &mut col);
            if !write_all_fd1(&wrap_buf[..written]) {
                return Ok(());
            }
        }
        input_pos = batch_end;
    }

    // Handle the last partial chunk with padding
    if remainder > 0 {
        let chunk = &data[full_end..];
        let mut padded = [0u8; 5];
        padded[..chunk.len()].copy_from_slice(chunk);
        let (b0, b1, b2, b3, b4) = (padded[0], padded[1], padded[2], padded[3], padded[4]);

        let mut partial = [b'='; 8];
        let val: u64 = (b0 as u64) << 32
            | (b1 as u64) << 24
            | (b2 as u64) << 16
            | (b3 as u64) << 8
            | (b4 as u64);
        partial[0] = b32_char(((val >> 35) & 0x1F) as u8);
        partial[1] = b32_char(((val >> 30) & 0x1F) as u8);
        if remainder >= 2 {
            partial[2] = b32_char(((val >> 25) & 0x1F) as u8);
            partial[3] = b32_char(((val >> 20) & 0x1F) as u8);
        }
        if remainder >= 3 {
            partial[4] = b32_char(((val >> 15) & 0x1F) as u8);
        }
        if remainder >= 4 {
            partial[5] = b32_char(((val >> 10) & 0x1F) as u8);
            partial[6] = b32_char(((val >> 5) & 0x1F) as u8);
        }

        if wrap == 0 {
            write_all_fd1(&partial);
        } else {
            let mut tail_buf = [0u8; 24]; // 8 chars + possible newline + margin
            let written = insert_newlines(&partial, &mut tail_buf, wrap, &mut col);
            write_all_fd1(&tail_buf[..written]);
        }
    }

    // Final newline if there's a partial line
    if wrap > 0 && col > 0 {
        write_all_fd1(b"\n");
    }

    Ok(())
}

/// Insert newlines into raw encoded data at `wrap` column boundaries.
/// Single pass: copies chunks of (wrap - col) bytes, inserting \n between.
/// Returns number of bytes written to `out`.
#[inline]
fn insert_newlines(raw: &[u8], out: &mut [u8], wrap: usize, col: &mut usize) -> usize {
    let mut ri = 0usize;
    let mut wi = 0usize;

    while ri < raw.len() {
        let space = wrap - *col;
        let available = raw.len() - ri;
        let to_copy = space.min(available);
        out[wi..wi + to_copy].copy_from_slice(&raw[ri..ri + to_copy]);
        wi += to_copy;
        ri += to_copy;
        *col += to_copy;
        if *col == wrap {
            out[wi] = b'\n';
            wi += 1;
            *col = 0;
        }
    }
    wi
}

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

    let cli = parse_args();
    let filename = cli.file.as_deref().unwrap_or("-");

    let file_data = if filename == "-" {
        let mut buf = Vec::new();
        if let Err(e) = io::stdin().lock().read_to_end(&mut buf) {
            eprintln!("{}: {}", TOOL_NAME, coreutils_rs::common::io_error_msg(&e));
            process::exit(1);
        }
        coreutils_rs::common::io::FileData::Owned(buf)
    } else {
        match coreutils_rs::common::io::read_file(std::path::Path::new(filename)) {
            Ok(d) => d,
            Err(e) => {
                eprintln!(
                    "{}: {}: {}",
                    TOOL_NAME,
                    filename,
                    coreutils_rs::common::io_error_msg(&e)
                );
                process::exit(1);
            }
        }
    };
    let data: &[u8] = &file_data;

    let stdout = io::stdout();
    let mut out = io::BufWriter::with_capacity(1024 * 1024, stdout.lock());

    if cli.decode {
        match base32_decode(data, cli.ignore_garbage) {
            Ok(decoded) => {
                if let Err(e) = out.write_all(&decoded) {
                    if e.kind() == io::ErrorKind::BrokenPipe {
                        process::exit(0);
                    }
                    eprintln!("{}: write error: {}", TOOL_NAME, e);
                    process::exit(1);
                }
            }
            Err(msg) => {
                eprintln!("{}", msg);
                process::exit(1);
            }
        }
    } else {
        if let Err(e) = encode_streaming(data, cli.wrap) {
            if e.kind() == io::ErrorKind::BrokenPipe {
                process::exit(0);
            }
            eprintln!("{}: write error: {}", TOOL_NAME, e);
            process::exit(1);
        }
        return;
    }

    if let Err(e) = out.flush()
        && e.kind() != io::ErrorKind::BrokenPipe
    {
        eprintln!("{}: write error: {}", TOOL_NAME, e);
        process::exit(1);
    }
}

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

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fbase32");
        Command::new(path)
    }
    #[test]
    fn test_encode_hello() {
        // "Hello" in base32 is "JBSWY3DP"
        let mut child = cmd()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"Hello").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "JBSWY3DP");
    }

    #[test]
    fn test_encode_hello_newline() {
        // "Hello\n" in base32 is "JBSWY3DPBI======"
        let mut child = cmd()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::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);
        assert_eq!(stdout.trim(), "JBSWY3DPBI======");
    }

    #[test]
    fn test_decode() {
        let mut child = cmd()
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"JBSWY3DP\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(&output.stdout, b"Hello");
    }

    #[test]
    fn test_roundtrip() {
        let input = b"The quick brown fox jumps over the lazy dog";

        // Encode
        let mut child = cmd()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(input).unwrap();
        let encode_output = child.wait_with_output().unwrap();
        assert!(encode_output.status.success());

        // Decode
        let mut child = cmd()
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(&encode_output.stdout)
            .unwrap();
        let decode_output = child.wait_with_output().unwrap();
        assert!(decode_output.status.success());
        assert_eq!(&decode_output.stdout, input);
    }

    #[test]
    fn test_wrap_flag() {
        // Test -w 10 wraps at 10 columns
        let mut child = cmd()
            .arg("-w")
            .arg("10")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"Hello, World!")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            assert!(line.len() <= 10, "line longer than 10: {}", line);
        }
    }

    #[test]
    fn test_wrap_zero() {
        // -w 0 disables wrapping
        let mut child = cmd()
            .arg("-w")
            .arg("0")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"Hello, World! This is a longer test input to verify no wrapping.")
            .unwrap();
        let output = child.wait_with_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(), 1, "should be a single line with -w 0");
    }

    #[test]
    fn test_ignore_garbage() {
        // -i should ignore garbage characters during decode
        let mut child = cmd()
            .arg("-d")
            .arg("-i")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        // Insert garbage characters in base32 encoded "Hello"
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"JB!!S##WY3DP\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(&output.stdout, b"Hello");
    }

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

    #[test]
    fn test_encode_lib_function() {
        // Unit test encode directly
        assert_eq!(base32_encode(b""), b"");
        assert_eq!(base32_encode(b"f"), b"MY======");
        assert_eq!(base32_encode(b"fo"), b"MZXQ====");
        assert_eq!(base32_encode(b"foo"), b"MZXW6===");
        assert_eq!(base32_encode(b"foob"), b"MZXW6YQ=");
        assert_eq!(base32_encode(b"fooba"), b"MZXW6YTB");
        assert_eq!(base32_encode(b"foobar"), b"MZXW6YTBOI======");
    }

    #[test]
    fn test_decode_lib_function() {
        assert_eq!(base32_decode(b"", false).unwrap(), b"");
        assert_eq!(base32_decode(b"MY======", false).unwrap(), b"f");
        assert_eq!(base32_decode(b"MZXQ====", false).unwrap(), b"fo");
        assert_eq!(base32_decode(b"MZXW6===", false).unwrap(), b"foo");
        assert_eq!(base32_decode(b"MZXW6YQ=", false).unwrap(), b"foob");
        assert_eq!(base32_decode(b"MZXW6YTB", false).unwrap(), b"fooba");
        assert_eq!(
            base32_decode(b"MZXW6YTBOI======", false).unwrap(),
            b"foobar"
        );
    }

    #[test]
    fn test_compare_gnu_base32_encode() {
        if Command::new("base32").arg("--version").output().is_err() {
            return;
        }
        let input = b"Hello, World!\n";

        let mut gnu_child = match Command::new("base32")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            Err(_) => return,
        };
        gnu_child.stdin.take().unwrap().write_all(input).unwrap();
        let gnu_out = gnu_child.wait_with_output().unwrap();

        let mut our_child = cmd()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        our_child.stdin.take().unwrap().write_all(input).unwrap();
        let our_out = our_child.wait_with_output().unwrap();
        assert_eq!(
            String::from_utf8_lossy(&our_out.stdout),
            String::from_utf8_lossy(&gnu_out.stdout),
            "Encoding mismatch with GNU base32"
        );
    }

    #[test]
    fn test_compare_gnu_base32_decode() {
        if Command::new("base32").arg("--version").output().is_err() {
            return;
        }
        let encoded = b"JBSWY3DPEHPK3PXP\n";

        let mut gnu_child = match Command::new("base32")
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            Err(_) => return,
        };
        gnu_child.stdin.take().unwrap().write_all(encoded).unwrap();
        let gnu_out = gnu_child.wait_with_output().unwrap();

        let mut our_child = cmd()
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        our_child.stdin.take().unwrap().write_all(encoded).unwrap();
        let our_out = our_child.wait_with_output().unwrap();
        assert_eq!(
            our_out.stdout, gnu_out.stdout,
            "Decoding mismatch with GNU base32"
        );
    }

    #[test]
    fn test_long_decode_flag() {
        let mut child = cmd()
            .arg("--decode")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"JBSWY3DP\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(&output.stdout, b"Hello");
    }

    #[test]
    fn test_binary_roundtrip() {
        let data: Vec<u8> = (0..=255).collect();
        let mut enc = cmd()
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        enc.stdin.take().unwrap().write_all(&data).unwrap();
        let encoded = enc.wait_with_output().unwrap();
        assert!(encoded.status.success());

        let mut dec = cmd()
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        dec.stdin
            .take()
            .unwrap()
            .write_all(&encoded.stdout)
            .unwrap();
        let decoded = dec.wait_with_output().unwrap();
        assert!(decoded.status.success());
        assert_eq!(decoded.stdout, data);
    }

    #[test]
    fn test_decode_invalid_input() {
        let mut child = cmd()
            .arg("-d")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"!!!INVALID!!!\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_file_input() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "Hello").unwrap();
        let output = cmd().arg(file.to_str().unwrap()).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "JBSWY3DP");
    }

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

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

    #[test]
    fn test_rfc4648_vectors() {
        let test_cases: &[(&[u8], &str)] = &[
            (b"", ""),
            (b"f", "MY======"),
            (b"fo", "MZXQ===="),
            (b"foo", "MZXW6==="),
            (b"foob", "MZXW6YQ="),
            (b"fooba", "MZXW6YTB"),
            (b"foobar", "MZXW6YTBOI======"),
        ];
        for (input, expected) in test_cases {
            let mut child = cmd()
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::piped())
                .spawn()
                .unwrap();
            child.stdin.take().unwrap().write_all(input).unwrap();
            let output = child.wait_with_output().unwrap();
            assert!(output.status.success());
            assert_eq!(
                String::from_utf8_lossy(&output.stdout).trim(),
                *expected,
                "mismatch for {:?}",
                String::from_utf8_lossy(input)
            );
        }
    }
}