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
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Configuration for the date command.
#[derive(Default)]
pub struct DateConfig {
    /// Display time described by STRING (-d).
    pub date_string: Option<String>,
    /// Read dates from a file, one per line (-f).
    pub date_file: Option<String>,
    /// ISO 8601 output format (-I).
    pub iso_format: Option<IsoFormat>,
    /// RFC 5322 / email format (-R).
    pub rfc_email: bool,
    /// RFC 3339 format.
    pub rfc_3339: Option<Rfc3339Format>,
    /// Show modification time of FILE (-r).
    pub reference_file: Option<String>,
    /// Set system time (-s). We only parse; actual setting requires root.
    pub set_string: Option<String>,
    /// Use UTC (-u).
    pub utc: bool,
    /// Custom format string (starts with +).
    pub format: Option<String>,
}

/// ISO 8601 format precision levels.
#[derive(Clone, Debug, PartialEq)]
pub enum IsoFormat {
    Date,
    Hours,
    Minutes,
    Seconds,
    Ns,
}

/// RFC 3339 format precision levels.
#[derive(Clone, Debug, PartialEq)]
pub enum Rfc3339Format {
    Date,
    Seconds,
    Ns,
}

/// Parse an ISO format precision string.
pub fn parse_iso_format(s: &str) -> Result<IsoFormat, String> {
    match s {
        "" | "date" => Ok(IsoFormat::Date),
        "hours" => Ok(IsoFormat::Hours),
        "minutes" => Ok(IsoFormat::Minutes),
        "seconds" => Ok(IsoFormat::Seconds),
        "ns" => Ok(IsoFormat::Ns),
        _ => Err(format!("invalid ISO 8601 format: '{}'", s)),
    }
}

/// Parse an RFC 3339 format precision string.
pub fn parse_rfc3339_format(s: &str) -> Result<Rfc3339Format, String> {
    match s {
        "date" => Ok(Rfc3339Format::Date),
        "seconds" => Ok(Rfc3339Format::Seconds),
        "ns" => Ok(Rfc3339Format::Ns),
        _ => Err(format!("invalid RFC 3339 format: '{}'", s)),
    }
}

/// Format a `SystemTime` using the given format string.
///
/// Uses libc `strftime` for most specifiers. Handles `%N` (nanoseconds) manually
/// since strftime does not support it.
pub fn format_date(time: &SystemTime, format: &str, utc: bool) -> String {
    let dur = time.duration_since(UNIX_EPOCH).unwrap_or_default();
    let secs = dur.as_secs() as i64;
    let nanos = dur.subsec_nanos();

    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    if utc {
        unsafe {
            libc::gmtime_r(&secs, &mut tm);
        }
    } else {
        unsafe {
            libc::localtime_r(&secs, &mut tm);
        }
    }

    // Process the format string, handling %N, %-X, %_X specially and passing
    // everything else through to strftime.
    let mut result = String::with_capacity(format.len() * 2);
    let chars: Vec<char> = format.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        if chars[i] == '%' && i + 1 < chars.len() {
            // Check for GNU format modifiers: %-X (no pad), %_X (space pad), %0X (zero pad)
            let modifier = if i + 2 < chars.len()
                && (chars[i + 1] == '-' || chars[i + 1] == '_' || chars[i + 1] == '0')
                && chars[i + 2].is_ascii_alphabetic()
            {
                let m = chars[i + 1];
                i += 1; // skip the modifier, will process specifier next
                Some(m)
            } else {
                None
            };

            match chars[i + 1] {
                's' => {
                    // Unix timestamp — output directly to avoid mktime timezone issues.
                    // strftime("%s") calls mktime() internally which treats the tm struct
                    // as local time, causing wrong results when tm was filled with gmtime_r().
                    result.push_str(&secs.to_string());
                    i += 2;
                }
                'N' => {
                    // Nanoseconds (9 digits, zero-padded)
                    result.push_str(&format!("{:09}", nanos));
                    i += 2;
                }
                'q' => {
                    // Quarter (1-4), not in standard strftime
                    let month = tm.tm_mon; // 0-11
                    let quarter = (month / 3) + 1;
                    result.push_str(&quarter.to_string());
                    i += 2;
                }
                'P' => {
                    // am/pm (lowercase), not always available in strftime
                    let ampm = if tm.tm_hour < 12 { "am" } else { "pm" };
                    result.push_str(ampm);
                    i += 2;
                }
                'Z' if utc => {
                    // Force "UTC" instead of platform-dependent "GMT"
                    result.push_str("UTC");
                    i += 2;
                }
                'n' => {
                    result.push('\n');
                    i += 2;
                }
                't' => {
                    result.push('\t');
                    i += 2;
                }
                _ => {
                    // Pass this specifier to strftime
                    let spec = format!("%{}", chars[i + 1]);
                    let formatted = strftime_single(&tm, &spec);
                    // Apply modifier if present
                    let formatted = if let Some(mod_char) = modifier {
                        apply_format_modifier(&formatted, mod_char)
                    } else {
                        formatted
                    };
                    result.push_str(&formatted);
                    i += 2;
                }
            }
        } else {
            result.push(chars[i]);
            i += 1;
        }
    }

    result
}

/// Call libc strftime for a single format specifier.
fn strftime_single(tm: &libc::tm, fmt: &str) -> String {
    let c_fmt = match std::ffi::CString::new(fmt) {
        Ok(c) => c,
        Err(_) => return String::new(),
    };
    let mut buf = vec![0u8; 128];
    let len = unsafe {
        libc::strftime(
            buf.as_mut_ptr() as *mut libc::c_char,
            buf.len(),
            c_fmt.as_ptr(),
            tm,
        )
    };
    if len == 0 && !fmt.is_empty() && fmt != "%%" {
        // strftime returns 0 on error or if the result is empty string
        // For %%, it legitimately returns "%"
        return String::new();
    }
    buf.truncate(len);
    String::from_utf8_lossy(&buf).into_owned()
}

/// Apply a GNU format modifier to a strftime result.
/// '-' removes leading zeros/spaces (no padding).
/// '_' replaces leading zeros with spaces.
/// '0' replaces leading spaces with zeros.
fn apply_format_modifier(formatted: &str, modifier: char) -> String {
    match modifier {
        '-' => {
            // Remove leading zeros and spaces (no padding)
            let trimmed = formatted.trim_start_matches(['0', ' ']);
            if trimmed.is_empty() {
                "0".to_string()
            } else {
                trimmed.to_string()
            }
        }
        '_' => {
            // Replace leading zeros with spaces
            let mut result = String::with_capacity(formatted.len());
            let mut leading = true;
            for ch in formatted.chars() {
                if leading && ch == '0' {
                    result.push(' ');
                } else {
                    leading = false;
                    result.push(ch);
                }
            }
            result
        }
        '0' => {
            // Replace leading spaces with zeros
            let mut result = String::with_capacity(formatted.len());
            let mut leading = true;
            for ch in formatted.chars() {
                if leading && ch == ' ' {
                    result.push('0');
                } else {
                    leading = false;
                    result.push(ch);
                }
            }
            result
        }
        _ => formatted.to_string(),
    }
}

/// Format a SystemTime in ISO 8601 format.
pub fn format_iso(time: &SystemTime, precision: &IsoFormat, utc: bool) -> String {
    match precision {
        IsoFormat::Date => format_date(time, "%Y-%m-%d", utc),
        IsoFormat::Hours => {
            let date_part = format_date(time, "%Y-%m-%dT%H", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{}{}", date_part, tz)
        }
        IsoFormat::Minutes => {
            let date_part = format_date(time, "%Y-%m-%dT%H:%M", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{}{}", date_part, tz)
        }
        IsoFormat::Seconds => {
            let date_part = format_date(time, "%Y-%m-%dT%H:%M:%S", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{}{}", date_part, tz)
        }
        IsoFormat::Ns => {
            let dur = time.duration_since(UNIX_EPOCH).unwrap_or_default();
            let nanos = dur.subsec_nanos();
            let date_part = format_date(time, "%Y-%m-%dT%H:%M:%S", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{},{:09}{}", date_part, nanos, tz)
        }
    }
}

/// Format a SystemTime in RFC 5322 (email) format.
pub fn format_rfc_email(time: &SystemTime, utc: bool) -> String {
    format_date(time, "%a, %d %b %Y %H:%M:%S %z", utc)
}

/// Format a SystemTime in RFC 3339 format.
pub fn format_rfc3339(time: &SystemTime, precision: &Rfc3339Format, utc: bool) -> String {
    match precision {
        Rfc3339Format::Date => format_date(time, "%Y-%m-%d", utc),
        Rfc3339Format::Seconds => {
            let date_part = format_date(time, "%Y-%m-%d %H:%M:%S", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{}{}", date_part, tz)
        }
        Rfc3339Format::Ns => {
            let dur = time.duration_since(UNIX_EPOCH).unwrap_or_default();
            let nanos = dur.subsec_nanos();
            let date_part = format_date(time, "%Y-%m-%d %H:%M:%S", utc);
            let tz = format_timezone_colon(time, utc);
            format!("{}.{:09}{}", date_part, nanos, tz)
        }
    }
}

/// Format a timezone offset with a colon (e.g., +05:30).
fn format_timezone_colon(time: &SystemTime, utc: bool) -> String {
    if utc {
        return "+00:00".to_string();
    }
    let raw = format_date(time, "%z", false);
    // raw is like "+0530" or "-0800"
    if raw.len() >= 5 {
        format!("{}:{}", &raw[..3], &raw[3..5])
    } else {
        raw
    }
}

/// Parse a date string into a SystemTime.
///
/// Supports:
/// - ISO format: "2024-01-15 10:30:00", "2024-01-15T10:30:00"
/// - Relative: "yesterday", "tomorrow", "now", "today"
/// - Relative offset: "1 day ago", "2 hours ago", "3 days", "+1 week"
/// - Epoch: "@SECONDS"
pub fn parse_date_string(s: &str, utc: bool) -> Result<SystemTime, String> {
    let s = s.trim();

    // Handle epoch format: @SECONDS
    if let Some(epoch_str) = s.strip_prefix('@') {
        let secs: i64 = epoch_str
            .trim()
            .parse()
            .map_err(|_| format!("invalid date '@{}'", epoch_str))?;
        if secs >= 0 {
            return Ok(UNIX_EPOCH + Duration::from_secs(secs as u64));
        } else {
            return Ok(UNIX_EPOCH - Duration::from_secs((-secs) as u64));
        }
    }

    let now = SystemTime::now();

    // Handle relative words
    match s.to_lowercase().as_str() {
        "now" | "today" => return Ok(now),
        "yesterday" => {
            return Ok(now - Duration::from_secs(86400));
        }
        "tomorrow" => {
            return Ok(now + Duration::from_secs(86400));
        }
        _ => {}
    }

    // Handle relative offsets: "N unit ago", "N unit", "+N unit"
    if let Some(result) = try_parse_relative(s, &now) {
        return Ok(result);
    }

    // Try time-only format: "HH:MM[ +OFFSET]"
    if let Some(result) = try_parse_time_only(s, utc) {
        return Ok(result);
    }

    // Try ISO-like format: "YYYY-MM-DD[ HH:MM[:SS]]"
    if let Some(result) = try_parse_iso(s, utc) {
        return Ok(result);
    }

    Err(format!("invalid date '{}'", s))
}

/// Try to parse a time-only string like "HH:MM", "HH:MM:SS", "HH:MM +OFFSET".
/// Interprets as today's date with the given time. Seconds default to 00.
fn try_parse_time_only(s: &str, utc: bool) -> Option<SystemTime> {
    let s = s.trim();
    let parts: Vec<&str> = s.split_whitespace().collect();
    if parts.is_empty() || parts.len() > 2 {
        return None;
    }

    let time_str = parts[0];
    let tz_str = if parts.len() == 2 {
        Some(parts[1])
    } else {
        None
    };

    // Validate time format: HH:MM or HH:MM:SS
    let time_fields: Vec<&str> = time_str.split(':').collect();
    if time_fields.len() < 2 || time_fields.len() > 3 {
        return None;
    }

    let hour: u32 = time_fields[0].parse().ok()?;
    let minute: u32 = time_fields[1].parse().ok()?;
    let second: u32 = if time_fields.len() == 3 {
        time_fields[2].parse().ok()?
    } else {
        0
    };

    if hour > 23 || minute > 59 || second > 60 {
        return None;
    }

    // Determine timezone offset in seconds east of UTC
    let mut use_utc = utc;
    let mut tz_offset_secs: i64 = 0;
    if let Some(tz) = tz_str {
        if tz.eq_ignore_ascii_case("UTC") || tz == "Z" {
            use_utc = true;
        } else if (tz.starts_with('+') || tz.starts_with('-')) && (tz.len() == 5 || tz.len() == 3) {
            let sign: i64 = if tz.starts_with('-') { -1 } else { 1 };
            let digits = &tz[1..];
            if !digits.chars().all(|c| c.is_ascii_digit()) {
                return None;
            }
            let (oh, om) = if digits.len() == 4 {
                let h: i64 = digits[..2].parse().ok()?;
                let m: i64 = digits[2..].parse().ok()?;
                (h, m)
            } else {
                let h: i64 = digits.parse().ok()?;
                (h, 0)
            };
            tz_offset_secs = sign * (oh * 3600 + om * 60);
            use_utc = true;
        } else {
            return None;
        }
    }

    // Get today's date
    let now = SystemTime::now();
    let now_secs = now.duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;

    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    if use_utc {
        let now_t = now_secs as libc::time_t;
        unsafe {
            libc::gmtime_r(&now_t, &mut tm);
        }
    } else {
        let now_t = now_secs as libc::time_t;
        unsafe {
            libc::localtime_r(&now_t, &mut tm);
        }
    }

    tm.tm_hour = hour as i32;
    tm.tm_min = minute as i32;
    tm.tm_sec = second as i32;
    tm.tm_isdst = -1;

    let epoch_secs = if use_utc {
        unsafe { libc::timegm(&mut tm) }
    } else {
        unsafe { libc::mktime(&mut tm) }
    };
    if epoch_secs == -1 {
        return None;
    }

    // Subtract timezone offset: input time is in the given tz, convert to UTC
    let final_secs = epoch_secs as i64 - tz_offset_secs;

    if final_secs >= 0 {
        Some(UNIX_EPOCH + Duration::from_secs(final_secs as u64))
    } else {
        Some(UNIX_EPOCH - Duration::from_secs((-final_secs) as u64))
    }
}

/// Try to parse a relative time expression.
fn try_parse_relative(s: &str, now: &SystemTime) -> Option<SystemTime> {
    let lower = s.to_lowercase();
    let parts: Vec<&str> = lower.split_whitespace().collect();

    if parts.len() < 2 {
        return None;
    }

    let is_ago = parts.last().map_or(false, |&p| p == "ago");
    let num_str = parts[0].trim_start_matches('+');
    let amount: i64 = num_str.parse().ok()?;

    let unit_idx = 1;
    if unit_idx >= parts.len() {
        return None;
    }
    let unit = parts[unit_idx];

    let seconds = match unit.trim_end_matches('s') {
        "second" => amount,
        "minute" => amount * 60,
        "hour" => amount * 3600,
        "day" => amount * 86400,
        "week" => amount * 86400 * 7,
        "month" => amount * 86400 * 30,
        "year" => amount * 86400 * 365,
        _ => return None,
    };

    let duration = Duration::from_secs(seconds.unsigned_abs());
    if is_ago || seconds < 0 {
        Some(*now - duration)
    } else {
        Some(*now + duration)
    }
}

/// Try to parse an ISO-like date string.
fn try_parse_iso(s: &str, utc: bool) -> Option<SystemTime> {
    // Split on space or T
    let s = s.replace('T', " ");
    let parts: Vec<&str> = s.splitn(2, ' ').collect();
    let date_part = parts[0];
    let time_part = if parts.len() > 1 {
        parts[1]
    } else {
        "00:00:00"
    };

    let date_fields: Vec<&str> = date_part.split('-').collect();
    if date_fields.len() != 3 {
        return None;
    }

    let year: i32 = date_fields[0].parse().ok()?;
    let month: u32 = date_fields[1].parse().ok()?;
    let day: u32 = date_fields[2].parse().ok()?;

    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return None;
    }

    // Parse time (strip timezone info for simplicity)
    let time_clean = time_part
        .split('+')
        .next()
        .unwrap_or(time_part)
        .split('Z')
        .next()
        .unwrap_or(time_part);
    let time_fields: Vec<&str> = time_clean.split(':').collect();
    let hour: u32 = time_fields
        .first()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    let minute: u32 = time_fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
    let second: u32 = time_fields
        .get(2)
        .and_then(|s| s.split('.').next())
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);

    if hour > 23 || minute > 59 || second > 60 {
        return None;
    }

    // Convert to Unix timestamp using libc mktime
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    tm.tm_year = year - 1900;
    tm.tm_mon = month as i32 - 1;
    tm.tm_mday = day as i32;
    tm.tm_hour = hour as i32;
    tm.tm_min = minute as i32;
    tm.tm_sec = second as i32;
    tm.tm_isdst = -1; // Let mktime determine DST

    let epoch_secs = if utc {
        unsafe { libc::timegm(&mut tm) }
    } else {
        unsafe { libc::mktime(&mut tm) }
    };
    if epoch_secs == -1 {
        return None;
    }

    if epoch_secs >= 0 {
        Some(UNIX_EPOCH + Duration::from_secs(epoch_secs as u64))
    } else {
        Some(UNIX_EPOCH - Duration::from_secs((-epoch_secs) as u64))
    }
}

/// Get the modification time of a file.
pub fn file_mod_time(path: &str) -> Result<SystemTime, String> {
    std::fs::metadata(path)
        .map_err(|e| format!("{}: {}", path, e))?
        .modified()
        .map_err(|e| format!("{}: {}", path, e))
}

/// Get the default date format (matches GNU date default output).
/// Uses %H:%M:%S (24-hour clock) to match GNU behavior.
pub fn default_format() -> &'static str {
    "%a %b %e %H:%M:%S %Z %Y"
}