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
use std::io::{self, Write};
use std::path::Path;
use std::process;

use coreutils_rs::common::io::{FileData, read_file, read_stdin};
use coreutils_rs::common::{enlarge_stdout_pipe, io_error_msg};
use coreutils_rs::fold;

/// Minimal writer that batches writes via raw libc::write to fd 1.
/// Eliminates BufWriter overhead (double-buffering) since fold's core
/// already buffers into ~1MB chunks internally.
#[cfg(unix)]
struct RawStdout;

#[cfg(unix)]
impl Write for RawStdout {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let ret = unsafe { libc::write(1, buf.as_ptr() as *const libc::c_void, buf.len() as _) };
        if ret >= 0 {
            Ok(ret as usize)
        } else {
            Err(io::Error::last_os_error())
        }
    }

    fn write_all(&mut self, mut buf: &[u8]) -> io::Result<()> {
        while !buf.is_empty() {
            let ret =
                unsafe { libc::write(1, buf.as_ptr() as *const libc::c_void, buf.len() as _) };
            if ret > 0 {
                buf = &buf[ret as usize..];
            } else if ret == 0 {
                return Err(io::Error::new(io::ErrorKind::WriteZero, "write returned 0"));
            } else {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::Interrupted {
                    continue;
                }
                return Err(err);
            }
        }
        Ok(())
    }

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

struct Cli {
    bytes: bool,
    spaces: bool,
    width: usize,
    files: Vec<String>,
}

fn parse_args() -> Cli {
    let mut cli = Cli {
        bytes: false,
        spaces: false,
        width: 80,
        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"--width=") {
                let val = arg.to_string_lossy();
                match val[8..].parse::<usize>() {
                    Ok(w) => cli.width = w,
                    Err(_) => {
                        eprintln!("fold: invalid number of columns: '{}'", &val[8..]);
                        process::exit(1);
                    }
                }
                continue;
            }
            match bytes {
                b"--bytes" => cli.bytes = true,
                b"--spaces" => cli.spaces = true,
                b"--width" => {
                    let val = args
                        .next()
                        .unwrap_or_else(|| {
                            eprintln!("fold: option '--width' requires an argument");
                            process::exit(1);
                        })
                        .to_string_lossy()
                        .into_owned();
                    match val.parse::<usize>() {
                        Ok(w) => cli.width = w,
                        Err(_) => {
                            eprintln!("fold: invalid number of columns: '{}'", val);
                            process::exit(1);
                        }
                    }
                }
                b"--help" => {
                    print!(
                        "Usage: fold [OPTION]... [FILE]...\n\
                         Wrap input lines in each FILE, writing 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         count bytes rather than columns\n\
                         \x20 -s, --spaces        break at spaces\n\
                         \x20 -w, --width=WIDTH   use WIDTH columns instead of 80\n\
                         \x20     --help          display this help and exit\n\
                         \x20     --version       output version information and exit\n"
                    );
                    process::exit(0);
                }
                b"--version" => {
                    println!("fold (fcoreutils) {}", env!("CARGO_PKG_VERSION"));
                    process::exit(0);
                }
                _ => {
                    eprintln!("fold: unrecognized option '{}'", arg.to_string_lossy());
                    eprintln!("Try 'fold --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.bytes = true,
                    b's' => cli.spaces = true,
                    b'w' => {
                        // -w takes a value
                        if i + 1 < bytes.len() {
                            let val = arg.to_string_lossy();
                            match val[i + 1..].parse::<usize>() {
                                Ok(w) => cli.width = w,
                                Err(_) => {
                                    eprintln!(
                                        "fold: invalid number of columns: '{}'",
                                        &val[i + 1..]
                                    );
                                    process::exit(1);
                                }
                            }
                        } else {
                            let val = args
                                .next()
                                .unwrap_or_else(|| {
                                    eprintln!("fold: option requires an argument -- 'w'");
                                    process::exit(1);
                                })
                                .to_string_lossy()
                                .into_owned();
                            match val.parse::<usize>() {
                                Ok(w) => cli.width = w,
                                Err(_) => {
                                    eprintln!("fold: invalid number of columns: '{}'", val);
                                    process::exit(1);
                                }
                            }
                        }
                        break;
                    }
                    _ => {
                        eprintln!("fold: invalid option -- '{}'", bytes[i] as char);
                        eprintln!("Try 'fold --help' for more information.");
                        process::exit(1);
                    }
                }
                i += 1;
            }
        } else {
            cli.files.push(arg.to_string_lossy().into_owned());
        }
    }

    cli
}

/// Apply madvise hints on mmapped file data for optimal sequential read.
/// Called after read_file() to reinforce sequential + hugepage hints.
#[cfg(target_os = "linux")]
fn apply_madvise(data: &FileData) {
    // Only apply to mmap'd data (not owned Vec)
    if let FileData::Mmap(_mmap) = data {
        let ptr = data.as_ptr() as *mut libc::c_void;
        let len = data.len();
        if len >= 4 * 1024 * 1024 {
            unsafe {
                libc::madvise(ptr, len, libc::MADV_SEQUENTIAL);
            }
        }
        if len >= 2 * 1024 * 1024 {
            unsafe {
                libc::madvise(ptr, len, libc::MADV_HUGEPAGE);
            }
        }
    }
}

/// Write all bytes directly to a file descriptor, bypassing BufWriter.
#[cfg(unix)]
fn write_all_fd(fd: i32, data: &[u8]) -> io::Result<()> {
    let mut pos = 0;
    while pos < data.len() {
        let n = unsafe {
            libc::write(
                fd,
                data[pos..].as_ptr() as *const libc::c_void,
                (data.len() - pos) as _,
            )
        };
        if n < 0 {
            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            return Err(err);
        }
        pos += n as usize;
    }
    Ok(())
}

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

    enlarge_stdout_pipe();

    let cli = parse_args();

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

    let mut had_error = false;

    // fold_bytes already buffers into ~1MB chunks internally, so we use
    // a direct raw-fd writer to avoid double-buffering through BufWriter.
    #[cfg(unix)]
    let mut out = RawStdout;
    #[cfg(not(unix))]
    let stdout = io::stdout();
    #[cfg(not(unix))]
    let mut out = io::BufWriter::with_capacity(1024 * 1024, stdout.lock());

    for filename in &files {
        let data = if filename == "-" {
            match read_stdin() {
                Ok(d) => FileData::Owned(d),
                Err(e) => {
                    eprintln!("fold: standard input: {}", io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        } else {
            match read_file(Path::new(filename)) {
                Ok(d) => d,
                Err(e) => {
                    eprintln!("fold: {}: {}", filename, io_error_msg(&e));
                    had_error = true;
                    continue;
                }
            }
        };

        #[cfg(target_os = "linux")]
        apply_madvise(&data);

        // Fast path: if output == input (all lines fit within width), bypass processing
        #[cfg(unix)]
        if fold::fold_is_passthrough(&data, cli.width, cli.bytes) {
            let _ = out.flush();
            if let Err(e) = write_all_fd(1, &data) {
                if e.kind() == io::ErrorKind::BrokenPipe {
                    process::exit(0);
                }
                eprintln!("fold: write error: {}", io_error_msg(&e));
                had_error = true;
            }
            continue;
        }

        if let Err(e) = fold::fold_bytes(&data, cli.width, cli.bytes, cli.spaces, &mut out) {
            if e.kind() == io::ErrorKind::BrokenPipe {
                process::exit(0);
            }
            eprintln!("fold: write error: {}", io_error_msg(&e));
            had_error = true;
        }
    }

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

    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("ffold");
        Command::new(path)
    }
    #[test]
    fn test_fold_default_width() {
        use std::io::Write;
        use std::process::Stdio;
        // Default fold width is 80
        let line = "x".repeat(100);
        let mut child = cmd()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(format!("{}\n", line).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.len(), 2);
        assert_eq!(lines[0].len(), 80);
        assert_eq!(lines[1].len(), 20);
    }

    #[test]
    fn test_fold_custom_width() {
        use std::io::Write;
        use std::process::Stdio;
        let line = "abcdefghij";
        let mut child = cmd()
            .args(["-w", "5"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(format!("{}\n", line).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, vec!["abcde", "fghij"]);
    }

    #[test]
    fn test_fold_short_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"short\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(output.stdout, b"short\n");
    }

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

    #[test]
    fn test_fold_bytes_mode() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .args(["-b", "-w", "3"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"abcdef\n").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], "abc");
        assert_eq!(lines[1], "def");
    }

    #[test]
    fn test_fold_spaces() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .args(["-s", "-w", "10"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"hello world foo bar\n")
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        // With -s, fold should break at spaces
        for line in stdout.lines() {
            assert!(line.len() <= 10, "line too long: {}", line);
        }
    }

    #[test]
    fn test_fold_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "a".repeat(200) + "\n").unwrap();
        let output = cmd()
            .args(["-w", "50", file.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.lines().count(), 4);
    }

    #[test]
    fn test_fold_multiple_lines() {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = cmd()
            .args(["-w", "5"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"abcdefgh\n12345678\n")
            .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(), 4);
    }

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