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
// fyes — output a string repeatedly until killed
//
// Usage: yes [STRING]...
// Repeatedly output a line with all specified STRING(s), or 'y'.

use std::process;
#[cfg(unix)]
use std::sync::atomic::{AtomicBool, Ordering};

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

/// Buffer size for bulk writes. 128KB is 2x the default Linux pipe buffer
/// (64KB) and large enough to amortize syscall overhead while staying in
/// L2 cache. Outperforms GNU yes's 8KB BUFSIZ for both pipe and /dev/null.
const BUF_SIZE: usize = 128 * 1024;

/// True if the inherited SIGPIPE handler (before Rust's runtime overwrites it)
/// was SIG_IGN. Captured by a pre-main() constructor.
#[cfg(unix)]
static INHERITED_SIGPIPE_IGN: AtomicBool = AtomicBool::new(false);

/// Pre-main() constructor that captures the inherited SIGPIPE handler before
/// Rust's runtime sets it to SIG_IGN in `reset_sigpipe()`.
///
/// .init_array / __mod_init_func constructors run after the dynamic linker
/// but before `main()` (and thus before Rust's `lang_start()` → `init()` →
/// `reset_sigpipe()`), so the handler at this point is whatever the parent
/// process (usually bash) set up via exec().
///
/// GNU yes (a C binary) inherits its SIGPIPE handler directly. In normal
/// shells, bash passes SIG_DFL → SIGPIPE kills silently. Under Node.js CI
/// runners, bash inherits and preserves SIG_IGN (POSIX requirement for
/// terminating signals) → write() returns EPIPE → error message printed.
#[cfg(unix)]
unsafe extern "C" fn sigpipe_check_init() {
    unsafe {
        let mut old: libc::sigaction = std::mem::zeroed();
        if libc::sigaction(libc::SIGPIPE, std::ptr::null(), &mut old) == 0
            && old.sa_sigaction == libc::SIG_IGN
        {
            INHERITED_SIGPIPE_IGN.store(true, Ordering::Relaxed);
        }
    }
}

#[cfg(target_os = "linux")]
#[used]
#[unsafe(link_section = ".init_array")]
static SIGPIPE_INIT: unsafe extern "C" fn() = sigpipe_check_init;

#[cfg(target_os = "macos")]
#[used]
#[unsafe(link_section = "__DATA,__mod_init_func")]
static SIGPIPE_INIT: unsafe extern "C" fn() = sigpipe_check_init;

fn main() {
    // Match GNU yes's SIGPIPE behavior exactly. The pre-main() constructor
    // captured the inherited SIGPIPE handler before Rust changed it.
    //
    // If inherited SIG_DFL: restore it so SIGPIPE kills us silently.
    // If inherited SIG_IGN: keep Rust's SIG_IGN, write() returns EPIPE,
    // and our error handler prints the message (matching GNU yes).
    #[cfg(unix)]
    unsafe {
        if !INHERITED_SIGPIPE_IGN.load(Ordering::Relaxed) {
            let mut sa: libc::sigaction = std::mem::zeroed();
            sa.sa_sigaction = libc::SIG_DFL;
            sa.sa_flags = 0;
            libc::sigemptyset(&mut sa.sa_mask);
            libc::sigaction(libc::SIGPIPE, &sa, std::ptr::null_mut());
        }
    }

    let raw_args: Vec<String> = std::env::args().skip(1).collect();

    // GNU yes: scan args BEFORE "--" for --help / --version (GNU permutation behavior)
    // Once "--" is seen, --help/--version are literal strings, not options.
    // Unknown long options (--anything) and short options (-x) are rejected.
    // Bare "-" is treated as a literal string.
    for arg in &raw_args {
        if arg == "--" {
            break; // stop scanning for options
        }
        match arg.as_str() {
            "--help" => {
                println!("Usage: {} [STRING]...", TOOL_NAME);
                println!("  or:  {} OPTION", TOOL_NAME);
                println!("Repeatedly output a line with all specified STRING(s), or 'y'.");
                println!();
                println!("      --help     display this help and exit");
                println!("      --version  output version information and exit");
                process::exit(0);
            }
            "--version" => {
                println!("{} (fcoreutils) {}", TOOL_NAME, VERSION);
                process::exit(0);
            }
            s if s.starts_with("--") => {
                eprintln!(
                    "{}: unrecognized option '{}'\nTry '{} --help' for more information.",
                    TOOL_NAME, s, TOOL_NAME
                );
                process::exit(1);
            }
            s if s.starts_with('-') && s.len() > 1 => {
                let first_char = s.as_bytes()[1] as char;
                eprintln!(
                    "{}: invalid option -- '{}'\nTry '{} --help' for more information.",
                    TOOL_NAME, first_char, TOOL_NAME
                );
                process::exit(1);
            }
            _ => {}
        }
    }

    // Build output from remaining args (unknown options already rejected above).
    // The first "--" terminates option scanning; subsequent args are literal.
    // Bare "-" is treated as a literal string (not an option).
    let mut end_of_opts = false;
    let mut output_args: Vec<&str> = Vec::new();

    for arg in &raw_args {
        if end_of_opts {
            output_args.push(arg.as_str());
            continue;
        }

        if arg == "--" {
            end_of_opts = true;
            continue;
        }

        output_args.push(arg.as_str());
    }

    let line = if output_args.is_empty() {
        "y\n".to_string()
    } else {
        let mut s = output_args.join(" ");
        s.push('\n');
        s
    };

    let line_bytes = line.as_bytes();
    let line_len = line_bytes.len();

    // Detect whether stdout is a pipe via F_GETPIPE_SZ.
    // When writing to a pipe, use GNU yes's BUFSIZ (8192) to match EPIPE
    // timing exactly — this ensures error messages interleave with data
    // identically when stderr/stdout are merged (2>&1 in test harnesses).
    // For non-pipe targets (/dev/null, files), use the larger BUF_SIZE.
    #[cfg(target_os = "linux")]
    let is_pipe = unsafe { libc::fcntl(1, libc::F_GETPIPE_SZ) > 0 };
    #[cfg(not(target_os = "linux"))]
    let is_pipe = false;

    const GNU_BUFSIZ: usize = 8192;
    let buf_target = if is_pipe { GNU_BUFSIZ } else { BUF_SIZE };

    // Build a buffer filled with repeated copies of the line.
    // The buffer length is always an exact multiple of line_len so that
    // every write boundary falls between complete lines. This prevents
    // partial lines from appearing when downstream consumers (e.g.,
    // `head -n 2 | uniq`) read at write boundaries.
    //
    // When a single line is already >= buf_target, use exactly one copy
    // to avoid allocating a needlessly huge buffer.
    let buf = if line_len >= buf_target {
        line_bytes.to_vec()
    } else {
        // Number of whole copies that fit within buf_target bytes.
        // Uses floor division to match GNU yes's BUFSIZ/line_len behavior,
        // ensuring identical write sizes for identical buffer targets.
        let copies = (buf_target / line_len).max(1);
        let mut v = Vec::with_capacity(copies * line_len);
        for _ in 0..copies {
            v.extend_from_slice(line_bytes);
        }
        v
    };
    let total = buf.len();

    // Write loop dispatch:
    // - Pipes: use libc::write() to match GNU yes's full_write() timing
    //   and EPIPE detection, ensuring identical error interleaving.
    // - Non-pipes (/dev/null, files): use inline syscall for max throughput.
    let ptr = buf.as_ptr();
    if is_pipe {
        write_loop_libc(ptr, total);
    } else {
        write_loop_fast(ptr, total);
    }
}

/// Fast write loop for non-pipe targets (/dev/null, files).
/// Uses inline syscall on x86_64 Linux to bypass libc's PLT indirection
/// and errno-setting overhead.
#[inline(never)]
fn write_loop_fast(ptr: *const u8, total: usize) -> ! {
    let total_isize = total as isize;

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    loop {
        // Inline syscall: write(1, ptr, total)
        let ret: isize;
        unsafe {
            std::arch::asm!(
                "syscall",
                in("rax") 1_u64,       // SYS_write
                in("rdi") 1_u64,       // fd = stdout
                in("rsi") ptr,         // buf
                in("rdx") total,       // count
                lateout("rax") ret,
                lateout("rcx") _,      // clobbered by syscall
                lateout("r11") _,      // clobbered by syscall
                options(nostack),
            );
        }
        if ret == total_isize {
            continue; // fast path: full write
        }
        if ret > 0 {
            // Partial write — drain remainder via libc (rare path)
            drain_partial(ptr, total, ret as usize);
            continue;
        }
        if ret == 0 {
            // write(2) returned 0 for non-zero count — exit to avoid spin.
            process::exit(1);
        }
        // Negative return = -errno
        let errno = (-ret) as i32;
        if errno == libc::EINTR {
            continue;
        }
        let err = std::io::Error::from_raw_os_error(errno);
        write_error_and_exit(&err);
    }

    #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
    loop {
        let ret = unsafe { libc::write(1, ptr as *const libc::c_void, total as _) };
        if ret as isize == total_isize {
            continue;
        }
        if ret > 0 {
            drain_partial(ptr, total, ret as usize);
            continue;
        }
        if ret == 0 {
            process::exit(1);
        }
        let err = std::io::Error::last_os_error();
        if err.kind() == std::io::ErrorKind::Interrupted {
            continue;
        }
        write_error_and_exit(&err);
    }
}

/// Compat write loop for pipe targets. Uses libc::write() to match GNU
/// yes's full_write() behavior, ensuring identical EPIPE detection timing
/// and error message interleaving when stderr/stdout share a fd.
#[inline(never)]
fn write_loop_libc(ptr: *const u8, total: usize) -> ! {
    let total_isize = total as isize;
    loop {
        let ret = unsafe { libc::write(1, ptr as *const libc::c_void, total as _) };
        if ret as isize == total_isize {
            continue;
        }
        if ret > 0 {
            drain_partial(ptr, total, ret as usize);
            continue;
        }
        if ret == 0 {
            process::exit(1);
        }
        let err = std::io::Error::last_os_error();
        if err.kind() == std::io::ErrorKind::Interrupted {
            continue;
        }
        write_error_and_exit(&err);
    }
}

/// Drain remaining bytes after a partial write. Rare path — kept out of
/// the hot loop to reduce instruction cache pressure.
#[cold]
#[inline(never)]
fn drain_partial(ptr: *const u8, total: usize, initial: usize) {
    let mut written = initial;
    while written < total {
        let r = unsafe {
            libc::write(
                1,
                ptr.add(written) as *const libc::c_void,
                (total - written) as _,
            )
        };
        if r > 0 {
            written += r as usize;
        } else if r == 0 {
            process::exit(1);
        } else {
            let e = std::io::Error::last_os_error();
            if e.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            write_error_and_exit(&e);
        }
    }
}

/// Write error diagnostic to stderr and exit. Cold path — never inlined
/// to keep the hot loop's instruction footprint minimal.
///
/// On Linux, formats the error into a single buffer and writes it with one
/// write(2) syscall to avoid interleaving when stderr is merged with stdout
/// (e.g. `yes 2>&1 | head`).
#[cold]
#[inline(never)]
fn write_error_and_exit(err: &std::io::Error) -> ! {
    #[cfg(target_os = "linux")]
    {
        if let Some(errno) = err.raw_os_error() {
            // Use a single write(2) syscall to avoid interleaving when stderr
            // is merged with stdout (e.g. `yes 2>&1 | head`).
            unsafe {
                let mut strerr_buf = [0u8; 256];
                let rc = libc::strerror_r(
                    errno,
                    strerr_buf.as_mut_ptr() as *mut libc::c_char,
                    strerr_buf.len(),
                );
                let err_str = if rc == 0 {
                    std::ffi::CStr::from_ptr(strerr_buf.as_ptr() as *const libc::c_char)
                        .to_str()
                        .unwrap_or("Unknown error")
                } else {
                    "Unknown error"
                };
                // Single write(2) with the full message
                let msg = format!("yes: standard output: {}\n", err_str);
                libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len() as _);
                libc::_exit(1);
            }
        }
    }

    // Fallback for non-Linux or errors without an OS error code
    let msg = coreutils_rs::common::io_error_msg(err);
    let error_line = format!("{}: standard output: {}\n", TOOL_NAME, msg);
    let _ = unsafe {
        libc::write(
            2,
            error_line.as_ptr() as *const libc::c_void,
            error_line.len() as _,
        )
    };
    #[cfg(unix)]
    unsafe {
        libc::_exit(1)
    };
    #[cfg(not(unix))]
    process::exit(1);
}

#[cfg(test)]
mod tests {
    use std::io::Read;
    use std::process::{Command, Stdio};

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fyes");
        Command::new(path)
    }

    fn cmd_path() -> String {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fyes");
        path.to_string_lossy().into_owned()
    }

    #[test]
    fn test_yes_default_y() {
        let mut child = cmd().stdout(Stdio::piped()).spawn().unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 10 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(
            lines.len() >= 5,
            "Expected at least 5 lines, got {}",
            lines.len()
        );
        for line in &lines[..5] {
            assert_eq!(*line, "y");
        }
    }

    #[test]
    fn test_yes_custom_string() {
        let mut child = cmd().arg("hello").stdout(Stdio::piped()).spawn().unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 20 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(
            lines.len() >= 3,
            "Expected at least 3 lines, got {}",
            lines.len()
        );
        for line in &lines[..3] {
            assert_eq!(*line, "hello");
        }
    }

    #[test]
    fn test_yes_multiple_args() {
        let mut child = cmd()
            .args(["a", "b"])
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 20 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(
            lines.len() >= 2,
            "Expected at least 2 lines, got {}",
            lines.len()
        );
        for line in &lines[..2] {
            assert_eq!(*line, "a b");
        }
    }

    #[test]
    fn test_yes_dash_dash_strips_separator() {
        // yes -- foo should output "foo", not "-- foo"
        let mut child = cmd()
            .args(["--", "foo"])
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 20 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(lines.len() >= 2);
        for line in &lines[..2] {
            assert_eq!(*line, "foo");
        }
    }

    #[test]
    fn test_yes_dash_dash_alone_gives_y() {
        // yes -- should output "y", not "--"
        let mut child = cmd().arg("--").stdout(Stdio::piped()).spawn().unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 20 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(lines.len() >= 2);
        for line in &lines[..2] {
            assert_eq!(*line, "y");
        }
    }

    #[test]
    fn test_yes_pipe_closes() {
        // yes piped to head should terminate (killed by SIGPIPE)
        let mut child = cmd()
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let child_stdout = child.stdout.take().unwrap();

        let head = Command::new("head")
            .arg("-n")
            .arg("1")
            .stdin(child_stdout)
            .stdout(Stdio::piped())
            .output()
            .unwrap();

        // Wait for the child process
        let status = child.wait().unwrap();

        assert_eq!(head.status.code(), Some(0));
        let text = String::from_utf8_lossy(&head.stdout);
        assert_eq!(text.trim(), "y");

        // With SIGPIPE unblocked: killed by SIGPIPE. With SIGPIPE blocked: EPIPE fallback exits 1.
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            assert!(
                status.signal() == Some(13) || status.code() == Some(1),
                "yes should be killed by SIGPIPE or exit 1, got status: {:?}",
                status
            );
        }
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_broken_pipe_terminates() {
        // When stdout is closed, yes should be killed by SIGPIPE.
        let mut child = cmd()
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();

        // Read a few bytes then close stdout to trigger SIGPIPE
        let mut stdout = child.stdout.take().unwrap();
        let mut buf = [0u8; 4];
        let _ = std::io::Read::read(&mut stdout, &mut buf);
        drop(stdout);

        let status = child.wait().unwrap();

        use std::os::unix::process::ExitStatusExt;
        assert!(
            status.signal() == Some(13) || status.code() == Some(1),
            "yes should be killed by SIGPIPE or exit 0/1, got status: {:?}",
            status
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_matches_gnu() {
        // Compare first 1000 lines with GNU yes
        let gnu = Command::new("sh")
            .args(["-c", "yes | head -n 1000"])
            .output();
        if let Ok(gnu) = gnu {
            let ours = Command::new("sh")
                .args([
                    "-c",
                    &format!("{} | head -n 1000", cmd().get_program().to_str().unwrap()),
                ])
                .output()
                .unwrap();
            assert_eq!(
                String::from_utf8_lossy(&ours.stdout),
                String::from_utf8_lossy(&gnu.stdout),
                "Output mismatch with GNU yes"
            );
        }
    }

    /// Helper: run `fyes <padded_arg> | head -n 2` and verify both lines are identical.
    /// This catches buffer-boundary splits that produce partial lines.
    #[cfg(unix)]
    fn assert_padded_string_unique(pad_len: usize) {
        let padded: String = " ".repeat(pad_len);
        let mut child = cmd().arg(&padded).stdout(Stdio::piped()).spawn().unwrap();

        let child_stdout = child.stdout.take().unwrap();

        let head = Command::new("head")
            .args(["-n", "2"])
            .stdin(child_stdout)
            .stdout(Stdio::piped())
            .output()
            .unwrap();

        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&head.stdout);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(
            lines.len(),
            2,
            "pad_len={}: expected 2 lines from head, got {}",
            pad_len,
            lines.len()
        );
        assert_eq!(
            lines[0],
            lines[1],
            "pad_len={}: the two lines differ (buffer split mid-line)\n  line0 len={}\n  line1 len={}",
            pad_len,
            lines[0].len(),
            lines[1].len()
        );
        assert_eq!(
            lines[0].len(),
            pad_len,
            "pad_len={}: line length mismatch",
            pad_len
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_1999_char_padded_string() {
        assert_padded_string_unique(1999);
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_4095_char_padded_string() {
        assert_padded_string_unique(4095);
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_4096_char_padded_string() {
        assert_padded_string_unique(4096);
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_8191_char_padded_string() {
        assert_padded_string_unique(8191);
    }

    #[test]
    #[cfg(unix)]
    fn test_yes_8192_char_padded_string() {
        assert_padded_string_unique(8192);
    }

    /// Verify that yes terminates cleanly when piped through head.
    #[test]
    #[cfg(unix)]
    fn test_yes_pipeline_terminates() {
        let mut child = cmd()
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();

        let child_stdout = child.stdout.take().unwrap();

        // Pipe through head -n 5 to trigger SIGPIPE
        let head = Command::new("head")
            .args(["-n", "5"])
            .stdin(child_stdout)
            .stdout(Stdio::piped())
            .output()
            .unwrap();

        let status = child.wait().unwrap();

        assert_eq!(head.status.code(), Some(0));

        use std::os::unix::process::ExitStatusExt;
        assert!(
            status.signal() == Some(13) || status.code() == Some(1),
            "yes should be killed by SIGPIPE or exit 0/1, got status: {:?}",
            status
        );
    }

    #[test]
    fn test_yes_unknown_long_option() {
        let output = cmd()
            .arg("--badopt")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("yes: unrecognized option '--badopt'"),
            "stderr should contain unrecognized option message, got: {}",
            stderr
        );
        assert!(
            stderr.contains("Try 'yes --help' for more information."),
            "stderr should contain help hint, got: {}",
            stderr
        );
    }

    #[test]
    fn test_yes_unknown_short_option() {
        let output = cmd()
            .arg("-z")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("yes: invalid option -- 'z'"),
            "stderr should contain invalid option message, got: {}",
            stderr
        );
        assert!(
            stderr.contains("Try 'yes --help' for more information."),
            "stderr should contain help hint, got: {}",
            stderr
        );
    }

    #[test]
    fn test_yes_bare_dash_is_literal() {
        // Bare "-" should be treated as literal string, not an option
        let mut child = cmd().arg("-").stdout(Stdio::piped()).spawn().unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 10 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(lines.len() >= 2);
        for line in &lines[..2] {
            assert_eq!(*line, "-");
        }
    }

    #[test]
    fn test_yes_option_after_dashdash_is_literal() {
        // yes -- --badopt should output "--badopt" as a literal string
        let mut child = cmd()
            .args(["--", "--badopt"])
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        let mut stdout = child.stdout.take().unwrap();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        while buf.len() < 20 {
            let n = stdout.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf);
        let lines: Vec<&str> = text.lines().collect();
        assert!(lines.len() >= 2);
        for line in &lines[..2] {
            assert_eq!(*line, "--badopt");
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_yes_pipe_head() {
        // yes | head -1 should produce "y"
        let output = std::process::Command::new("sh")
            .args(["-c"])
            .arg(format!("{} | head -1", cmd_path()))
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "y");
    }

    #[test]
    fn test_yes_epipe_clean_exit() {
        // Pipe fyes to a process that closes early - should not panic
        let mut child = cmd()
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        // Read a small amount then drop to trigger EPIPE
        let mut stdout = child.stdout.take().unwrap();
        let mut buf = [0u8; 64];
        let _ = stdout.read(&mut buf);
        drop(stdout);
        let result = child.wait_with_output().unwrap();
        // Should exit (not panic). Exit code may be 1 or killed by signal
        let stderr = String::from_utf8_lossy(&result.stderr);
        assert!(
            !stderr.contains("panicked"),
            "fyes should not panic on EPIPE, stderr: {}",
            stderr
        );
    }

    #[test]
    fn test_yes_consistent_output() {
        // Verify output is consistently "y\n" repeated
        let mut child = cmd().stdout(Stdio::piped()).spawn().unwrap();
        let mut stdout = child.stdout.take().unwrap();
        let mut buf = vec![0u8; 8192];
        let mut total = 0;
        while total < buf.len() {
            let n = stdout.read(&mut buf[total..]).unwrap();
            if n == 0 {
                break;
            }
            total += n;
        }
        drop(stdout);
        let _ = child.kill();
        let _ = child.wait();

        let text = String::from_utf8_lossy(&buf[..total]);
        for line in text.lines() {
            assert_eq!(
                line.trim_end_matches('\r'),
                "y",
                "Expected 'y' but got '{}'",
                line
            );
        }
    }
}