php-dates 0.2.1

PHP date() patterns for Rust: strict createFromFormat-style parsing, a pattern resolution contract and a Day.js export, with no framework dependency
Documentation
//! Compiled PHP date patterns: `date()` / `DateTime::format()` and `DateTime::createFromFormat()`.

use crate::{Error, Result};
use std::{fmt, str::FromStr};

/// One piece of a pattern.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Token {
    /// A character that is not a token. `createFromFormat` gives ` # ? * ! | +` a meaning; `format` prints them.
    Literal(char),
    /// A character after a backslash: always itself.
    Escaped(char),
    /// `d`
    Day2,
    /// `D`
    DayShort,
    /// `j`
    Day,
    /// `l`
    DayName,
    /// `N`
    IsoWeekday,
    /// `S`
    OrdinalSuffix,
    /// `w`
    Weekday,
    /// `z`
    DayOfYear,
    /// `W`
    IsoWeek,
    /// `F`
    MonthName,
    /// `m`
    Month2,
    /// `M`
    MonthShort,
    /// `n`
    Month,
    /// `t`
    DaysInMonth,
    /// `L`
    LeapYear,
    /// `o`
    IsoYear,
    /// `X`
    ExpandedYear,
    /// `x`
    ExpandedYearSigned,
    /// `Y`
    Year4,
    /// `y`
    Year2,
    /// `a`
    MeridiemLower,
    /// `A`
    MeridiemUpper,
    /// `B`
    Swatch,
    /// `g`
    Hour12,
    /// `G`
    Hour24,
    /// `h`
    Hour12Padded,
    /// `H`
    Hour24Padded,
    /// `i`
    Minute,
    /// `s`
    Second,
    /// `u`
    Micro,
    /// `v`
    Milli,
    /// `e`
    ZoneName,
    /// `I`
    Dst,
    /// `O`
    OffsetCompact,
    /// `P`
    OffsetColon,
    /// `p`
    OffsetColonZ,
    /// `T`
    ZoneAbbreviation,
    /// `Z`
    OffsetSeconds,
    /// `c`
    Iso8601,
    /// `r`
    Rfc2822,
    /// `U`
    Timestamp,
}

impl Token {
    /// A token `createFromFormat()` does not read.
    pub(crate) const fn only_formats(self) -> bool {
        matches!(
            self,
            Self::IsoWeekday
                | Self::Weekday
                | Self::IsoWeek
                | Self::DaysInMonth
                | Self::LeapYear
                | Self::IsoYear
                | Self::Swatch
                | Self::Dst
                | Self::OffsetSeconds
                | Self::Iso8601
                | Self::Rfc2822
        )
    }
}

/// A compiled PHP date pattern.
///
/// The same pattern formats ([`format`](Self::format)) and parses ([`parse_at`](Self::parse_at)). The tokens are
/// those of PHP 8.5's `DateTime::format()`:
///
/// | | Tokens |
/// |---|---|
/// | Day | `d D j l N S w z` |
/// | Week | `W` |
/// | Month | `F m M n t` |
/// | Year | `L o X x Y y` |
/// | Time | `a A B g G h H i s u v` |
/// | Time zone | `e I O P p T Z` |
/// | Full | `c r U` |
/// | Escape | `\` |
///
/// Names are English. `createFromFormat()` reads `d D j l S z F m M n Y y X x a A g h G H i s v u e T O P p U`, plus
/// the pattern characters ` # ? * ! | +`; the others only format.
///
/// A compiled pattern is `Send + Sync` and does not change, so compile once and share it. [`as_str`](Self::as_str) and
/// `Display` give back the text it was compiled from, and [`FromStr`] is [`compile`](Self::compile).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhpDatePattern {
    pub(crate) tokens: Vec<Token>,
    source: Box<str>,
}

impl fmt::Display for PhpDatePattern {
    /// The pattern text, not a date.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad(&self.source)
    }
}

impl FromStr for PhpDatePattern {
    type Err = Error;

    fn from_str(pattern: &str) -> Result<Self> {
        Self::compile(pattern)
    }
}

impl PhpDatePattern {
    /// Compile a pattern the way PHP reads it: a letter that is not a token is a literal, and `\` escapes the next
    /// character.
    ///
    /// # Errors
    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash.
    pub fn compile(pattern: &str) -> Result<Self> {
        Self::build(pattern, false)
    }

    /// Like [`compile`](Self::compile), but a letter that is not a PHP token is an error instead of a literal. Use
    /// it to validate patterns a person typed: `compile("Y-m-d q")` prints a literal `q`, which is almost always a
    /// typo.
    ///
    /// # Errors
    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash or a letter that is not a token.
    pub fn compile_strict(pattern: &str) -> Result<Self> {
        Self::build(pattern, true)
    }

    /// The text the pattern was compiled from.
    #[must_use]
    pub const fn as_str(&self) -> &str {
        &self.source
    }

    /// Whether `createFromFormat()` can read this pattern: `false` when it has a token that only formats
    /// (`N w W o t L B I Z c r`), so that every parse would fail. Use it to reject a pattern for input when it is
    /// configured rather than on the first value.
    #[must_use]
    pub fn is_parseable(&self) -> bool {
        !self.tokens.iter().any(|token| token.only_formats())
    }

    fn build(pattern: &str, strict: bool) -> Result<Self> {
        let mut tokens = Vec::with_capacity(pattern.len());
        let mut chars = pattern.chars();
        while let Some(character) = chars.next() {
            tokens.push(match character {
                '\\' => Token::Escaped(
                    chars.next().ok_or_else(|| Error::argument("Date format ends with an incomplete escape."))?,
                ),
                'd' => Token::Day2,
                'D' => Token::DayShort,
                'j' => Token::Day,
                'l' => Token::DayName,
                'N' => Token::IsoWeekday,
                'S' => Token::OrdinalSuffix,
                'w' => Token::Weekday,
                'z' => Token::DayOfYear,
                'W' => Token::IsoWeek,
                'F' => Token::MonthName,
                'm' => Token::Month2,
                'M' => Token::MonthShort,
                'n' => Token::Month,
                't' => Token::DaysInMonth,
                'L' => Token::LeapYear,
                'o' => Token::IsoYear,
                'X' => Token::ExpandedYear,
                'x' => Token::ExpandedYearSigned,
                'Y' => Token::Year4,
                'y' => Token::Year2,
                'a' => Token::MeridiemLower,
                'A' => Token::MeridiemUpper,
                'B' => Token::Swatch,
                'g' => Token::Hour12,
                'G' => Token::Hour24,
                'h' => Token::Hour12Padded,
                'H' => Token::Hour24Padded,
                'i' => Token::Minute,
                's' => Token::Second,
                'u' => Token::Micro,
                'v' => Token::Milli,
                'e' => Token::ZoneName,
                'I' => Token::Dst,
                'O' => Token::OffsetCompact,
                'P' => Token::OffsetColon,
                'p' => Token::OffsetColonZ,
                'T' => Token::ZoneAbbreviation,
                'Z' => Token::OffsetSeconds,
                'c' => Token::Iso8601,
                'r' => Token::Rfc2822,
                'U' => Token::Timestamp,
                other if strict && other.is_ascii_alphabetic() => {
                    return Err(Error::argument(format!("PHP date token \"{other}\" is not supported.")));
                }
                other => Token::Literal(other),
            });
        }
        Ok(Self { tokens, source: pattern.into() })
    }
}