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
#[cfg(not(target_os = "linux"))]
use std::io::BufWriter;
use std::io::{self, BufReader, Write};
#[cfg(unix)]
use std::mem::ManuallyDrop;
#[cfg(unix)]
use std::os::unix::io::FromRawFd;
use std::path::Path;
use std::process;

#[cfg(unix)]
use coreutils_rs::common::io::try_mmap_stdin;
use coreutils_rs::common::io::{MmapHints, read_file_with_hints};
use coreutils_rs::common::{enlarge_stdout_pipe, io_error_msg};
use coreutils_rs::cut::{self, CutMode};

/// Writer that uses vmsplice(2) for zero-copy pipe output on Linux.
/// When stdout is a pipe, vmsplice references user-space pages directly
/// in the pipe buffer (no kernel memcpy). Falls back to regular write
/// for non-pipe fds (files, terminals).
#[cfg(target_os = "linux")]
struct VmspliceWriter {
    raw: ManuallyDrop<std::fs::File>,
    /// Whether stdout is a pipe (detected at construction via fstat).
    stdout_is_pipe: bool,
    /// Whether the current write source is safe for vmsplice (i.e., backed by
    /// mmap or a persistent buffer that won't be freed/reused while the pipe
    /// reader might still reference the pages). Callers toggle this before
    /// writing mmap-backed data directly.
    vmsplice_enabled: bool,
}

#[cfg(target_os = "linux")]
impl VmspliceWriter {
    fn new() -> Self {
        let raw = unsafe { ManuallyDrop::new(std::fs::File::from_raw_fd(1)) };
        // Detect if stdout is a pipe using fstat. vmsplice only works on pipes.
        let stdout_is_pipe = {
            let mut stat: libc::stat = unsafe { std::mem::zeroed() };
            let rc = unsafe { libc::fstat(1, &mut stat) };
            rc == 0 && (stat.st_mode & libc::S_IFMT) == libc::S_IFIFO
        };
        Self {
            raw,
            stdout_is_pipe,
            // Default off: only enable for writes from mmap-backed or
            // persistent buffers where pages remain valid after write returns.
            vmsplice_enabled: false,
        }
    }

    /// Enable or disable vmsplice for subsequent writes.
    ///
    /// # Safety contract
    /// Only enable when the data being written is backed by mmap pages or a
    /// buffer that will NOT be freed/reused until the pipe consumer reads it.
    /// vmsplice passes pages by reference to the pipe; if the backing memory
    /// is freed or overwritten before the reader consumes it, data corruption
    /// occurs.
    #[inline]
    fn set_vmsplice_enabled(&mut self, enabled: bool) {
        self.vmsplice_enabled = enabled;
    }
}

#[cfg(target_os = "linux")]
impl VmspliceWriter {
    /// Whether vmsplice is currently active (stdout is pipe AND caller enabled it).
    #[inline(always)]
    fn use_vmsplice(&self) -> bool {
        self.stdout_is_pipe && self.vmsplice_enabled
    }
}

#[cfg(target_os = "linux")]
impl Write for VmspliceWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if !self.use_vmsplice() || buf.is_empty() {
            return (&*self.raw).write(buf);
        }
        loop {
            let iov = libc::iovec {
                iov_base: buf.as_ptr() as *mut libc::c_void,
                iov_len: buf.len(),
            };
            let n = unsafe { libc::vmsplice(1, &iov, 1, 0) };
            if n >= 0 {
                return Ok(n as usize);
            }
            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            self.vmsplice_enabled = false;
            return (&*self.raw).write(buf);
        }
    }

    fn write_all(&mut self, mut buf: &[u8]) -> io::Result<()> {
        if !self.use_vmsplice() || buf.is_empty() {
            return (&*self.raw).write_all(buf);
        }
        while !buf.is_empty() {
            let iov = libc::iovec {
                iov_base: buf.as_ptr() as *mut libc::c_void,
                iov_len: buf.len(),
            };
            let n = unsafe { libc::vmsplice(1, &iov, 1, 0) };
            if n > 0 {
                buf = &buf[n as usize..];
            } else if n == 0 {
                return Err(io::Error::new(io::ErrorKind::WriteZero, "vmsplice wrote 0"));
            } else {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::Interrupted {
                    continue;
                }
                self.vmsplice_enabled = false;
                return (&*self.raw).write_all(buf);
            }
        }
        Ok(())
    }

    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
        if !self.use_vmsplice() || bufs.is_empty() {
            return (&*self.raw).write_vectored(bufs);
        }
        // SAFETY: IoSlice is #[repr(transparent)] over iovec on Unix,
        // so &[IoSlice] has the same memory layout as &[iovec].
        // Direct pointer cast eliminates Vec allocation + copy per call.
        // bufs may exceed UIO_MAXIOV (1024); .min(1024) below handles the split.
        loop {
            let count = bufs.len().min(1024);
            let iovs = bufs.as_ptr() as *const libc::iovec;
            let n = unsafe { libc::vmsplice(1, iovs, count, 0) };
            if n >= 0 {
                return Ok(n as usize);
            }
            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            self.vmsplice_enabled = false;
            return (&*self.raw).write_vectored(bufs);
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

struct Cli {
    bytes: Option<String>,
    characters: Option<String>,
    fields: Option<String>,
    delimiter: Option<String>,
    complement: bool,
    only_delimited: bool,
    output_delimiter: Option<String>,
    zero_terminated: bool,
    files: Vec<String>,
}

/// Hand-rolled argument parser — eliminates clap's ~100-200µs initialization.
/// cut's args: -b, -c, -f (with LIST), -d (with DELIM), -s, -z, -n, --complement,
/// --output-delimiter, and positional files.
fn parse_args() -> Cli {
    let mut cli = Cli {
        bytes: None,
        characters: None,
        fields: None,
        delimiter: None,
        complement: false,
        only_delimited: false,
        output_delimiter: None,
        zero_terminated: false,
        files: Vec::new(),
    };

    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"--" {
            // Everything after -- is positional
            for a in args {
                cli.files.push(a.to_string_lossy().into_owned());
            }
            break;
        }
        if bytes.starts_with(b"--") {
            // Long options
            if bytes.starts_with(b"--bytes=") {
                cli.bytes = Some(std::str::from_utf8(&bytes[8..]).unwrap_or("").to_string());
            } else if bytes.starts_with(b"--characters=") {
                cli.characters = Some(std::str::from_utf8(&bytes[13..]).unwrap_or("").to_string());
            } else if bytes.starts_with(b"--fields=") {
                cli.fields = Some(std::str::from_utf8(&bytes[9..]).unwrap_or("").to_string());
            } else if bytes.starts_with(b"--delimiter=") {
                cli.delimiter = Some(std::str::from_utf8(&bytes[12..]).unwrap_or("").to_string());
            } else if bytes.starts_with(b"--output-delimiter=") {
                cli.output_delimiter =
                    Some(std::str::from_utf8(&bytes[19..]).unwrap_or("").to_string());
            } else {
                match bytes {
                    b"--bytes" => {
                        if let Some(v) = args.next() {
                            cli.bytes = Some(v.to_string_lossy().into_owned());
                        } else {
                            eprintln!("cut: option '--bytes' requires an argument");
                            process::exit(1);
                        }
                    }
                    b"--characters" => {
                        if let Some(v) = args.next() {
                            cli.characters = Some(v.to_string_lossy().into_owned());
                        } else {
                            eprintln!("cut: option '--characters' requires an argument");
                            process::exit(1);
                        }
                    }
                    b"--fields" => {
                        if let Some(v) = args.next() {
                            cli.fields = Some(v.to_string_lossy().into_owned());
                        } else {
                            eprintln!("cut: option '--fields' requires an argument");
                            process::exit(1);
                        }
                    }
                    b"--delimiter" => {
                        if let Some(v) = args.next() {
                            cli.delimiter = Some(v.to_string_lossy().into_owned());
                        } else {
                            eprintln!("cut: option '--delimiter' requires an argument");
                            process::exit(1);
                        }
                    }
                    b"--output-delimiter" => {
                        if let Some(v) = args.next() {
                            cli.output_delimiter = Some(v.to_string_lossy().into_owned());
                        } else {
                            eprintln!("cut: option '--output-delimiter' requires an argument");
                            process::exit(1);
                        }
                    }
                    b"--complement" => cli.complement = true,
                    b"--only-delimited" => cli.only_delimited = true,
                    b"--zero-terminated" => cli.zero_terminated = true,
                    b"--help" => {
                        print!(
                            "Usage: cut OPTION... [FILE]...\n\
                            Print selected parts of lines from each FILE 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 -b, --bytes=LIST        select only these bytes\n\
                            \x20 -c, --characters=LIST   select only these characters\n\
                            \x20 -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter\n\
                            \x20 -f, --fields=LIST       select only these fields;  also print any line\n\
                            \x20                           that contains no delimiter character, unless\n\
                            \x20                           the -s option is specified\n\
                            \x20 -n                       (ignored)\n\
                            \x20     --complement         complement the set of selected bytes, characters\n\
                            \x20                           or fields\n\
                            \x20 -s, --only-delimited     do not print lines not containing delimiters\n\
                            \x20     --output-delimiter=STRING  use STRING as the output delimiter\n\
                            \x20                           the default is to use the input delimiter\n\
                            \x20 -z, --zero-terminated    line delimiter is NUL, not newline\n\
                            \x20     --help               display this help and exit\n\
                            \x20     --version            output version information and exit\n"
                        );
                        process::exit(0);
                    }
                    b"--version" => {
                        println!("cut (fcoreutils) {}", env!("CARGO_PKG_VERSION"));
                        process::exit(0);
                    }
                    _ => {
                        eprintln!("cut: unrecognized option '{}'", arg.to_string_lossy());
                        eprintln!("Try 'cut --help' for more information.");
                        process::exit(1);
                    }
                }
            }
        } else if bytes.len() > 1 && bytes[0] == b'-' {
            // Short options: can be combined (-sf1-3 means -s -f 1-3)
            let mut i = 1;
            while i < bytes.len() {
                match bytes[i] {
                    b'n' => {} // ignored (POSIX compat)
                    b's' => cli.only_delimited = true,
                    b'z' => cli.zero_terminated = true,
                    b'b' | b'c' | b'd' | b'f' => {
                        // These take a value: rest of arg or next arg
                        let flag = bytes[i];
                        let val = if i + 1 < bytes.len() {
                            // Value attached: -b1-3, -d:
                            std::str::from_utf8(&bytes[i + 1..])
                                .unwrap_or("")
                                .to_string()
                        } else if let Some(v) = args.next() {
                            v.to_string_lossy().into_owned()
                        } else {
                            eprintln!("cut: option requires an argument -- '{}'", flag as char);
                            process::exit(1);
                        };
                        match flag {
                            b'b' => cli.bytes = Some(val),
                            b'c' => cli.characters = Some(val),
                            b'd' => cli.delimiter = Some(val),
                            b'f' => cli.fields = Some(val),
                            _ => unreachable!(),
                        }
                        // Skip remaining bytes since they were consumed as value
                        i = bytes.len();
                        continue;
                    }
                    _ => {
                        eprintln!("cut: invalid option -- '{}'", bytes[i] as char);
                        eprintln!("Try 'cut --help' for more information.");
                        process::exit(1);
                    }
                }
                i += 1;
            }
        } else {
            cli.files.push(arg.to_string_lossy().into_owned());
        }
    }

    cli
}

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

    enlarge_stdout_pipe();

    // Pre-initialize rayon global thread pool to avoid 300-500us cold-start.
    let cpus = std::thread::available_parallelism()
        .map(|v| v.get().max(1))
        .unwrap_or(1);
    let _ = rayon::ThreadPoolBuilder::new()
        .num_threads(cpus.saturating_sub(1).max(1)) // n-1 pool threads; main thread joins as nth worker in rayon::scope
        .build_global();

    let cli = parse_args();

    // Determine mode
    let mode_count =
        cli.bytes.is_some() as u8 + cli.characters.is_some() as u8 + cli.fields.is_some() as u8;
    if mode_count == 0 {
        eprintln!("cut: you must specify a list of bytes, characters, or fields");
        eprintln!("Try 'cut --help' for more information.");
        process::exit(1);
    }
    if mode_count > 1 {
        eprintln!("cut: only one type of list may be specified");
        eprintln!("Try 'cut --help' for more information.");
        process::exit(1);
    }

    let (mode, spec) = if let Some(ref s) = cli.bytes {
        (CutMode::Bytes, s.as_str())
    } else if let Some(ref s) = cli.characters {
        (CutMode::Characters, s.as_str())
    } else {
        (CutMode::Fields, cli.fields.as_ref().unwrap().as_str())
    };

    // GNU cut: -s (--only-delimited) is only valid with -f
    if cli.only_delimited && mode != CutMode::Fields {
        eprintln!(
            "cut: suppressing non-delimited lines makes sense\n\tonly when operating on fields"
        );
        eprintln!("Try 'cut --help' for more information.");
        process::exit(1);
    }

    // GNU cut: -d (--delimiter) is only valid with -f
    if cli.delimiter.is_some() && mode != CutMode::Fields {
        eprintln!("cut: an input delimiter may be specified only when operating on fields");
        eprintln!("Try 'cut --help' for more information.");
        process::exit(1);
    }

    // When --output-delimiter is specified for bytes/chars mode, don't merge adjacent ranges
    // so the output delimiter is inserted between adjacent (but originally separate) ranges.
    let has_output_delim = cli.output_delimiter.is_some();
    let no_merge_adjacent = has_output_delim && mode != CutMode::Fields;

    let ranges = match cut::parse_ranges(spec, no_merge_adjacent) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("cut: {}", e);
            eprintln!("Try 'cut --help' for more information.");
            process::exit(1);
        }
    };

    let delim = if let Some(ref d) = cli.delimiter {
        if d.len() != 1 {
            eprintln!("cut: the delimiter must be a single character");
            eprintln!("Try 'cut --help' for more information.");
            process::exit(1);
        }
        d.as_bytes()[0]
    } else {
        b'\t'
    };

    // Default output delimiter: field delimiter for -f, empty for -b/-c
    // GNU cut only uses a delimiter between fields, not between byte/char ranges
    let output_delim = if let Some(ref od) = cli.output_delimiter {
        od.as_bytes().to_vec()
    } else if mode == CutMode::Fields {
        vec![delim]
    } else {
        vec![]
    };

    let line_delim = if cli.zero_terminated { b'\0' } else { b'\n' };

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

    // On Linux: VmspliceWriter directly — no BufWriter wrapper.
    // cut's batch processing already produces large output buffers (Vec<u8> or IoSlice),
    // so BufWriter's internal buffering is pure overhead (extra memcpy for output < 16MB).
    #[cfg(target_os = "linux")]
    let mut out = VmspliceWriter::new();
    // On other Unix: raw fd stdout with BufWriter
    #[cfg(all(unix, not(target_os = "linux")))]
    let mut raw = unsafe { ManuallyDrop::new(std::fs::File::from_raw_fd(1)) };
    #[cfg(all(unix, not(target_os = "linux")))]
    let mut out = BufWriter::with_capacity(16 * 1024 * 1024, &mut *raw);
    #[cfg(not(unix))]
    let stdout = io::stdout();
    #[cfg(not(unix))]
    let mut out = BufWriter::with_capacity(16 * 1024 * 1024, stdout.lock());
    let mut had_error = false;

    let cfg = cut::CutConfig {
        mode,
        ranges: &ranges,
        complement: cli.complement,
        delim,
        output_delim: &output_delim,
        suppress_no_delim: cli.only_delimited,
        line_delim,
    };

    // Try to mmap stdin for zero-copy (only used if stdin is a regular file)
    #[cfg(unix)]
    let stdin_mmap = {
        if files.iter().any(|f| f == "-") {
            try_mmap_stdin(0)
        } else {
            None
        }
    };

    // Pre-read all stdin data for piped input.
    // On Linux: try splice+memfd for zero-copy (kernel→kernel), fallback to read_stdin.
    // splice avoids the kernel→userspace copy, saving ~0.5ms for 10MB.
    #[cfg(target_os = "linux")]
    let splice_mmap: Option<memmap2::MmapMut> =
        if stdin_mmap.is_none() && files.iter().any(|f| f == "-") {
            coreutils_rs::common::io::splice_stdin_to_mmap().unwrap_or(None)
        } else {
            None
        };
    #[cfg(not(target_os = "linux"))]
    let splice_mmap: Option<memmap2::MmapMut> = None;

    #[allow(unused_variables)]
    let has_splice = splice_mmap.is_some();

    #[cfg(unix)]
    let mut stdin_buf: Option<Vec<u8>> =
        if stdin_mmap.is_none() && !has_splice && files.iter().any(|f| f == "-") {
            match coreutils_rs::common::io::read_stdin() {
                Ok(buf) => Some(buf),
                Err(e) => {
                    if e.kind() != io::ErrorKind::BrokenPipe {
                        eprintln!("cut: {}", io_error_msg(&e));
                        process::exit(1);
                    }
                    Some(Vec::new())
                }
            }
        } else {
            None
        };
    #[cfg(not(unix))]
    let mut stdin_buf: Option<Vec<u8>> = if files.iter().any(|f| f == "-") {
        match coreutils_rs::common::io::read_stdin() {
            Ok(buf) => Some(buf),
            Err(e) => {
                if e.kind() != io::ErrorKind::BrokenPipe {
                    eprintln!("cut: {}", io_error_msg(&e));
                    process::exit(1);
                }
                Some(Vec::new())
            }
        }
    } else {
        None
    };

    // For piped stdin with mutable data: try in-place extraction.
    // In-place avoids allocating intermediate Vec output buffers entirely.
    // Generalizes the old field-1-only path to all field and byte patterns.
    let mut stdin_inplace_done = false;

    // Try in-place on splice_mmap first (Linux: zero-copy pipe→memfd→mmap)
    #[cfg(target_os = "linux")]
    let mut splice_mmap = splice_mmap;
    #[cfg(target_os = "linux")]
    let mut splice_inplace_len: usize = 0;
    #[cfg(target_os = "linux")]
    if let Some(ref mut mmap_data) = splice_mmap
        && !mmap_data.is_empty()
        && let Some(new_len) = cut::process_cut_data_mut(mmap_data, &cfg)
    {
        splice_inplace_len = new_len;
        stdin_inplace_done = true;
    }

    // Try in-place on stdin_buf (Vec<u8>) if splice didn't handle it
    if !stdin_inplace_done
        && let Some(ref mut data) = stdin_buf
        && !data.is_empty()
        && let Some(new_len) = cut::process_cut_data_mut(data, &cfg)
    {
        data.truncate(new_len);
        stdin_inplace_done = true;
    }

    for filename in &files {
        let result: io::Result<()> = if filename == "-" {
            #[cfg(unix)]
            {
                if stdin_inplace_done {
                    // Write in-place processed data directly to output.
                    // Enable vmsplice: the backing memory (mmap or Vec) persists
                    // until end of main(), so pipe pages remain valid.
                    #[cfg(target_os = "linux")]
                    {
                        out.set_vmsplice_enabled(true);
                        let res = if splice_inplace_len > 0 {
                            if let Some(ref mmap_data) = splice_mmap {
                                out.write_all(&mmap_data[..splice_inplace_len])
                            } else {
                                Ok(())
                            }
                        } else if let Some(ref data) = stdin_buf {
                            out.write_all(data)
                        } else {
                            Ok(())
                        };
                        out.set_vmsplice_enabled(false);
                        res
                    }
                    #[cfg(not(target_os = "linux"))]
                    {
                        if let Some(ref data) = stdin_buf {
                            out.flush().and_then(|()| out.get_mut().write_all(data))
                        } else {
                            Ok(())
                        }
                    }
                } else if let Some(ref data) = stdin_mmap {
                    cut::process_cut_data(data, &cfg, &mut out)
                } else {
                    // Try splice mmap first (Linux only), then stdin_buf
                    #[cfg(target_os = "linux")]
                    if let Some(ref data) = splice_mmap {
                        cut::process_cut_data(data.as_ref(), &cfg, &mut out)
                    } else if let Some(ref data) = stdin_buf {
                        cut::process_cut_data(data, &cfg, &mut out)
                    } else {
                        let reader = BufReader::new(io::stdin().lock());
                        cut::process_cut_reader(reader, &cfg, &mut out)
                    }
                    #[cfg(not(target_os = "linux"))]
                    if let Some(ref data) = stdin_buf {
                        cut::process_cut_data(data, &cfg, &mut out)
                    } else {
                        let reader = BufReader::new(io::stdin().lock());
                        cut::process_cut_reader(reader, &cfg, &mut out)
                    }
                }
            }
            #[cfg(not(unix))]
            {
                if stdin_inplace_done {
                    if let Some(ref data) = stdin_buf {
                        out.write_all(data)
                    } else {
                        Ok(())
                    }
                } else if let Some(ref data) = stdin_buf {
                    cut::process_cut_data(data, &cfg, &mut out)
                } else {
                    let reader = BufReader::new(io::stdin().lock());
                    cut::process_cut_reader(reader, &cfg, &mut out)
                }
            }
        } else {
            match read_file_with_hints(Path::new(filename), MmapHints::Lazy) {
                Ok(data) => cut::process_cut_data(&data, &cfg, &mut out),
                Err(e) => {
                    eprintln!("cut: {}: {}", filename, io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        };

        if let Err(e) = result {
            if e.kind() == io::ErrorKind::BrokenPipe {
                process::exit(0);
            }
            eprintln!("cut: write error: {}", io_error_msg(&e));
            had_error = true;
        }
    }

    if let Err(e) = out.flush() {
        if e.kind() == io::ErrorKind::BrokenPipe {
            process::exit(0);
        }
        eprintln!("cut: write error: {}", io_error_msg(&e));
        had_error = true;
    }

    if had_error {
        process::exit(1);
    }
}

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

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("fcut");
        Command::new(path)
    }
    #[test]
    fn test_cut_fields() {
        let mut child = cmd()
            .args(["-d:", "-f1"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"a:b:c\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "a");
    }

    #[test]
    fn test_cut_bytes() {
        let mut child = cmd()
            .args(["-b1-3"])
            .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());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "hel");
    }

    #[test]
    fn test_cut_multiple_fields() {
        let mut child = cmd()
            .args(["-d:", "-f1,3"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"a:b:c:d\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "a:c");
    }

    #[test]
    fn test_cut_field_range() {
        let mut child = cmd()
            .args(["-d:", "-f2-4"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"a:b:c:d:e\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "b:c:d");
    }

    #[test]
    fn test_cut_complement() {
        let dir = tempfile::tempdir().unwrap();
        let infile = dir.path().join("in.txt");
        let outfile = dir.path().join("out.txt");
        std::fs::write(&infile, "a:b:c\n").unwrap();
        let output = cmd()
            .args(["-d:", "-f2", "--complement", infile.to_str().unwrap()])
            .stdout(std::fs::File::create(&outfile).unwrap())
            .output()
            .unwrap();
        assert!(output.status.success());
        assert_eq!(std::fs::read_to_string(&outfile).unwrap().trim(), "a:c");
    }

    #[test]
    fn test_cut_no_delimiter_in_line() {
        let mut child = cmd()
            .args(["-d:", "-f1"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"no delimiter here\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        // When line has no delimiter, whole line is printed (unless -s)
        assert_eq!(
            String::from_utf8_lossy(&output.stdout).trim(),
            "no delimiter here"
        );
    }

    #[test]
    fn test_cut_only_delimited() {
        let mut child = cmd()
            .args(["-d:", "-f1", "-s"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"no delimiter\nhas:delimiter\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // -s suppresses lines without delimiter
        assert_eq!(stdout.trim(), "has");
    }

    #[test]
    fn test_cut_characters() {
        let mut child = cmd()
            .args(["-c1-5"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"hello world\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "hello");
    }

    #[test]
    fn test_cut_empty_input() {
        let mut child = cmd()
            .args(["-f1"])
            .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());
        assert!(output.stdout.is_empty());
    }

    #[test]
    fn test_cut_output_delimiter() {
        let dir = tempfile::tempdir().unwrap();
        let infile = dir.path().join("in.txt");
        let outfile = dir.path().join("out.txt");
        std::fs::write(&infile, "a:b:c:d\n").unwrap();
        let output = cmd()
            .args([
                "-d:",
                "-f1,3",
                "--output-delimiter=|",
                infile.to_str().unwrap(),
            ])
            .stdout(std::fs::File::create(&outfile).unwrap())
            .output()
            .unwrap();
        assert!(output.status.success());
        assert_eq!(std::fs::read_to_string(&outfile).unwrap().trim(), "a|c");
    }

    #[test]
    fn test_cut_no_option() {
        let output = cmd().output().unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_cut_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("data.txt");
        let outfile = dir.path().join("out.txt");
        std::fs::write(&file, "a:b:c\nx:y:z\n").unwrap();
        let output = cmd()
            .args(["-d:", "-f2", file.to_str().unwrap()])
            .stdout(std::fs::File::create(&outfile).unwrap())
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = std::fs::read_to_string(&outfile).unwrap();
        let lines: Vec<&str> = stdout.lines().collect();
        assert_eq!(lines, vec!["b", "y"]);
    }

    #[test]
    fn test_cut_tab_delimiter() {
        let mut child = cmd()
            .args(["-f2"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"first\tsecond\tthird\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "second");
    }
}