time_compute 1.0.0

Dependency-free date/time computation library, with an API closely mirroring chrono
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
//! Formatting (and parsing) utilities for date and time.
//!
//! This module provides the common types and routines used to implement, for
//! example, [`DateTime::format`](crate::DateTime::format) or
//! [`DateTime::parse_from_str`](crate::DateTime::parse_from_str).
//! For most cases the high-level methods on [`NaiveDate`](crate::NaiveDate),
//! [`NaiveTime`](crate::NaiveTime), [`NaiveDateTime`](crate::NaiveDateTime)
//! and [`DateTime`](crate::DateTime) are easier to use.
//!
//! Internally, formatting and parsing share the same abstract **formatting
//! items**, which are just an [`Iterator`] of the [`Item`] type. They are
//! generated from more readable **format strings**; this crate supports a
//! built-in syntax closely resembling C's `strftime` format. The available
//! specifiers are documented in the [`strftime`] module.
//!
//! Month names, weekday names, AM/PM markers and the `%x`/`%X`/`%c`/`%r`
//! formats are always in English/POSIX by default. Locale-aware
//! alternatives (matching `chrono`'s own `unstable-locales` feature 1:1,
//! including the "unstable" naming) are available
//! behind the `unstable-locales` crate feature: see [`Locale`],
//! [`StrftimeItems::new_with_locale`], and the `format_localized`/
//! `format_localized_with_items` methods on [`NaiveDate`](crate::NaiveDate)
//! and [`DateTime`](crate::DateTime).

use core::fmt;
use std::boxed::Box;

mod formatting;
pub(crate) mod locales;
mod parse;
mod parsed;
pub(crate) mod scan;

pub mod strftime;

pub use formatting::{DelayedFormat, SecondsFormat};
pub(crate) use formatting::{write_rfc2822, write_rfc3339};
#[cfg(feature = "unstable-locales")]
pub use locales::Locale;
pub(crate) use parse::parse_rfc3339;
pub use parse::{parse, parse_and_remainder};
pub use parsed::Parsed;
pub use strftime::StrftimeItems;

/// An uninhabited type used for `InternalNumeric` and `InternalFixed` below.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Void {}

/// Padding characters for numeric items.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Pad {
    /// No padding.
    None,
    /// Zero (`0`) padding.
    Zero,
    /// Space padding.
    Space,
}

/// Numeric item types.
///
/// They have associated formatting width (FW) and parsing width (PW).
///
/// The **formatting width** is the minimal width to be formatted. If the
/// number is too short, and the padding is not [`Pad::None`], then it is
/// left-padded. If the number is too long or (in some cases) negative, it is
/// printed as is.
///
/// The **parsing width** is the maximal width to be scanned. The parser only
/// tries to consume from one to the given number of digits (greedily). It
/// also trims the preceding whitespace, if any. It cannot parse a negative
/// number, so some date and time values cannot be formatted then parsed with
/// the same formatting items.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Numeric {
    /// Full Gregorian year (FW=4, PW=infinite).
    /// May accept years before 1 BCE or after 9999 CE, given an initial sign (+/-).
    Year,
    /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
    YearDiv100,
    /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
    YearMod100,
    /// Year in the ISO week date (FW=4, PW=infinite).
    /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
    IsoYear,
    /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
    IsoYearDiv100,
    /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
    IsoYearMod100,
    /// Quarter (FW=PW=1).
    Quarter,
    /// Month (FW=PW=2).
    Month,
    /// Day of the month (FW=PW=2).
    Day,
    /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
    WeekFromSun,
    /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
    WeekFromMon,
    /// Week number in the ISO week date (FW=PW=2).
    IsoWeek,
    /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
    NumDaysFromSun,
    /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
    WeekdayFromMon,
    /// Day of the year (FW=PW=3).
    Ordinal,
    /// Hour number in the 24-hour clocks (FW=PW=2).
    Hour,
    /// Hour number in the 12-hour clocks (FW=PW=2).
    Hour12,
    /// The number of minutes since the last whole hour (FW=PW=2).
    Minute,
    /// The number of seconds since the last whole minute (FW=PW=2).
    Second,
    /// The number of nanoseconds since the last whole second (FW=PW=9).
    /// Note that this is *not* left-aligned; see also [`Fixed::Nanosecond`].
    Nanosecond,
    /// The number of non-leap seconds since midnight UTC on January 1, 1970 (FW=1, PW=infinite).
    /// For formatting, it assumes UTC upon the absence of a time zone offset.
    Timestamp,

    /// Internal uses only.
    ///
    /// This item exists so that one can add additional internal-only
    /// formatting without breaking major compatibility (as enum variants
    /// cannot be selectively private).
    Internal(InternalNumeric),
}

/// An opaque type representing numeric item types for internal uses only.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct InternalNumeric {
    _dummy: Void,
}

impl fmt::Debug for InternalNumeric {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<InternalNumeric>")
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for InternalNumeric {
    fn format(&self, f: defmt::Formatter) {
        defmt::write!(f, "<InternalNumeric>")
    }
}

/// Fixed-format item types.
///
/// They have their own rules of formatting and parsing. Otherwise noted,
/// they print in the specified case but parse case-insensitively.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Fixed {
    /// Abbreviated month names.
    ///
    /// Prints a three-letter-long name in the title case, reads the same name in any case.
    ShortMonthName,
    /// Full month names.
    ///
    /// Prints a full name in the title case, reads either a short or full name in any case.
    LongMonthName,
    /// Abbreviated day of the week names.
    ///
    /// Prints a three-letter-long name in the title case, reads the same name in any case.
    ShortWeekdayName,
    /// Full day of the week names.
    ///
    /// Prints a full name in the title case, reads either a short or full name in any case.
    LongWeekdayName,
    /// AM/PM.
    ///
    /// Prints in lower case, reads in any case.
    LowerAmPm,
    /// AM/PM.
    ///
    /// Prints in upper case, reads in any case.
    UpperAmPm,
    /// An optional dot plus one or more digits for left-aligned nanoseconds.
    /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
    /// See also [`Numeric::Nanosecond`].
    Nanosecond,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 3.
    Nanosecond3,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 6.
    Nanosecond6,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 9.
    Nanosecond9,
    /// Timezone name.
    ///
    /// It does not support parsing, its use in the parser is an immediate failure.
    TimezoneName,
    /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
    ///
    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
    /// The offset is limited from `-24:00` to `+24:00`, same as [`FixedOffset`](crate::FixedOffset)'s range.
    TimezoneOffsetColon,
    /// Offset from the local time to UTC with seconds (`+09:00:00` or `-04:00:00` or `+00:00:00`).
    ///
    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
    /// The offset is limited from `-24:00:00` to `+24:00:00`, same as [`FixedOffset`](crate::FixedOffset)'s range.
    TimezoneOffsetDoubleColon,
    /// Offset from the local time to UTC without minutes (`+09` or `-04` or `+00`).
    ///
    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
    /// The offset is limited from `-24` to `+24`, same as [`FixedOffset`](crate::FixedOffset)'s range.
    TimezoneOffsetTripleColon,
    /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
    ///
    /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
    /// and `Z` can be either in upper case or in lower case.
    /// The offset is limited from `-24:00` to `+24:00`, same as [`FixedOffset`](crate::FixedOffset)'s range.
    TimezoneOffsetColonZ,
    /// Same as [`TimezoneOffsetColon`](Fixed::TimezoneOffsetColon) but prints no colon.
    /// Parsing allows an optional colon.
    TimezoneOffset,
    /// Same as [`TimezoneOffsetColonZ`](Fixed::TimezoneOffsetColonZ) but prints no colon.
    /// Parsing allows an optional colon.
    TimezoneOffsetZ,
    /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
    RFC2822,
    /// RFC 3339 & ISO 8601 date and time syntax.
    RFC3339,

    /// Internal uses only.
    ///
    /// This item exists so that one can add additional internal-only
    /// formatting without breaking major compatibility (as enum variants
    /// cannot be selectively private).
    Internal(InternalFixed),
}

/// An opaque type representing fixed-format item types for internal uses only.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InternalFixed {
    val: InternalInternal,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum InternalInternal {
    /// Same as [`TimezoneOffsetColonZ`](Fixed::TimezoneOffsetColonZ), but allows missing minutes
    /// (per ISO 8601). Panics if used for printing.
    TimezoneOffsetPermissive,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
    Nanosecond3NoDot,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
    Nanosecond6NoDot,
    /// Same as [`Nanosecond`](Fixed::Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
    Nanosecond9NoDot,
}

/// Type for specifying the format of UTC offsets.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct OffsetFormat {
    /// See [`OffsetPrecision`].
    pub precision: OffsetPrecision,
    /// Separator between hours, minutes and seconds.
    pub colons: Colons,
    /// Represent `+00:00` as `Z`.
    pub allow_zulu: bool,
    /// Pad the hour value to two digits.
    pub padding: Pad,
}

/// The precision of an offset from UTC formatting item.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum OffsetPrecision {
    /// Format offset from UTC as only hours. Not recommended: it is not
    /// uncommon for time zones to have an offset of 30 minutes, 15 minutes,
    /// etc. Any minutes and seconds get truncated.
    Hours,
    /// Format offset from UTC as hours and minutes.
    /// Any seconds will be rounded to the nearest minute.
    Minutes,
    /// Format offset from UTC as hours, minutes and seconds.
    Seconds,
    /// Format offset from UTC as hours, and optionally with minutes.
    /// Any seconds will be rounded to the nearest minute.
    OptionalMinutes,
    /// Format offset from UTC as hours and minutes, and optionally seconds.
    OptionalSeconds,
    /// Format offset from UTC as hours and optionally minutes and seconds.
    OptionalMinutesAndSeconds,
}

/// The separator between hours and minutes in an offset.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Colons {
    /// No separator.
    None,
    /// Colon (`:`) as separator.
    Colon,
    /// No separator when formatting, colon allowed when parsing.
    Maybe,
}

/// A single formatting item. This is used for both formatting and parsing.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub enum Item<'a> {
    /// A literally printed and parsed text.
    Literal(&'a str),
    /// Same as `Literal` but with the string owned by the item.
    OwnedLiteral(Box<str>),
    /// Whitespace. Prints literally but reads zero or more whitespace.
    Space(&'a str),
    /// Same as `Space` but with the string owned by the item.
    OwnedSpace(Box<str>),
    /// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
    /// the parser simply ignores any padded whitespace and zeroes.
    Numeric(Numeric, Pad),
    /// Fixed-format item.
    Fixed(Fixed),
    /// Issues a formatting error. Used to signal an invalid format string.
    Error,
}

#[cfg(feature = "defmt")]
impl<'a> defmt::Format for Item<'a> {
    fn format(&self, f: defmt::Formatter) {
        match self {
            Item::Literal(v) => defmt::write!(f, "Literal {{ {} }}", v),
            Item::OwnedLiteral(_) => {}
            Item::Space(v) => defmt::write!(f, "Space {{ {}  }}", v),
            Item::OwnedSpace(_) => {}
            Item::Numeric(u, v) => defmt::write!(f, "Numeric {{ {}, {} }}", u, v),
            Item::Fixed(v) => defmt::write!(f, "Fixed {{ {}  }}", v),
            Item::Error => defmt::write!(f, "Error"),
        }
    }
}

const fn num(numeric: Numeric) -> Item<'static> {
    Item::Numeric(numeric, Pad::None)
}

const fn num0(numeric: Numeric) -> Item<'static> {
    Item::Numeric(numeric, Pad::Zero)
}

const fn nums(numeric: Numeric) -> Item<'static> {
    Item::Numeric(numeric, Pad::Space)
}

const fn fixed(fixed: Fixed) -> Item<'static> {
    Item::Fixed(fixed)
}

const fn internal_fixed(val: InternalInternal) -> Item<'static> {
    Item::Fixed(Fixed::Internal(InternalFixed { val }))
}

impl Item<'_> {
    /// Converts items that contain a reference to the format string into an owned variant.
    pub fn to_owned(self) -> Item<'static> {
        match self {
            Item::Literal(s) => Item::OwnedLiteral(Box::from(s)),
            Item::Space(s) => Item::OwnedSpace(Box::from(s)),
            Item::Numeric(n, p) => Item::Numeric(n, p),
            Item::Fixed(f) => Item::Fixed(f),
            Item::OwnedLiteral(l) => Item::OwnedLiteral(l),
            Item::OwnedSpace(s) => Item::OwnedSpace(s),
            Item::Error => Item::Error,
        }
    }
}

/// An error from the `parse` function.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ParseError(ParseErrorKind);

impl ParseError {
    /// The category of parse error.
    pub const fn kind(&self) -> ParseErrorKind {
        self.0
    }
}

/// The category of parse error.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ParseErrorKind {
    /// Given field is out of permitted range.
    OutOfRange,
    /// There is no possible date and time value with the given set of fields.
    ///
    /// This does not include the out-of-range conditions, which are
    /// trivially invalid. It includes the case that there are one or more
    /// fields that are inconsistent with each other.
    Impossible,
    /// Given set of fields is not enough to make a requested date and time value.
    NotEnough,
    /// The input string has some invalid character sequence for the given formatting items.
    Invalid,
    /// The input string has been prematurely ended.
    TooShort,
    /// All formatting items have been read but there is a remaining input.
    TooLong,
    /// There was an error in the formatting string, or there were non-supported formatting items.
    BadFormat,
}

/// Same as `Result<T, ParseError>`.
pub type ParseResult<T> = Result<T, ParseError>;

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            ParseErrorKind::OutOfRange => write!(f, "input is out of range"),
            ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"),
            ParseErrorKind::NotEnough => write!(f, "input is not enough for unique date and time"),
            ParseErrorKind::Invalid => write!(f, "input contains invalid characters"),
            ParseErrorKind::TooShort => write!(f, "premature end of input"),
            ParseErrorKind::TooLong => write!(f, "trailing input"),
            ParseErrorKind::BadFormat => write!(f, "bad or unsupported format string"),
        }
    }
}

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

// to be used in this module and submodules
pub(crate) const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible);
const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough);
const INVALID: ParseError = ParseError(ParseErrorKind::Invalid);
const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort);
pub(crate) const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong);
const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn item_to_owned_converts_literal_and_space_variants() {
        assert_eq!(Item::Literal("abc").to_owned(), Item::OwnedLiteral(Box::from("abc")));
        assert_eq!(Item::Space(" ").to_owned(), Item::OwnedSpace(Box::from(" ")));
        // Already-owned and non-borrowing variants pass through unchanged.
        assert_eq!(
            Item::OwnedLiteral(Box::from("xyz")).to_owned(),
            Item::OwnedLiteral(Box::from("xyz"))
        );
        assert_eq!(Item::Numeric(Numeric::Year, Pad::Zero).to_owned(), num0(Numeric::Year));
        assert_eq!(Item::Fixed(Fixed::RFC3339).to_owned(), fixed(Fixed::RFC3339));
        assert_eq!(Item::Error.to_owned(), Item::Error);
    }

    #[test]
    fn parse_error_kind_round_trips_through_the_accessor() {
        assert_eq!(OUT_OF_RANGE.kind(), ParseErrorKind::OutOfRange);
        assert_eq!(TOO_SHORT.kind(), ParseErrorKind::TooShort);
        assert_eq!(TOO_LONG.kind(), ParseErrorKind::TooLong);
        assert_eq!(BAD_FORMAT.kind(), ParseErrorKind::BadFormat);
        assert_eq!(IMPOSSIBLE.kind(), ParseErrorKind::Impossible);
        assert_eq!(NOT_ENOUGH.kind(), ParseErrorKind::NotEnough);
        assert_eq!(INVALID.kind(), ParseErrorKind::Invalid);
    }

    #[test]
    fn parse_error_display_messages_are_distinct_and_non_empty() {
        let all = [OUT_OF_RANGE, IMPOSSIBLE, NOT_ENOUGH, INVALID, TOO_SHORT, TOO_LONG, BAD_FORMAT];
        let mut messages: Vec<String> = all.iter().map(|e| e.to_string()).collect();
        for msg in &messages {
            assert!(!msg.is_empty());
        }
        let original_len = messages.len();
        messages.sort();
        messages.dedup();
        assert_eq!(messages.len(), original_len, "each ParseErrorKind should have a distinct message");
    }

    #[test]
    fn numeric_and_fixed_helper_constructors_use_the_expected_padding() {
        assert_eq!(num(Numeric::Day), Item::Numeric(Numeric::Day, Pad::None));
        assert_eq!(num0(Numeric::Day), Item::Numeric(Numeric::Day, Pad::Zero));
        assert_eq!(nums(Numeric::Day), Item::Numeric(Numeric::Day, Pad::Space));
        assert_eq!(fixed(Fixed::ShortMonthName), Item::Fixed(Fixed::ShortMonthName));
    }

    #[test]
    fn pad_variants_are_distinguishable() {
        assert_ne!(Pad::None, Pad::Zero);
        assert_ne!(Pad::Zero, Pad::Space);
        assert_ne!(Pad::None, Pad::Space);
    }
}