grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/time/dialect.rs
// Purpose:   Strptime formats from other log tools, translated to jiff's
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::borrow::Cow;

use super::{JavaPattern, TimeError, TimeFormat};

/// The strptime dialect a format string is written in. Each reads a few
/// directives differently from jiff, such as `%L`, or `%j` as an offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StrptimeDialect {
    /// jiff's own strtime: no translation.
    Jiff,
    /// C strptime plus `%L` for fractional seconds.
    PercentL,
    /// ctime-style letters: `%L` fractions, `%o` `%q` `%g` `%l` unpadded
    /// fields, `%w` `%i` `%j` `%k` offsets.
    Ctime,
    /// `%N` and `%Q` for subsecond digits, as in `%3N`.
    PercentN,
    /// Java-style date patterns, as in `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`: pattern
    /// letters, `'quoted'` literals and `[optional]` sections. Builds a
    /// [`TimeFormat::Java`].
    Java,
}

impl TimeFormat {
    /// A [`TimeFormat::Strptime`] from `format` written in `dialect`, or a
    /// [`TimeFormat::Java`] for [`StrptimeDialect::Java`].
    ///
    /// # Errors
    ///
    /// [`TimeError::Directive`] for a directive jiff can't parse: a zone
    /// abbreviation (`%Z`), a locale form (`%c`, `%x`) or `%Ez`.
    /// [`TimeError::Pattern`] for a Java-style pattern letter grippo doesn't
    /// read, an unclosed quote or a stray `]`.
    pub fn strptime(dialect: StrptimeDialect, format: &str) -> Result<Self, TimeError> {
        match dialect {
            StrptimeDialect::Jiff => return Ok(Self::Strptime(format.to_owned())),
            StrptimeDialect::Java => return JavaPattern::build(format).map(Self::Java),
            _ => {}
        }
        let mut out = String::with_capacity(format.len() + 8);
        let mut rest = format;
        while let Some(at) = rest.find('%') {
            out.push_str(&rest[..at]);
            let tail = &rest[at + 1..];
            let len = tail
                .char_indices()
                .find(|&(_, c)| c.is_ascii_alphabetic() || matches!(c, '%' | '+'))
                .map(|(i, c)| i + c.len_utf8())
                .ok_or_else(|| TimeError::Directive(rest[at..].to_owned()))?;
            out.push_str(&directive(dialect, &rest[at..=at + len])?);
            rest = &tail[len..];
        }
        out.push_str(rest);
        Ok(Self::Strptime(out))
    }
}

/// One directive, `%` through its letter, in jiff's dialect.
fn directive(dialect: StrptimeDialect, spec: &str) -> Result<Cow<'_, str>, TimeError> {
    let refuse = || Err(TimeError::Directive(spec.to_owned()));
    let mapped = match (dialect, spec) {
        (_, "%Z") | (StrptimeDialect::PercentN, "%c" | "%+" | "%x" | "%X" | "%E") => {
            return refuse();
        }
        (StrptimeDialect::PercentL | StrptimeDialect::Ctime, "%L") => "%f",
        (StrptimeDialect::Ctime, "%o") => "%_m",
        (StrptimeDialect::Ctime, "%q") => "%-m",
        (StrptimeDialect::Ctime, "%g") => "%-d",
        (StrptimeDialect::Ctime, "%l") => "%-I",
        (StrptimeDialect::Ctime, "%w") => "%z",
        (StrptimeDialect::Ctime, "%i") => "%:::z",
        (StrptimeDialect::Ctime, "%j") => "%:z",
        (StrptimeDialect::Ctime, "%k") => "%::z",
        (StrptimeDialect::Ctime, "%D" | "%x") => "%m/%d/%Y",
        (StrptimeDialect::Ctime, "%T" | "%X") => "%H:%M:%S",
        (StrptimeDialect::Ctime, "%r") => "%I:%M:%S %P",
        (StrptimeDialect::Ctime, "%c") => "%a %b %d %H:%M:%S %Y",
        (StrptimeDialect::PercentN, _) if spec.ends_with(['N', 'Q']) => {
            return Ok(Cow::Owned(format!("{}f", &spec[..spec.len() - 1])));
        }
        _ => spec,
    };
    Ok(Cow::Borrowed(mapped))
}