Skip to main content

deep_time/strptime/
mod.rs

1pub mod parser;
2
3use crate::error::{DtErr, DtErrKind};
4use crate::{Dt, TimeParts, an_err};
5use core::result::Result;
6use core::str;
7
8pub(crate) use parser::*;
9
10/// A pre-validated, reusable date/time format string.
11///
12/// - Format is validated **once** at construction (`new` returns `Result`).
13/// - Format bytes are copied into an owned fixed-size buffer.
14/// - Only ASCII formats are accepted.
15///
16/// ## See also
17///
18/// - [`StrPTimeFmt::new`]
19/// - [`StrPTimeFmt::to_dt`]
20/// - [`StrPTimeFmt::to_str`]
21#[derive(Debug, Clone, Copy)]
22pub struct StrPTimeFmt {
23    fmt: [u8; Self::MAX_FORMAT_LEN],
24    len: usize,
25}
26
27impl StrPTimeFmt {
28    pub const MAX_FORMAT_LEN: usize = 256;
29
30    /// Creates a new validated format.
31    ///
32    /// - Validates syntax and supported directives.
33    /// - Requires the format to be valid ASCII and ≤ 256 bytes.
34    /// - Returns a `DtErr` on any failure.
35    ///
36    /// ## Examples
37    ///
38    /// ```
39    /// # #[cfg(feature = "parse")]
40    /// # {
41    /// use deep_time::{Dt, StrPTimeFmt};
42    ///
43    /// let fmt = Dt::parse_fmt("%F %T").unwrap();
44    ///
45    /// // parse a datetime
46    /// let dt = fmt.to_dt("2025-05-23 14:30:00", false, false, false).unwrap();
47    ///
48    /// // change a datetimes format
49    /// let s = fmt.to_str("2000-01-01 12:00:00", "%d %m %Y %H:%M:%S", false, false, false).unwrap();
50    ///
51    /// assert_eq!(s, "01 01 2000 12:00:00");
52    /// # }
53    /// ```
54    pub fn new(fmt: &str) -> Result<Self, DtErr> {
55        if fmt.len() > Self::MAX_FORMAT_LEN {
56            return Err(an_err!(
57                DtErrKind::UnexpectedEnd,
58                "format string too long (max {} bytes)",
59                Self::MAX_FORMAT_LEN
60            ));
61        }
62        let fmt = fmt.as_bytes();
63        if !fmt.is_ascii() {
64            return Err(an_err!(
65                DtErrKind::UnexpectedEnd,
66                "format string must be ASCII"
67            ));
68        }
69
70        Self::validate_format(fmt)?;
71
72        let mut buffer = [0u8; Self::MAX_FORMAT_LEN];
73        buffer[..fmt.len()].copy_from_slice(fmt);
74
75        Ok(Self {
76            fmt: buffer,
77            len: fmt.len(),
78        })
79    }
80
81    /// Parses a date/time string using this pre-validated format.
82    ///
83    /// The four boolean flags control lenient parsing behavior — see
84    /// [`Dt::from_str`](../struct.Dt.html#method.from_str) for full documentation.
85    ///
86    /// ## Parameters
87    ///
88    /// - `s`: The input string to parse.
89    /// - `inp_can_end_before_fmt`: Allow input to end before format is fully consumed.
90    /// - `fmt_can_end_before_inp`: Allow format to end before input is fully consumed.
91    /// - `allow_partial_date`: Default missing month/day to `1` instead of erroring.
92    ///
93    /// ## Errors
94    ///
95    /// Returns [`DtErr`] for parse failures, incomplete data, trailing characters, etc.
96    ///
97    /// ## Examples
98    ///
99    /// ```
100    /// use deep_time::{Dt, StrPTimeFmt};
101    ///
102    /// let fmt = Dt::parse_fmt("%F %T").unwrap();
103    /// let dt = fmt.to_dt("2025-05-23 14:30:00", false, false, false).unwrap();
104    /// ```
105    pub fn to_dt(
106        &self,
107        s: &str,
108        inp_can_end_before_fmt: bool,
109        fmt_can_end_before_inp: bool,
110        allow_partial_date: bool,
111    ) -> Result<Dt, DtErr> {
112        TimeParts::from_str(
113            self.as_str()?,
114            s,
115            inp_can_end_before_fmt,
116            fmt_can_end_before_inp,
117            allow_partial_date,
118        )
119        .and_then(|p| p.to_dt())
120    }
121
122    /// Formats a [`Dt`] into a string using this pre-validated format and a given
123    /// output format.
124    ///
125    /// Effectively parses a [`str`] with the contained format, then outputs a
126    /// [`String`](`alloc::string::String`) to a new given format.
127    ///
128    /// Requires the `alloc` feature.
129    ///
130    /// ## Parameters
131    ///
132    /// - `s`: datetime input [`str`].
133    /// - `output_fmt`: The new format to output the datetime as.
134    /// - The remaining three flags are passed through to the internal `to_dt` call.
135    ///
136    /// ## Examples
137    ///
138    /// ```
139    /// use deep_time::{Dt, StrPTimeFmt};
140    ///
141    /// let fmt = Dt::parse_fmt("%Y-%m-%dT%H:%M:%S").unwrap();
142    /// let s = fmt.to_str("2000-01-01T12:00:00", "%d %m %Y %H:%M:%S", false, false, false).unwrap();
143    ///
144    /// assert_eq!(s, "01 01 2000 12:00:00");
145    /// ```
146    #[cfg(feature = "alloc")]
147    pub fn to_str(
148        &self,
149        s: &str,
150        output_fmt: &str,
151        inp_can_end_before_fmt: bool,
152        fmt_can_end_before_inp: bool,
153        allow_partial_date: bool,
154    ) -> Result<alloc::string::String, DtErr> {
155        let parts = TimeParts::from_str(
156            self.as_str()?,
157            s,
158            inp_can_end_before_fmt,
159            fmt_can_end_before_inp,
160            allow_partial_date,
161        )?;
162        parts.to_dt()?.to_str(output_fmt)
163    }
164
165    fn validate_format(mut fmt: &[u8]) -> Result<(), DtErr> {
166        while !fmt.is_empty() {
167            if fmt[0] != b'%' {
168                // literal character (including whitespace) — always valid
169                fmt = &fmt[1..];
170                continue;
171            }
172
173            // lone % at end of format
174            if fmt.len() == 1 {
175                return Err(an_err!(DtErrKind::UnexpectedEnd, "after %"));
176            }
177            fmt = &fmt[1..]; // eat %
178
179            // reuse existing helper for flags/width/colons
180            let (_, _, _, new_fmt) = Parser::parse_format_extensions(fmt, 0);
181            fmt = new_fmt;
182
183            if fmt.is_empty() {
184                return Err(an_err!(DtErrKind::UnexpectedEnd, "expected directive"));
185            }
186
187            let directive = fmt[0];
188
189            match directive {
190            // all currently supported directives
191            b'%' | b'A' | b'a' | b'B' | b'b' | b'h' | b'C' | b'd' | b'e' |
192            b'f' | b'N' | b'G' | b'g' | b'H' | b'k' | b'I' | b'l' | b'j' |
193            b'M' | b'm' | b'n' | b't' | b'P' | b'p' | b'Q' | b'S' | b's' |
194            b'U' | b'u' | b'V' | b'W' | b'w' | b'Y' | b'y' | b'z' |
195            // shortcuts
196            b'F' | b'D' | b'T' | b'R' |
197            // library directives
198            b'L' | b'*' => {
199                fmt = &fmt[1..];
200            }
201
202            b'.' => {
203                // special case for %.f / %.3N etc.
204                fmt = &fmt[1..]; // eat the .
205
206                // optional width digits
207                while !fmt.is_empty() && fmt[0].is_ascii_digit() {
208                    fmt = &fmt[1..];
209                }
210
211                let next = fmt.first().copied().unwrap_or(0);
212                if !matches!(next, b'f' | b'N') {
213                    return Err(an_err!(DtErrKind::BadFractional, "{}", char::from(next)));
214                }
215                fmt = &fmt[1..];
216            }
217
218            // explicitly unsupported (same as Parser)
219            b'c' | b'r' | b'X' | b'x' | b'Z' => {
220                return Err(an_err!(
221                    DtErrKind::UnsupportedDirective,
222                    "{}",
223                    char::from(directive)
224                ));
225            }
226
227            _ => {
228                return Err(an_err!(DtErrKind::UnknownDirective));
229            }
230        }
231        }
232
233        Ok(())
234    }
235
236    #[inline]
237    fn as_bytes(&self) -> &[u8] {
238        &self.fmt[..self.len]
239    }
240
241    #[inline]
242    fn as_str(&self) -> Result<&str, DtErr> {
243        match core::str::from_utf8(self.as_bytes()) {
244            Ok(f) => Ok(f),
245            Err(e) => Err(an_err!(DtErrKind::InvalidBytes, "{}", e)),
246        }
247    }
248}