1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
34//! Formatting (and parsing) utilities for date and time.
5//!
6//! This module provides the common types and routines to implement,
7//! for example, [`DateTime::format`](../struct.DateTime.html#method.format) or
8//! [`DateTime::parse_from_str`](../struct.DateTime.html#method.parse_from_str) methods.
9//! For most cases you should use these high-level interfaces.
10//!
11//! Internally the formatting and parsing shares the same abstract **formatting items**,
12//! which are just an [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) of
13//! the [`Item`](./enum.Item.html) type.
14//! They are generated from more readable **format strings**;
15//! currently Chrono supports a built-in syntax closely resembling
16//! C's `strftime` format. The available options can be found [here](./strftime/index.html).
17//!
18//! # Example
19//! ```
20//! # #[cfg(feature = "alloc")] {
21//! use chrono::{NaiveDateTime, TimeZone, Utc};
22//!
23//! let date_time = Utc.with_ymd_and_hms(2020, 11, 10, 0, 1, 32).unwrap();
24//!
25//! let formatted = format!("{}", date_time.format("%Y-%m-%d %H:%M:%S"));
26//! assert_eq!(formatted, "2020-11-10 00:01:32");
27//!
28//! let parsed = NaiveDateTime::parse_from_str(&formatted, "%Y-%m-%d %H:%M:%S")?.and_utc();
29//! assert_eq!(parsed, date_time);
30//! # }
31//! # Ok::<(), chrono::ParseError>(())
32//! ```
3334#[cfg(all(feature = "alloc", not(feature = "std"), not(test)))]
35use alloc::boxed::Box;
36#[cfg(all(feature = "core-error", not(feature = "std")))]
37use core::error::Error;
38use core::fmt;
39use core::str::FromStr;
40#[cfg(feature = "std")]
41use std::error::Error;
4243use crate::{Month, ParseMonthError, ParseWeekdayError, Weekday};
4445mod formatting;
46mod parsed;
4748// due to the size of parsing routines, they are in separate modules.
49mod parse;
50pub(crate) mod scan;
5152pub mod strftime;
5354#[allow(unused)]
55// TODO: remove '#[allow(unused)]' once we use this module for parsing or something else that does
56// not require `alloc`.
57pub(crate) mod locales;
5859pub use formatting::SecondsFormat;
60pub(crate) use formatting::write_hundreds;
61#[cfg(feature = "alloc")]
62pub(crate) use formatting::write_rfc2822;
63#[cfg(any(feature = "alloc", feature = "serde"))]
64pub(crate) use formatting::write_rfc3339;
65#[cfg(feature = "alloc")]
66#[allow(deprecated)]
67pub use formatting::{DelayedFormat, format, format_item};
68#[cfg(feature = "unstable-locales")]
69pub use locales::Locale;
70pub(crate) use parse::parse_rfc3339;
71pub use parse::{parse, parse_and_remainder};
72pub use parsed::Parsed;
73pub use strftime::StrftimeItems;
7475/// An uninhabited type used for `InternalNumeric` and `InternalFixed` below.
76#[derive(#[automatically_derived]
impl ::core::clone::Clone for Void {
#[inline]
fn clone(&self) -> Void { match *self {} }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Void {
#[inline]
fn eq(&self, other: &Void) -> bool { match *self {} }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Void {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Void {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
match *self {}
}
}Hash)]
77enum Void {}
7879/// Padding characters for numeric items.
80#[derive(#[automatically_derived]
impl ::core::marker::Copy for Pad { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Pad {
#[inline]
fn clone(&self) -> Pad { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Pad {
#[inline]
fn eq(&self, other: &Pad) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Pad {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for Pad {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Pad::None => "None",
Pad::Zero => "Zero",
Pad::Space => "Space",
})
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for Pad {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
81#[cfg_attr(feature = "defmt", derive(defmt::Format))]
82pub enum Pad {
83/// No padding.
84None,
85/// Zero (`0`) padding.
86Zero,
87/// Space padding.
88Space,
89}
9091/// Numeric item types.
92/// They have associated formatting width (FW) and parsing width (PW).
93///
94/// The **formatting width** is the minimal width to be formatted.
95/// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
96/// then it is left-padded.
97/// If the number is too long or (in some cases) negative, it is printed as is.
98///
99/// The **parsing width** is the maximal width to be scanned.
100/// The parser only tries to consume from one to given number of digits (greedily).
101/// It also trims the preceding whitespace if any.
102/// It cannot parse the negative number, so some date and time cannot be formatted then
103/// parsed with the same formatting items.
104#[non_exhaustive]
105#[derive(#[automatically_derived]
impl ::core::clone::Clone for Numeric {
#[inline]
fn clone(&self) -> Numeric {
match self {
Numeric::Year => Numeric::Year,
Numeric::YearDiv100 => Numeric::YearDiv100,
Numeric::YearMod100 => Numeric::YearMod100,
Numeric::IsoYear => Numeric::IsoYear,
Numeric::IsoYearDiv100 => Numeric::IsoYearDiv100,
Numeric::IsoYearMod100 => Numeric::IsoYearMod100,
Numeric::Quarter => Numeric::Quarter,
Numeric::Month => Numeric::Month,
Numeric::Day => Numeric::Day,
Numeric::WeekFromSun => Numeric::WeekFromSun,
Numeric::WeekFromMon => Numeric::WeekFromMon,
Numeric::IsoWeek => Numeric::IsoWeek,
Numeric::NumDaysFromSun => Numeric::NumDaysFromSun,
Numeric::WeekdayFromMon => Numeric::WeekdayFromMon,
Numeric::Ordinal => Numeric::Ordinal,
Numeric::Hour => Numeric::Hour,
Numeric::Hour12 => Numeric::Hour12,
Numeric::Minute => Numeric::Minute,
Numeric::Second => Numeric::Second,
Numeric::Nanosecond => Numeric::Nanosecond,
Numeric::Timestamp => Numeric::Timestamp,
Numeric::Internal(__self_0) =>
Numeric::Internal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Numeric {
#[inline]
fn eq(&self, other: &Numeric) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Numeric::Internal(__self_0), Numeric::Internal(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Numeric {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<InternalNumeric>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for Numeric {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Numeric::Year => ::core::fmt::Formatter::write_str(f, "Year"),
Numeric::YearDiv100 =>
::core::fmt::Formatter::write_str(f, "YearDiv100"),
Numeric::YearMod100 =>
::core::fmt::Formatter::write_str(f, "YearMod100"),
Numeric::IsoYear =>
::core::fmt::Formatter::write_str(f, "IsoYear"),
Numeric::IsoYearDiv100 =>
::core::fmt::Formatter::write_str(f, "IsoYearDiv100"),
Numeric::IsoYearMod100 =>
::core::fmt::Formatter::write_str(f, "IsoYearMod100"),
Numeric::Quarter =>
::core::fmt::Formatter::write_str(f, "Quarter"),
Numeric::Month => ::core::fmt::Formatter::write_str(f, "Month"),
Numeric::Day => ::core::fmt::Formatter::write_str(f, "Day"),
Numeric::WeekFromSun =>
::core::fmt::Formatter::write_str(f, "WeekFromSun"),
Numeric::WeekFromMon =>
::core::fmt::Formatter::write_str(f, "WeekFromMon"),
Numeric::IsoWeek =>
::core::fmt::Formatter::write_str(f, "IsoWeek"),
Numeric::NumDaysFromSun =>
::core::fmt::Formatter::write_str(f, "NumDaysFromSun"),
Numeric::WeekdayFromMon =>
::core::fmt::Formatter::write_str(f, "WeekdayFromMon"),
Numeric::Ordinal =>
::core::fmt::Formatter::write_str(f, "Ordinal"),
Numeric::Hour => ::core::fmt::Formatter::write_str(f, "Hour"),
Numeric::Hour12 => ::core::fmt::Formatter::write_str(f, "Hour12"),
Numeric::Minute => ::core::fmt::Formatter::write_str(f, "Minute"),
Numeric::Second => ::core::fmt::Formatter::write_str(f, "Second"),
Numeric::Nanosecond =>
::core::fmt::Formatter::write_str(f, "Nanosecond"),
Numeric::Timestamp =>
::core::fmt::Formatter::write_str(f, "Timestamp"),
Numeric::Internal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Internal", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for Numeric {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
Numeric::Internal(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash)]
106#[cfg_attr(feature = "defmt", derive(defmt::Format))]
107pub enum Numeric {
108/// Full Gregorian year (FW=4, PW=∞).
109 /// May accept years before 1 BCE or after 9999 CE, given an initial sign (+/-).
110Year,
111/// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
112YearDiv100,
113/// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
114YearMod100,
115/// Year in the ISO week date (FW=4, PW=∞).
116 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
117IsoYear,
118/// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
119IsoYearDiv100,
120/// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
121IsoYearMod100,
122/// Quarter (FW=PW=1).
123Quarter,
124/// Month (FW=PW=2).
125Month,
126/// Day of the month (FW=PW=2).
127Day,
128/// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
129WeekFromSun,
130/// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
131WeekFromMon,
132/// Week number in the ISO week date (FW=PW=2).
133IsoWeek,
134/// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
135NumDaysFromSun,
136/// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
137WeekdayFromMon,
138/// Day of the year (FW=PW=3).
139Ordinal,
140/// Hour number in the 24-hour clocks (FW=PW=2).
141Hour,
142/// Hour number in the 12-hour clocks (FW=PW=2).
143Hour12,
144/// The number of minutes since the last whole hour (FW=PW=2).
145Minute,
146/// The number of seconds since the last whole minute (FW=PW=2).
147Second,
148/// The number of nanoseconds since the last whole second (FW=PW=9).
149 /// Note that this is *not* left-aligned;
150 /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
151Nanosecond,
152/// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
153 /// For formatting, it assumes UTC upon the absence of time zone offset.
154Timestamp,
155156/// Internal uses only.
157 ///
158 /// This item exists so that one can add additional internal-only formatting
159 /// without breaking major compatibility (as enum variants cannot be selectively private).
160Internal(InternalNumeric),
161}
162163/// An opaque type representing numeric item types for internal uses only.
164#[derive(#[automatically_derived]
impl ::core::clone::Clone for InternalNumeric {
#[inline]
fn clone(&self) -> InternalNumeric {
InternalNumeric { _dummy: ::core::clone::Clone::clone(&self._dummy) }
}
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for InternalNumeric {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Void>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for InternalNumeric {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self._dummy, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for InternalNumeric {
#[inline]
fn eq(&self, other: &InternalNumeric) -> bool {
self._dummy == other._dummy
}
}PartialEq)]
165pub struct InternalNumeric {
166 _dummy: Void,
167}
168169impl fmt::Debugfor InternalNumeric {
170fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171f.write_fmt(format_args!("<InternalNumeric>"))write!(f, "<InternalNumeric>")172 }
173}
174175#[cfg(feature = "defmt")]
176impl defmt::Format for InternalNumeric {
177fn format(&self, f: defmt::Formatter) {
178defmt::write!(f, "<InternalNumeric>")
179 }
180}
181182/// Fixed-format item types.
183///
184/// They have their own rules of formatting and parsing.
185/// Otherwise noted, they print in the specified cases but parse case-insensitively.
186#[non_exhaustive]
187#[derive(#[automatically_derived]
impl ::core::clone::Clone for Fixed {
#[inline]
fn clone(&self) -> Fixed {
match self {
Fixed::ShortMonthName => Fixed::ShortMonthName,
Fixed::LongMonthName => Fixed::LongMonthName,
Fixed::ShortWeekdayName => Fixed::ShortWeekdayName,
Fixed::LongWeekdayName => Fixed::LongWeekdayName,
Fixed::LowerAmPm => Fixed::LowerAmPm,
Fixed::UpperAmPm => Fixed::UpperAmPm,
Fixed::Nanosecond => Fixed::Nanosecond,
Fixed::Nanosecond3 => Fixed::Nanosecond3,
Fixed::Nanosecond6 => Fixed::Nanosecond6,
Fixed::Nanosecond9 => Fixed::Nanosecond9,
Fixed::TimezoneName => Fixed::TimezoneName,
Fixed::TimezoneOffsetColon => Fixed::TimezoneOffsetColon,
Fixed::TimezoneOffsetDoubleColon =>
Fixed::TimezoneOffsetDoubleColon,
Fixed::TimezoneOffsetTripleColon =>
Fixed::TimezoneOffsetTripleColon,
Fixed::TimezoneOffsetColonZ => Fixed::TimezoneOffsetColonZ,
Fixed::TimezoneOffset => Fixed::TimezoneOffset,
Fixed::TimezoneOffsetZ => Fixed::TimezoneOffsetZ,
Fixed::RFC2822 => Fixed::RFC2822,
Fixed::RFC3339 => Fixed::RFC3339,
Fixed::Internal(__self_0) =>
Fixed::Internal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Fixed {
#[inline]
fn eq(&self, other: &Fixed) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Fixed::Internal(__self_0), Fixed::Internal(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Fixed {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<InternalFixed>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for Fixed {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Fixed::ShortMonthName =>
::core::fmt::Formatter::write_str(f, "ShortMonthName"),
Fixed::LongMonthName =>
::core::fmt::Formatter::write_str(f, "LongMonthName"),
Fixed::ShortWeekdayName =>
::core::fmt::Formatter::write_str(f, "ShortWeekdayName"),
Fixed::LongWeekdayName =>
::core::fmt::Formatter::write_str(f, "LongWeekdayName"),
Fixed::LowerAmPm =>
::core::fmt::Formatter::write_str(f, "LowerAmPm"),
Fixed::UpperAmPm =>
::core::fmt::Formatter::write_str(f, "UpperAmPm"),
Fixed::Nanosecond =>
::core::fmt::Formatter::write_str(f, "Nanosecond"),
Fixed::Nanosecond3 =>
::core::fmt::Formatter::write_str(f, "Nanosecond3"),
Fixed::Nanosecond6 =>
::core::fmt::Formatter::write_str(f, "Nanosecond6"),
Fixed::Nanosecond9 =>
::core::fmt::Formatter::write_str(f, "Nanosecond9"),
Fixed::TimezoneName =>
::core::fmt::Formatter::write_str(f, "TimezoneName"),
Fixed::TimezoneOffsetColon =>
::core::fmt::Formatter::write_str(f, "TimezoneOffsetColon"),
Fixed::TimezoneOffsetDoubleColon =>
::core::fmt::Formatter::write_str(f,
"TimezoneOffsetDoubleColon"),
Fixed::TimezoneOffsetTripleColon =>
::core::fmt::Formatter::write_str(f,
"TimezoneOffsetTripleColon"),
Fixed::TimezoneOffsetColonZ =>
::core::fmt::Formatter::write_str(f, "TimezoneOffsetColonZ"),
Fixed::TimezoneOffset =>
::core::fmt::Formatter::write_str(f, "TimezoneOffset"),
Fixed::TimezoneOffsetZ =>
::core::fmt::Formatter::write_str(f, "TimezoneOffsetZ"),
Fixed::RFC2822 => ::core::fmt::Formatter::write_str(f, "RFC2822"),
Fixed::RFC3339 => ::core::fmt::Formatter::write_str(f, "RFC3339"),
Fixed::Internal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Internal", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for Fixed {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
Fixed::Internal(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash)]
188#[cfg_attr(feature = "defmt", derive(defmt::Format))]
189pub enum Fixed {
190/// Abbreviated month names.
191 ///
192 /// Prints a three-letter-long name in the title case, reads the same name in any case.
193ShortMonthName,
194/// Full month names.
195 ///
196 /// Prints a full name in the title case, reads either a short or full name in any case.
197LongMonthName,
198/// Abbreviated day of the week names.
199 ///
200 /// Prints a three-letter-long name in the title case, reads the same name in any case.
201ShortWeekdayName,
202/// Full day of the week names.
203 ///
204 /// Prints a full name in the title case, reads either a short or full name in any case.
205LongWeekdayName,
206/// AM/PM.
207 ///
208 /// Prints in lower case, reads in any case.
209LowerAmPm,
210/// AM/PM.
211 ///
212 /// Prints in upper case, reads in any case.
213UpperAmPm,
214/// An optional dot plus one or more digits for left-aligned nanoseconds.
215 /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
216 /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
217Nanosecond,
218/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
219Nanosecond3,
220/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
221Nanosecond6,
222/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
223Nanosecond9,
224/// Timezone name.
225 ///
226 /// It does not support parsing, its use in the parser is an immediate failure.
227TimezoneName,
228/// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
229 ///
230 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
231 /// The offset is limited from `-24:00` to `+24:00`,
232 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
233TimezoneOffsetColon,
234/// Offset from the local time to UTC with seconds (`+09:00:00` or `-04:00:00` or `+00:00:00`).
235 ///
236 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
237 /// The offset is limited from `-24:00:00` to `+24:00:00`,
238 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
239TimezoneOffsetDoubleColon,
240/// Offset from the local time to UTC without minutes (`+09` or `-04` or `+00`).
241 ///
242 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
243 /// The offset is limited from `-24` to `+24`,
244 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
245TimezoneOffsetTripleColon,
246/// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
247 ///
248 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
249 /// and `Z` can be either in upper case or in lower case.
250 /// The offset is limited from `-24:00` to `+24:00`,
251 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
252TimezoneOffsetColonZ,
253/// Same as [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
254 /// Parsing allows an optional colon.
255TimezoneOffset,
256/// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
257 /// Parsing allows an optional colon.
258TimezoneOffsetZ,
259/// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
260RFC2822,
261/// RFC 3339 & ISO 8601 date and time syntax.
262RFC3339,
263264/// Internal uses only.
265 ///
266 /// This item exists so that one can add additional internal-only formatting
267 /// without breaking major compatibility (as enum variants cannot be selectively private).
268Internal(InternalFixed),
269}
270271/// An opaque type representing fixed-format item types for internal uses only.
272#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InternalFixed {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "InternalFixed",
"val", &&self.val)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InternalFixed {
#[inline]
fn clone(&self) -> InternalFixed {
InternalFixed { val: ::core::clone::Clone::clone(&self.val) }
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for InternalFixed {
#[inline]
fn eq(&self, other: &InternalFixed) -> bool { self.val == other.val }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InternalFixed {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<InternalInternal>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for InternalFixed {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.val, state)
}
}Hash)]
273#[cfg_attr(feature = "defmt", derive(defmt::Format))]
274pub struct InternalFixed {
275 val: InternalInternal,
276}
277278#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InternalInternal {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InternalInternal::TimezoneOffsetPermissive =>
"TimezoneOffsetPermissive",
InternalInternal::Nanosecond3NoDot => "Nanosecond3NoDot",
InternalInternal::Nanosecond6NoDot => "Nanosecond6NoDot",
InternalInternal::Nanosecond9NoDot => "Nanosecond9NoDot",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InternalInternal {
#[inline]
fn clone(&self) -> InternalInternal {
match self {
InternalInternal::TimezoneOffsetPermissive =>
InternalInternal::TimezoneOffsetPermissive,
InternalInternal::Nanosecond3NoDot =>
InternalInternal::Nanosecond3NoDot,
InternalInternal::Nanosecond6NoDot =>
InternalInternal::Nanosecond6NoDot,
InternalInternal::Nanosecond9NoDot =>
InternalInternal::Nanosecond9NoDot,
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for InternalInternal {
#[inline]
fn eq(&self, other: &InternalInternal) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InternalInternal {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for InternalInternal {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
279#[cfg_attr(feature = "defmt", derive(defmt::Format))]
280enum InternalInternal {
281/// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ), but
282 /// allows missing minutes (per [ISO 8601][iso8601]).
283 ///
284 /// # Panics
285 ///
286 /// If you try to use this for printing.
287 ///
288 /// [iso8601]: https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
289TimezoneOffsetPermissive,
290/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
291Nanosecond3NoDot,
292/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
293Nanosecond6NoDot,
294/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
295Nanosecond9NoDot,
296}
297298/// Type for specifying the format of UTC offsets.
299#[derive(#[automatically_derived]
impl ::core::fmt::Debug for OffsetFormat {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "OffsetFormat",
"precision", &self.precision, "colons", &self.colons,
"allow_zulu", &self.allow_zulu, "padding", &&self.padding)
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for OffsetFormat { }Copy, #[automatically_derived]
impl ::core::clone::Clone for OffsetFormat {
#[inline]
fn clone(&self) -> OffsetFormat {
let _: ::core::clone::AssertParamIsClone<OffsetPrecision>;
let _: ::core::clone::AssertParamIsClone<Colons>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Pad>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for OffsetFormat {
#[inline]
fn eq(&self, other: &OffsetFormat) -> bool {
self.allow_zulu == other.allow_zulu &&
self.precision == other.precision &&
self.colons == other.colons && self.padding == other.padding
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for OffsetFormat {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<OffsetPrecision>;
let _: ::core::cmp::AssertParamIsEq<Colons>;
let _: ::core::cmp::AssertParamIsEq<bool>;
let _: ::core::cmp::AssertParamIsEq<Pad>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for OffsetFormat {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.precision, state);
::core::hash::Hash::hash(&self.colons, state);
::core::hash::Hash::hash(&self.allow_zulu, state);
::core::hash::Hash::hash(&self.padding, state)
}
}Hash)]
300#[cfg_attr(feature = "defmt", derive(defmt::Format))]
301pub struct OffsetFormat {
302/// See `OffsetPrecision`.
303pub precision: OffsetPrecision,
304/// Separator between hours, minutes and seconds.
305pub colons: Colons,
306/// Represent `+00:00` as `Z`.
307pub allow_zulu: bool,
308/// Pad the hour value to two digits.
309pub padding: Pad,
310}
311312/// The precision of an offset from UTC formatting item.
313#[derive(#[automatically_derived]
impl ::core::fmt::Debug for OffsetPrecision {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OffsetPrecision::Hours => "Hours",
OffsetPrecision::Minutes => "Minutes",
OffsetPrecision::Seconds => "Seconds",
OffsetPrecision::OptionalMinutes => "OptionalMinutes",
OffsetPrecision::OptionalSeconds => "OptionalSeconds",
OffsetPrecision::OptionalMinutesAndSeconds =>
"OptionalMinutesAndSeconds",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for OffsetPrecision { }Copy, #[automatically_derived]
impl ::core::clone::Clone for OffsetPrecision {
#[inline]
fn clone(&self) -> OffsetPrecision { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for OffsetPrecision {
#[inline]
fn eq(&self, other: &OffsetPrecision) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for OffsetPrecision {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for OffsetPrecision {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
314#[cfg_attr(feature = "defmt", derive(defmt::Format))]
315pub enum OffsetPrecision {
316/// Format offset from UTC as only hours. Not recommended, it is not uncommon for timezones to
317 /// have an offset of 30 minutes, 15 minutes, etc.
318 /// Any minutes and seconds get truncated.
319Hours,
320/// Format offset from UTC as hours and minutes.
321 /// Any seconds will be rounded to the nearest minute.
322Minutes,
323/// Format offset from UTC as hours, minutes and seconds.
324Seconds,
325/// Format offset from UTC as hours, and optionally with minutes.
326 /// Any seconds will be rounded to the nearest minute.
327OptionalMinutes,
328/// Format offset from UTC as hours and minutes, and optionally seconds.
329OptionalSeconds,
330/// Format offset from UTC as hours and optionally minutes and seconds.
331OptionalMinutesAndSeconds,
332}
333334/// The separator between hours and minutes in an offset.
335#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Colons {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Colons::None => "None",
Colons::Colon => "Colon",
Colons::Maybe => "Maybe",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for Colons { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Colons {
#[inline]
fn clone(&self) -> Colons { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Colons {
#[inline]
fn eq(&self, other: &Colons) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Colons {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Colons {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
336#[cfg_attr(feature = "defmt", derive(defmt::Format))]
337pub enum Colons {
338/// No separator
339None,
340/// Colon (`:`) as separator
341Colon,
342/// No separator when formatting, colon allowed when parsing.
343Maybe,
344}
345346/// A single formatting item. This is used for both formatting and parsing.
347#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for Item<'a> {
#[inline]
fn clone(&self) -> Item<'a> {
match self {
Item::Literal(__self_0) =>
Item::Literal(::core::clone::Clone::clone(__self_0)),
Item::OwnedLiteral(__self_0) =>
Item::OwnedLiteral(::core::clone::Clone::clone(__self_0)),
Item::Space(__self_0) =>
Item::Space(::core::clone::Clone::clone(__self_0)),
Item::OwnedSpace(__self_0) =>
Item::OwnedSpace(::core::clone::Clone::clone(__self_0)),
Item::Numeric(__self_0, __self_1) =>
Item::Numeric(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Item::Fixed(__self_0) =>
Item::Fixed(::core::clone::Clone::clone(__self_0)),
Item::Error => Item::Error,
}
}
}Clone, #[automatically_derived]
impl<'a> ::core::cmp::PartialEq for Item<'a> {
#[inline]
fn eq(&self, other: &Item<'a>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Item::Literal(__self_0), Item::Literal(__arg1_0)) =>
__self_0 == __arg1_0,
(Item::OwnedLiteral(__self_0), Item::OwnedLiteral(__arg1_0))
=> __self_0 == __arg1_0,
(Item::Space(__self_0), Item::Space(__arg1_0)) =>
__self_0 == __arg1_0,
(Item::OwnedSpace(__self_0), Item::OwnedSpace(__arg1_0)) =>
__self_0 == __arg1_0,
(Item::Numeric(__self_0, __self_1),
Item::Numeric(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Item::Fixed(__self_0), Item::Fixed(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'a> ::core::cmp::Eq for Item<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<&'a str>;
let _: ::core::cmp::AssertParamIsEq<Box<str>>;
let _: ::core::cmp::AssertParamIsEq<&'a str>;
let _: ::core::cmp::AssertParamIsEq<Box<str>>;
let _: ::core::cmp::AssertParamIsEq<Numeric>;
let _: ::core::cmp::AssertParamIsEq<Pad>;
let _: ::core::cmp::AssertParamIsEq<Fixed>;
}
}Eq, #[automatically_derived]
impl<'a> ::core::fmt::Debug for Item<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Item::Literal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Literal", &__self_0),
Item::OwnedLiteral(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OwnedLiteral", &__self_0),
Item::Space(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Space",
&__self_0),
Item::OwnedSpace(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OwnedSpace", &__self_0),
Item::Numeric(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Numeric", __self_0, &__self_1),
Item::Fixed(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Fixed",
&__self_0),
Item::Error => ::core::fmt::Formatter::write_str(f, "Error"),
}
}
}Debug, #[automatically_derived]
impl<'a> ::core::hash::Hash for Item<'a> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
Item::Literal(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Item::OwnedLiteral(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Item::Space(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Item::OwnedSpace(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Item::Numeric(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
Item::Fixed(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash)]
348pub enum Item<'a> {
349/// A literally printed and parsed text.
350Literal(&'a str),
351/// Same as `Literal` but with the string owned by the item.
352#[cfg(feature = "alloc")]
353OwnedLiteral(Box<str>),
354/// Whitespace. Prints literally but reads zero or more whitespace.
355Space(&'a str),
356/// Same as `Space` but with the string owned by the item.
357#[cfg(feature = "alloc")]
358OwnedSpace(Box<str>),
359/// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
360 /// the parser simply ignores any padded whitespace and zeroes.
361Numeric(Numeric, Pad),
362/// Fixed-format item.
363Fixed(Fixed),
364/// Issues a formatting error. Used to signal an invalid format string.
365Error,
366}
367368#[cfg(feature = "defmt")]
369impl<'a> defmt::Format for Item<'a> {
370fn format(&self, f: defmt::Formatter) {
371match self {
372 Item::Literal(v) => defmt::write!(f, "Literal {{ {} }}", v),
373#[cfg(feature = "alloc")]
374Item::OwnedLiteral(_) => {}
375 Item::Space(v) => defmt::write!(f, "Space {{ {} }}", v),
376#[cfg(feature = "alloc")]
377Item::OwnedSpace(_) => {}
378 Item::Numeric(u, v) => defmt::write!(f, "Numeric {{ {}, {} }}", u, v),
379 Item::Fixed(v) => defmt::write!(f, "Fixed {{ {} }}", v),
380 Item::Error => defmt::write!(f, "Error"),
381 }
382 }
383}
384385const fn num(numeric: Numeric) -> Item<'static> {
386 Item::Numeric(numeric, Pad::None)
387}
388389const fn num0(numeric: Numeric) -> Item<'static> {
390 Item::Numeric(numeric, Pad::Zero)
391}
392393const fn nums(numeric: Numeric) -> Item<'static> {
394 Item::Numeric(numeric, Pad::Space)
395}
396397const fn fixed(fixed: Fixed) -> Item<'static> {
398 Item::Fixed(fixed)
399}
400401const fn internal_fixed(val: InternalInternal) -> Item<'static> {
402 Item::Fixed(Fixed::Internal(InternalFixed { val }))
403}
404405impl Item<'_> {
406/// Convert items that contain a reference to the format string into an owned variant.
407#[cfg(any(feature = "alloc", feature = "std"))]
408pub fn to_owned(self) -> Item<'static> {
409match self {
410 Item::Literal(s) => Item::OwnedLiteral(Box::from(s)),
411 Item::Space(s) => Item::OwnedSpace(Box::from(s)),
412 Item::Numeric(n, p) => Item::Numeric(n, p),
413 Item::Fixed(f) => Item::Fixed(f),
414 Item::OwnedLiteral(l) => Item::OwnedLiteral(l),
415 Item::OwnedSpace(s) => Item::OwnedSpace(s),
416 Item::Error => Item::Error,
417 }
418 }
419}
420421/// An error from the `parse` function.
422#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ParseError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "ParseError",
&&self.0)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ParseError {
#[inline]
fn clone(&self) -> ParseError {
let _: ::core::clone::AssertParamIsClone<ParseErrorKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ParseError {
#[inline]
fn eq(&self, other: &ParseError) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ParseError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ParseErrorKind>;
}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for ParseError { }Copy, #[automatically_derived]
impl ::core::hash::Hash for ParseError {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
423#[cfg_attr(feature = "defmt", derive(defmt::Format))]
424pub struct ParseError(ParseErrorKind);
425426impl ParseError {
427/// The category of parse error
428pub const fn kind(&self) -> ParseErrorKind {
429self.0
430}
431}
432433/// The category of parse error
434#[allow(clippy::manual_non_exhaustive)]
435#[derive(#[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::fmt::Debug for ParseErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ParseErrorKind::OutOfRange => "OutOfRange",
ParseErrorKind::Impossible => "Impossible",
ParseErrorKind::NotEnough => "NotEnough",
ParseErrorKind::Invalid => "Invalid",
ParseErrorKind::TooShort => "TooShort",
ParseErrorKind::TooLong => "TooLong",
ParseErrorKind::BadFormat => "BadFormat",
ParseErrorKind::__Nonexhaustive => "__Nonexhaustive",
})
}
}Debug, #[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::clone::Clone for ParseErrorKind {
#[inline]
fn clone(&self) -> ParseErrorKind { *self }
}Clone, #[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::cmp::PartialEq for ParseErrorKind {
#[inline]
fn eq(&self, other: &ParseErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::cmp::Eq for ParseErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::marker::Copy for ParseErrorKind { }Copy, #[automatically_derived]
#[allow(clippy::manual_non_exhaustive)]
impl ::core::hash::Hash for ParseErrorKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
436#[cfg_attr(feature = "defmt", derive(defmt::Format))]
437pub enum ParseErrorKind {
438/// Given field is out of permitted range.
439OutOfRange,
440441/// There is no possible date and time value with given set of fields.
442 ///
443 /// This does not include the out-of-range conditions, which are trivially invalid.
444 /// It includes the case that there are one or more fields that are inconsistent to each other.
445Impossible,
446447/// Given set of fields is not enough to make a requested date and time value.
448 ///
449 /// Note that there *may* be a case that given fields constrain the possible values so much
450 /// that there is a unique possible value. Chrono only tries to be correct for
451 /// most useful sets of fields however, as such constraint solving can be expensive.
452NotEnough,
453454/// The input string has some invalid character sequence for given formatting items.
455Invalid,
456457/// The input string has been prematurely ended.
458TooShort,
459460/// All formatting items have been read but there is a remaining input.
461TooLong,
462463/// There was an error on the formatting string, or there were non-supported formatting items.
464BadFormat,
465466// TODO: Change this to `#[non_exhaustive]` (on the enum) with the next breaking release.
467#[doc(hidden)]
468__Nonexhaustive,
469}
470471/// Same as `Result<T, ParseError>`.
472pub type ParseResult<T> = Result<T, ParseError>;
473474impl fmt::Displayfor ParseError {
475fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
476match self.0 {
477 ParseErrorKind::OutOfRange => f.write_fmt(format_args!("input is out of range"))write!(f, "input is out of range"),
478 ParseErrorKind::Impossible => f.write_fmt(format_args!("no possible date and time matching input"))write!(f, "no possible date and time matching input"),
479 ParseErrorKind::NotEnough => f.write_fmt(format_args!("input is not enough for unique date and time"))write!(f, "input is not enough for unique date and time"),
480 ParseErrorKind::Invalid => f.write_fmt(format_args!("input contains invalid characters"))write!(f, "input contains invalid characters"),
481 ParseErrorKind::TooShort => f.write_fmt(format_args!("premature end of input"))write!(f, "premature end of input"),
482 ParseErrorKind::TooLong => f.write_fmt(format_args!("trailing input"))write!(f, "trailing input"),
483 ParseErrorKind::BadFormat => f.write_fmt(format_args!("bad or unsupported format string"))write!(f, "bad or unsupported format string"),
484_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
485 }
486 }
487}
488489#[cfg(any(feature = "core-error", feature = "std"))]
490impl Errorfor ParseError {
491#[allow(deprecated)]
492fn description(&self) -> &str {
493"parser error, see to_string() for details"
494}
495}
496497// to be used in this module and submodules
498pub(crate) const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
499const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible);
500const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough);
501const INVALID: ParseError = ParseError(ParseErrorKind::Invalid);
502const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort);
503pub(crate) const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong);
504const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat);
505506// this implementation is here only because we need some private code from `scan`
507508/// Parsing a `str` into a `Weekday` uses the format [`%A`](./format/strftime/index.html).
509///
510/// # Example
511///
512/// ```
513/// use chrono::Weekday;
514///
515/// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
516/// assert!("any day".parse::<Weekday>().is_err());
517/// ```
518///
519/// The parsing is case-insensitive.
520///
521/// ```
522/// # use chrono::Weekday;
523/// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
524/// ```
525///
526/// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
527///
528/// ```
529/// # use chrono::Weekday;
530/// assert!("thurs".parse::<Weekday>().is_err());
531/// ```
532impl FromStrfor Weekday {
533type Err = ParseWeekdayError;
534535fn from_str(s: &str) -> Result<Self, Self::Err> {
536if let Ok(("", w)) = scan::short_or_long_weekday(s) {
537Ok(w)
538 } else {
539Err(ParseWeekdayError { _dummy: () })
540 }
541 }
542}
543544/// Parsing a `str` into a `Month` uses the format [`%B`](./format/strftime/index.html).
545///
546/// # Example
547///
548/// ```
549/// use chrono::Month;
550///
551/// assert_eq!("January".parse::<Month>(), Ok(Month::January));
552/// assert!("any day".parse::<Month>().is_err());
553/// ```
554///
555/// The parsing is case-insensitive.
556///
557/// ```
558/// # use chrono::Month;
559/// assert_eq!("fEbruARy".parse::<Month>(), Ok(Month::February));
560/// ```
561///
562/// Only the shortest form (e.g. `jan`) and the longest form (e.g. `january`) is accepted.
563///
564/// ```
565/// # use chrono::Month;
566/// assert!("septem".parse::<Month>().is_err());
567/// assert!("Augustin".parse::<Month>().is_err());
568/// ```
569impl FromStrfor Month {
570type Err = ParseMonthError;
571572fn from_str(s: &str) -> Result<Self, Self::Err> {
573if let Ok(("", w)) = scan::short_or_long_month0(s) {
574match w {
5750 => Ok(Month::January),
5761 => Ok(Month::February),
5772 => Ok(Month::March),
5783 => Ok(Month::April),
5794 => Ok(Month::May),
5805 => Ok(Month::June),
5816 => Ok(Month::July),
5827 => Ok(Month::August),
5838 => Ok(Month::September),
5849 => Ok(Month::October),
58510 => Ok(Month::November),
58611 => Ok(Month::December),
587_ => Err(ParseMonthError { _dummy: () }),
588 }
589 } else {
590Err(ParseMonthError { _dummy: () })
591 }
592 }
593}