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
// fnumfmt -- convert numbers to/from human-readable form
//
// Usage: numfmt [OPTION]... [NUMBER]...
//
// Converts numbers from/to human-readable strings.
// Numbers can be given on the command line or read from standard input.

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

use coreutils_rs::numfmt::{self, InvalidMode, NumfmtConfig};

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

fn print_help() {
    println!("Usage: {} [OPTION]... [NUMBER]...", TOOL_NAME);
    println!("Reformat NUMBER(s), or the numbers from standard input if none are specified.");
    println!();
    println!("Mandatory arguments to long options are mandatory for short options too.");
    println!("  -d, --delimiter=X    use X instead of whitespace for field delimiter");
    println!("      --field=FIELDS   replace the numbers in these input fields (default=1);");
    println!("                         see FIELDS below");
    println!("      --format=FORMAT  use printf style floating-point FORMAT;");
    println!("                         see FORMAT below for details");
    println!("      --from=UNIT      auto-scale input numbers to UNITs; default is 'none';");
    println!("                         see UNIT below");
    println!("      --from-unit=N    specify the input unit size (instead of the default 1)");
    println!("      --grouping       use locale-defined grouping of digits, e.g. 1,000,000");
    println!("                         (which means it has no effect in the C/POSIX locale)");
    println!("      --header[=N]     print (without converting) the first N header lines;");
    println!("                         N defaults to 1 if not specified");
    println!("      --invalid=MODE   failure mode for invalid numbers: MODE can be:");
    println!("                         abort (default), fail, warn, ignore");
    println!("      --padding=N      pad the output to N characters; positive N will");
    println!("                         right-align; negative N will left-align;");
    println!("                         padding is ignored if the output is wider than N");
    println!("      --round=METHOD   use METHOD for rounding when scaling; METHOD can be:");
    println!("                         up, down, from-zero, towards-zero, nearest (default)");
    println!("      --suffix=SUFFIX  add SUFFIX to output numbers, and accept optional");
    println!("                         SUFFIX in input numbers");
    println!("      --to=UNIT        auto-scale output numbers to UNITs; see UNIT below");
    println!("      --to-unit=N      the output unit size (instead of the default 1)");
    println!("  -z, --zero-terminated  line delimiter is NUL, not newline");
    println!("      --help     display this help and exit");
    println!("      --version  output version information and exit");
    println!();
    println!("UNIT options:");
    println!("  none       no auto-scaling is done; suffixes will trigger an error");
    println!("  auto       accept optional single/two letter suffix:");
    println!("               1K = 1000, 1Ki = 1024, 1M = 1000000, 1Mi = 1048576, ...");
    println!("  si         accept optional single letter suffix:");
    println!("               1K = 1000, 1M = 1000000, ...");
    println!("  iec        accept optional single letter suffix:");
    println!("               1K = 1024, 1M = 1048576, ...");
    println!("  iec-i      accept optional two-letter suffix:");
    println!("               1Ki = 1024, 1Mi = 1048576, ...");
}

fn print_version() {
    println!("{} (fcoreutils) {}", TOOL_NAME, VERSION);
}

fn parse_args() -> (NumfmtConfig, Vec<String>) {
    let mut config = NumfmtConfig::default();
    let mut positional: Vec<String> = Vec::new();

    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--help" => {
                print_help();
                process::exit(0);
            }
            "--version" => {
                print_version();
                process::exit(0);
            }
            "--" => {
                // Remaining args are positional.
                for a in args.by_ref() {
                    positional.push(a);
                }
                break;
            }
            "-z" | "--zero-terminated" => {
                config.zero_terminated = true;
            }
            "--grouping" => {
                config.grouping = true;
            }
            _ => {
                if let Some(val) = arg.strip_prefix("--from=") {
                    match numfmt::parse_scale_unit(val) {
                        Ok(u) => config.from = u,
                        Err(e) => {
                            eprintln!("{}: {}", TOOL_NAME, e);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--to=") {
                    match numfmt::parse_scale_unit(val) {
                        Ok(u) => config.to = u,
                        Err(e) => {
                            eprintln!("{}: {}", TOOL_NAME, e);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--from-unit=") {
                    match val.parse::<f64>() {
                        Ok(n) if n > 0.0 => config.from_unit = n,
                        _ => {
                            eprintln!("{}: invalid unit size: '{}'", TOOL_NAME, val);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--to-unit=") {
                    match val.parse::<f64>() {
                        Ok(n) if n > 0.0 => config.to_unit = n,
                        _ => {
                            eprintln!("{}: invalid unit size: '{}'", TOOL_NAME, val);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--padding=") {
                    match val.parse::<i32>() {
                        Ok(n) if n != 0 => config.padding = Some(n),
                        _ => {
                            eprintln!("{}: invalid padding value: '{}'", TOOL_NAME, val);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--round=") {
                    match numfmt::parse_round_method(val) {
                        Ok(m) => config.round = m,
                        Err(e) => {
                            eprintln!("{}: {}", TOOL_NAME, e);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--suffix=") {
                    config.suffix = Some(val.to_string());
                } else if let Some(val) = arg.strip_prefix("--format=") {
                    config.format = Some(val.to_string());
                } else if let Some(val) = arg.strip_prefix("--field=") {
                    match numfmt::parse_fields(val) {
                        Ok(f) => config.field = f,
                        Err(e) => {
                            eprintln!("{}: {}", TOOL_NAME, e);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--invalid=") {
                    match numfmt::parse_invalid_mode(val) {
                        Ok(m) => config.invalid = m,
                        Err(e) => {
                            eprintln!("{}: {}", TOOL_NAME, e);
                            process::exit(1);
                        }
                    }
                } else if arg == "--header" {
                    config.header = 1;
                } else if let Some(val) = arg.strip_prefix("--header=") {
                    match val.parse::<usize>() {
                        Ok(n) => config.header = n,
                        Err(_) => {
                            eprintln!("{}: invalid header value: '{}'", TOOL_NAME, val);
                            process::exit(1);
                        }
                    }
                } else if arg == "-d" || arg == "--delimiter" {
                    match args.next() {
                        Some(val) => {
                            if val.len() != 1 {
                                eprintln!(
                                    "{}: the delimiter must be a single character",
                                    TOOL_NAME
                                );
                                process::exit(1);
                            }
                            config.delimiter = val.chars().next();
                        }
                        None => {
                            eprintln!("{}: option requires an argument -- 'd'", TOOL_NAME);
                            process::exit(1);
                        }
                    }
                } else if let Some(val) = arg.strip_prefix("--delimiter=") {
                    if val.len() != 1 {
                        eprintln!("{}: the delimiter must be a single character", TOOL_NAME);
                        process::exit(1);
                    }
                    config.delimiter = val.chars().next();
                } else if let Some(val) = arg.strip_prefix("-d") {
                    if val.len() != 1 {
                        eprintln!("{}: the delimiter must be a single character", TOOL_NAME);
                        process::exit(1);
                    }
                    config.delimiter = val.chars().next();
                } else if arg.starts_with('-') && arg.len() > 1 {
                    // Could be a negative number.
                    if arg
                        .chars()
                        .nth(1)
                        .is_some_and(|c| c.is_ascii_digit() || c == '.')
                    {
                        positional.push(arg);
                    } else {
                        eprintln!("{}: unrecognized option '{}'", TOOL_NAME, arg);
                        eprintln!("Try '{} --help' for more information.", TOOL_NAME);
                        process::exit(1);
                    }
                } else {
                    positional.push(arg);
                }
            }
        }
    }

    (config, positional)
}

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

    let (config, positional) = parse_args();

    if positional.is_empty() {
        // Read from stdin.
        let stdin = io::stdin();
        let reader = stdin.lock();
        let stdout = io::stdout();
        let writer = BufWriter::with_capacity(256 * 1024, stdout.lock());

        match numfmt::run_numfmt(reader, writer, &config) {
            Ok(()) => {}
            Err(_) => process::exit(2),
        }
    } else {
        // Process command-line arguments as numbers.
        let stdout = io::stdout();
        let mut writer = BufWriter::with_capacity(8 * 1024, stdout.lock());
        let terminator = if config.zero_terminated { '\0' } else { '\n' };
        let mut had_error = false;

        for number in &positional {
            match numfmt::process_line(number, &config) {
                Ok(result) => {
                    let _ = write!(writer, "{}{}", result, terminator);
                }
                Err(e) => match config.invalid {
                    InvalidMode::Abort => {
                        eprintln!("{}: {}", TOOL_NAME, e);
                        process::exit(2);
                    }
                    InvalidMode::Fail => {
                        eprintln!("{}: {}", TOOL_NAME, e);
                        let _ = write!(writer, "{}{}", number, terminator);
                        had_error = true;
                    }
                    InvalidMode::Warn => {
                        eprintln!("{}: {}", TOOL_NAME, e);
                        let _ = write!(writer, "{}{}", number, terminator);
                    }
                    InvalidMode::Ignore => {
                        let _ = write!(writer, "{}{}", number, terminator);
                    }
                },
            }
        }

        let _ = writer.flush();
        if had_error {
            process::exit(2);
        }
    }
}

#[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("fnumfmt");
        Command::new(path)
    }
    #[test]
    fn test_numfmt_from_si() {
        let mut child = cmd()
            .arg("--from=si")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"1K\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "1000");
    }

    #[test]
    fn test_numfmt_to_si() {
        let mut child = cmd()
            .arg("--to=si")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"1000\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "1.0K");
    }

    #[test]
    fn test_numfmt_from_iec() {
        let mut child = cmd()
            .arg("--from=iec")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"1K\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "1024");
    }

    #[test]
    fn test_numfmt_to_iec() {
        let mut child = cmd()
            .arg("--to=iec")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"1048576\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.trim() == "1.0M" || stdout.trim() == "1M");
    }

    #[test]
    fn test_numfmt_padding() {
        let mut child = cmd()
            .args(["--to=si", "--padding=10"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(b"1000\n").unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.len() >= 10);
    }

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

    #[test]
    fn test_numfmt_arg_mode() {
        let output = cmd().args(["--to=si", "1000"]).output().unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "1.0K");
    }

    #[test]
    fn test_numfmt_multiple_args() {
        let output = cmd()
            .args(["--to=si", "1000", "2000", "3000"])
            .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(), 3);
    }

    #[test]
    fn test_numfmt_large_number() {
        let output = cmd().args(["--to=iec", "1073741824"]).output().unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("G"));
    }

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

    #[test]
    fn test_numfmt_empty_input() {
        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());
    }
}