wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Date parsing shared by the CLI commands.

use jiff::{civil, tz::TimeZone, Timestamp, Zoned};

/// Parses a date/time in `tz`, accepting the same inputs as the original:
///
/// - Unix timestamps (bare integers, seconds since the epoch)
/// - `2006-01-02`
/// - `2006-01-02T15:04:05` and `2006-01-02 15:04:05`
/// - RFC 3339, with or without fractional seconds (`2006-01-02T15:04:05Z07:00`)
///
/// Inputs carrying their own offset denote an absolute instant and are
/// re-expressed in `tz`; inputs without one are interpreted as local wall time.
pub fn parse(s: &str, tz: &TimeZone) -> Result<Zoned, DateError> {
    let s = s.trim();
    if s.is_empty() {
        return Err(DateError(String::new()));
    }

    // Unix timestamp fast path: bare integers are by far the common batch input.
    if let Some(ts) = parse_i64(s) {
        return Timestamp::from_second(ts)
            .map(|t| t.to_zoned(tz.clone()))
            .map_err(|_| DateError(s.to_string()));
    }

    parse_format(s, tz).ok_or_else(|| DateError(s.to_string()))
}

/// Selects the format from the input's length and separator character rather
/// than trying each one in turn, so the common cases parse on the first try.
fn parse_format(s: &str, tz: &TimeZone) -> Option<Zoned> {
    let b = s.as_bytes();

    // "2006-01-02"
    if b.len() == 10 {
        return s
            .parse::<civil::Date>()
            .ok()
            .and_then(|d| d.to_zoned(tz.clone()).ok());
    }

    if b.len() > 10 {
        match b[10] {
            b'T' => {
                // Offset-bearing forms denote an absolute instant.
                if ends_with_offset(b) {
                    if let Ok(ts) = s.parse::<Timestamp>() {
                        return Some(ts.to_zoned(tz.clone()));
                    }
                }
                if let Ok(dt) = s.parse::<civil::DateTime>() {
                    return dt.to_zoned(tz.clone()).ok();
                }
            }
            b' ' => {
                // "2006-01-02 15:04:05" — jiff wants the ISO 'T' separator.
                let mut swapped = String::with_capacity(s.len());
                swapped.push_str(&s[..10]);
                swapped.push('T');
                swapped.push_str(&s[11..]);
                if let Ok(dt) = swapped.parse::<civil::DateTime>() {
                    return dt.to_zoned(tz.clone()).ok();
                }
                if ends_with_offset(swapped.as_bytes()) {
                    if let Ok(ts) = swapped.parse::<Timestamp>() {
                        return Some(ts.to_zoned(tz.clone()));
                    }
                }
            }
            _ => {}
        }
    }

    // Fallback for inputs that dodged the discriminator.
    if let Ok(ts) = s.parse::<Timestamp>() {
        return Some(ts.to_zoned(tz.clone()));
    }
    if let Ok(dt) = s.parse::<civil::DateTime>() {
        return dt.to_zoned(tz.clone()).ok();
    }
    if let Ok(d) = s.parse::<civil::Date>() {
        return d.to_zoned(tz.clone()).ok();
    }
    None
}

/// Reports whether the input ends in a `Z` or a `±HH:MM` offset.
fn ends_with_offset(b: &[u8]) -> bool {
    match b.last() {
        Some(b'Z' | b'z') => true,
        _ => b.len() >= 6 && matches!(b[b.len() - 6], b'+' | b'-') && b[b.len() - 3] == b':',
    }
}

/// Parses a decimal integer without allocating.
pub fn parse_i64(s: &str) -> Option<i64> {
    let b = s.as_bytes();
    if b.is_empty() {
        return None;
    }
    let neg = b[0] == b'-';
    let mut i = usize::from(neg || b[0] == b'+');
    if i >= b.len() {
        return None;
    }
    let mut n: i64 = 0;
    while i < b.len() {
        let c = b[i].wrapping_sub(b'0');
        if c > 9 {
            return None;
        }
        n = n.checked_mul(10)?.checked_add(c as i64)?;
        i += 1;
    }
    Some(if neg { -n } else { n })
}

#[derive(Debug)]
pub struct DateError(String);

impl std::fmt::Display for DateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid date: {:?}", self.0)
    }
}

impl std::error::Error for DateError {}