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
use std::io::{self, BufWriter, 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_with_hints;
use coreutils_rs::common::io::{FileData, MmapHints, read_file_with_hints, read_stdin};
use coreutils_rs::common::{enlarge_stdout_pipe, io_error_msg};
use coreutils_rs::tac;

struct Cli {
    before: bool,
    regex: bool,
    separator: Option<String>,
    files: Vec<String>,
}

/// Hand-rolled argument parser — eliminates clap's ~100-200µs initialization.
/// tac has very few options: -b, -r, -s STRING, --help, --version, and files.
fn parse_args() -> Cli {
    let mut cli = Cli {
        before: false,
        regex: false,
        separator: None,
        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"--" {
            for a in args {
                cli.files.push(a.to_string_lossy().into_owned());
            }
            break;
        }
        if bytes.starts_with(b"--") {
            if bytes.starts_with(b"--separator=") {
                let val = arg.to_string_lossy();
                cli.separator = Some(val[12..].to_string());
                continue;
            }
            match bytes {
                b"--before" => cli.before = true,
                b"--regex" => cli.regex = true,
                b"--separator" => {
                    cli.separator = Some(
                        args.next()
                            .unwrap_or_else(|| {
                                eprintln!("tac: option '--separator' requires an argument");
                                process::exit(1);
                            })
                            .to_string_lossy()
                            .into_owned(),
                    );
                }
                b"--help" => {
                    print!(
                        "Usage: tac [OPTION]... [FILE]...\n\
                         Write each FILE to standard output, last line first.\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, --before             attach the separator before instead of after\n\
                         \x20 -r, --regex              interpret the separator as a regular expression\n\
                         \x20 -s, --separator=STRING    use STRING as the separator instead of newline\n\
                         \x20     --help               display this help and exit\n\
                         \x20     --version            output version information and exit\n"
                    );
                    process::exit(0);
                }
                b"--version" => {
                    println!("tac (fcoreutils) {}", env!("CARGO_PKG_VERSION"));
                    process::exit(0);
                }
                _ => {
                    eprintln!("tac: unrecognized option '{}'", arg.to_string_lossy());
                    eprintln!("Try 'tac --help' for more information.");
                    process::exit(1);
                }
            }
        } else if bytes.len() > 1 && bytes[0] == b'-' {
            let mut i = 1;
            while i < bytes.len() {
                match bytes[i] {
                    b'b' => cli.before = true,
                    b'r' => cli.regex = true,
                    b's' => {
                        // -s takes a value: rest of this arg or next arg
                        if i + 1 < bytes.len() {
                            let val = arg.to_string_lossy();
                            cli.separator = Some(val[i + 1..].to_string());
                        } else {
                            cli.separator = Some(
                                args.next()
                                    .unwrap_or_else(|| {
                                        eprintln!("tac: option requires an argument -- 's'");
                                        process::exit(1);
                                    })
                                    .to_string_lossy()
                                    .into_owned(),
                            );
                        }
                        break; // consumed rest of arg
                    }
                    _ => {
                        eprintln!("tac: invalid option -- '{}'", bytes[i] as char);
                        eprintln!("Try 'tac --help' for more information.");
                        process::exit(1);
                    }
                }
                i += 1;
            }
        } else {
            cli.files.push(arg.to_string_lossy().into_owned());
        }
    }

    cli
}

fn run(cli: &Cli, files: &[String], out: &mut impl Write) -> bool {
    let mut had_error = false;

    for filename in files {
        let data: FileData = if filename == "-" {
            #[cfg(unix)]
            {
                match try_mmap_stdin_with_hints(2 * 1024 * 1024, false) {
                    Some(mmap) => FileData::Mmap(mmap),
                    None => {
                        #[cfg(target_os = "linux")]
                        {
                            match coreutils_rs::common::io::splice_stdin_to_mmap() {
                                Ok(Some(mmap)) => FileData::Owned(mmap.to_vec()),
                                _ => match read_stdin() {
                                    Ok(d) => FileData::Owned(d),
                                    Err(e) => {
                                        eprintln!("tac: standard input: {}", io_error_msg(&e));
                                        had_error = true;
                                        continue;
                                    }
                                },
                            }
                        }
                        #[cfg(not(target_os = "linux"))]
                        match read_stdin() {
                            Ok(d) => FileData::Owned(d),
                            Err(e) => {
                                eprintln!("tac: standard input: {}", io_error_msg(&e));
                                had_error = true;
                                continue;
                            }
                        }
                    }
                }
            }
            #[cfg(not(unix))]
            match read_stdin() {
                Ok(d) => FileData::Owned(d),
                Err(e) => {
                    eprintln!("tac: standard input: {}", io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        } else {
            // Use read_file which auto-selects read() for <1MB and mmap for larger.
            // read() avoids mmap setup/teardown overhead (page table creation, TLB flush)
            // that dominates for small files. For large files, mmap enables zero-copy writev.
            match read_file_with_hints(Path::new(filename), MmapHints::Lazy) {
                Ok(d) => d,
                Err(e) => {
                    eprintln!("tac: {}: {}", filename, io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        };

        let result = if cli.regex {
            let bytes: &[u8] = &data;
            let sep = cli.separator.as_deref().unwrap_or("\n");
            tac::tac_regex_separator(bytes, sep, cli.before, out)
        } else if let Some(ref sep) = cli.separator {
            let bytes: &[u8] = &data;
            if sep.is_empty() {
                // GNU tac: -s '' means NUL byte separator
                tac::tac_bytes(bytes, b'\0', cli.before, out)
            } else if sep.len() == 1 {
                // Single-byte custom separator: use fd-based streaming
                #[cfg(unix)]
                {
                    let _ = out.flush();
                    tac::tac_bytes_to_fd(bytes, sep.as_bytes()[0], cli.before, 1)
                }
                #[cfg(not(unix))]
                tac::tac_string_separator(bytes, sep.as_bytes(), cli.before, out)
            } else {
                tac::tac_string_separator(bytes, sep.as_bytes(), cli.before, out)
            }
        } else {
            // Default newline separator: use fd-based streaming to bypass BufWriter
            let bytes: &[u8] = &data;
            #[cfg(unix)]
            {
                let _ = out.flush();
                tac::tac_bytes_to_fd(bytes, b'\n', cli.before, 1)
            }
            #[cfg(not(unix))]
            tac::tac_bytes(bytes, b'\n', cli.before, out)
        };

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

    had_error
}

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

    enlarge_stdout_pipe();

    let mut cli = parse_args();

    let files: Vec<String> = if cli.files.is_empty() {
        vec!["-".to_string()]
    } else {
        std::mem::take(&mut cli.files)
    };

    // Use 1MB BufWriter. The tac core functions now stream 1MB chunks internally,
    // so a smaller BufWriter suffices and avoids massive page fault overhead from
    // allocating a 16MB buffer.
    #[cfg(unix)]
    let had_error = {
        let raw = unsafe { ManuallyDrop::new(std::fs::File::from_raw_fd(1)) };
        let mut writer = BufWriter::with_capacity(1024 * 1024, &*raw);
        let err = run(&cli, &files, &mut writer);
        let _ = writer.flush();
        err
    };
    #[cfg(not(unix))]
    let had_error = {
        let stdout = io::stdout();
        let lock = stdout.lock();
        let mut writer = BufWriter::with_capacity(1024 * 1024, lock);
        let err = run(&cli, &files, &mut writer);
        let _ = writer.flush();
        err
    };

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

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

    fn cmd() -> Command {
        let mut path = std::env::current_exe().unwrap();
        path.pop();
        path.pop();
        path.push("ftac");
        Command::new(path)
    }
    #[test]
    fn test_tac_basic() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"a\nb\nc\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout), "c\nb\na\n");
    }

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

    #[test]
    fn test_tac_single_line() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"hello\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout), "hello\n");
    }

    #[test]
    fn test_tac_no_trailing_newline() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"a\nb").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // Should still reverse: "b" then "a\n"
        assert!(stdout.contains("b") && stdout.contains("a"));
    }

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

    #[test]
    fn test_tac_multiple_files() {
        let dir = tempfile::tempdir().unwrap();
        let f1 = dir.path().join("a.txt");
        let f2 = dir.path().join("b.txt");
        std::fs::write(&f1, "1\n2\n").unwrap();
        std::fs::write(&f2, "3\n4\n").unwrap();
        let output = cmd()
            .args([f1.to_str().unwrap(), f2.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
    }

    #[test]
    fn test_tac_nonexistent_file() {
        let output = cmd().arg("/nonexistent_xyz_tac").output().unwrap();
        assert!(!output.status.success());
    }

    #[test]
    fn test_tac_custom_separator() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .args(["-s", ":"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"a:b:c:").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // With separator ":", reversed
        assert!(stdout.contains("c"));
    }

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

    #[test]
    fn test_tac_many_lines() {
        use std::io::Write;
        use std::process::Stdio;
        let input: String = (1..=100).map(|i| format!("{}\n", i)).collect();
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(input.as_bytes())
            .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[0], "100");
        assert_eq!(lines[99], "1");
    }
}