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)]
81pub enum Pad {
82/// No padding.
83None,
84/// Zero (`0`) padding.
85Zero,
86/// Space padding.
87Space,
88}
8990/// Numeric item types.
91/// They have associated formatting width (FW) and parsing width (PW).
92///
93/// The **formatting width** is the minimal width to be formatted.
94/// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
95/// then it is left-padded.
96/// If the number is too long or (in some cases) negative, it is printed as is.
97///
98/// The **parsing width** is the maximal width to be scanned.
99/// The parser only tries to consume from one to given number of digits (greedily).
100/// It also trims the preceding whitespace if any.
101/// It cannot parse the negative number, so some date and time cannot be formatted then
102/// parsed with the same formatting items.
103#[non_exhaustive]
104#[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)]
105pub enum Numeric {
106/// Full Gregorian year (FW=4, PW=∞).
107 /// May accept years before 1 BCE or after 9999 CE, given an initial sign (+/-).
108Year,
109/// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
110YearDiv100,
111/// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
112YearMod100,
113/// Year in the ISO week date (FW=4, PW=∞).
114 /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
115IsoYear,
116/// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
117IsoYearDiv100,
118/// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
119IsoYearMod100,
120/// Quarter (FW=PW=1).
121Quarter,
122/// Month (FW=PW=2).
123Month,
124/// Day of the month (FW=PW=2).
125Day,
126/// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
127WeekFromSun,
128/// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
129WeekFromMon,
130/// Week number in the ISO week date (FW=PW=2).
131IsoWeek,
132/// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
133NumDaysFromSun,
134/// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
135WeekdayFromMon,
136/// Day of the year (FW=PW=3).
137Ordinal,
138/// Hour number in the 24-hour clocks (FW=PW=2).
139Hour,
140/// Hour number in the 12-hour clocks (FW=PW=2).
141Hour12,
142/// The number of minutes since the last whole hour (FW=PW=2).
143Minute,
144/// The number of seconds since the last whole minute (FW=PW=2).
145Second,
146/// The number of nanoseconds since the last whole second (FW=PW=9).
147 /// Note that this is *not* left-aligned;
148 /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
149Nanosecond,
150/// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
151 /// For formatting, it assumes UTC upon the absence of time zone offset.
152Timestamp,
153154/// Internal uses only.
155 ///
156 /// This item exists so that one can add additional internal-only formatting
157 /// without breaking major compatibility (as enum variants cannot be selectively private).
158Internal(InternalNumeric),
159}
160161/// An opaque type representing numeric item types for internal uses only.
162#[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)]
163pub struct InternalNumeric {
164 _dummy: Void,
165}
166167impl fmt::Debugfor InternalNumeric {
168fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169f.write_fmt(format_args!("<InternalNumeric>"))write!(f, "<InternalNumeric>")170 }
171}
172173/// Fixed-format item types.
174///
175/// They have their own rules of formatting and parsing.
176/// Otherwise noted, they print in the specified cases but parse case-insensitively.
177#[non_exhaustive]
178#[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)]
179pub enum Fixed {
180/// Abbreviated month names.
181 ///
182 /// Prints a three-letter-long name in the title case, reads the same name in any case.
183ShortMonthName,
184/// Full month names.
185 ///
186 /// Prints a full name in the title case, reads either a short or full name in any case.
187LongMonthName,
188/// Abbreviated day of the week names.
189 ///
190 /// Prints a three-letter-long name in the title case, reads the same name in any case.
191ShortWeekdayName,
192/// Full day of the week names.
193 ///
194 /// Prints a full name in the title case, reads either a short or full name in any case.
195LongWeekdayName,
196/// AM/PM.
197 ///
198 /// Prints in lower case, reads in any case.
199LowerAmPm,
200/// AM/PM.
201 ///
202 /// Prints in upper case, reads in any case.
203UpperAmPm,
204/// An optional dot plus one or more digits for left-aligned nanoseconds.
205 /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
206 /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
207Nanosecond,
208/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
209Nanosecond3,
210/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
211Nanosecond6,
212/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
213Nanosecond9,
214/// Timezone name.
215 ///
216 /// It does not support parsing, its use in the parser is an immediate failure.
217TimezoneName,
218/// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
219 ///
220 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
221 /// The offset is limited from `-24:00` to `+24:00`,
222 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
223TimezoneOffsetColon,
224/// Offset from the local time to UTC with seconds (`+09:00:00` or `-04:00:00` or `+00:00:00`).
225 ///
226 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
227 /// The offset is limited from `-24:00:00` to `+24:00:00`,
228 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
229TimezoneOffsetDoubleColon,
230/// Offset from the local time to UTC without minutes (`+09` or `-04` or `+00`).
231 ///
232 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
233 /// The offset is limited from `-24` to `+24`,
234 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
235TimezoneOffsetTripleColon,
236/// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
237 ///
238 /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
239 /// and `Z` can be either in upper case or in lower case.
240 /// The offset is limited from `-24:00` to `+24:00`,
241 /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
242TimezoneOffsetColonZ,
243/// Same as [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
244 /// Parsing allows an optional colon.
245TimezoneOffset,
246/// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
247 /// Parsing allows an optional colon.
248TimezoneOffsetZ,
249/// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
250RFC2822,
251/// RFC 3339 & ISO 8601 date and time syntax.
252RFC3339,
253254/// Internal uses only.
255 ///
256 /// This item exists so that one can add additional internal-only formatting
257 /// without breaking major compatibility (as enum variants cannot be selectively private).
258Internal(InternalFixed),
259}
260261/// An opaque type representing fixed-format item types for internal uses only.
262#[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)]
263pub struct InternalFixed {
264 val: InternalInternal,
265}
266267#[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)]
268enum InternalInternal {
269/// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ), but
270 /// allows missing minutes (per [ISO 8601][iso8601]).
271 ///
272 /// # Panics
273 ///
274 /// If you try to use this for printing.
275 ///
276 /// [iso8601]: https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
277TimezoneOffsetPermissive,
278/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
279Nanosecond3NoDot,
280/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
281Nanosecond6NoDot,
282/// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
283Nanosecond9NoDot,
284}
285286/// Type for specifying the format of UTC offsets.
287#[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)]
288pub struct OffsetFormat {
289/// See `OffsetPrecision`.
290pub precision: OffsetPrecision,
291/// Separator between hours, minutes and seconds.
292pub colons: Colons,
293/// Represent `+00:00` as `Z`.
294pub allow_zulu: bool,
295/// Pad the hour value to two digits.
296pub padding: Pad,
297}
298299/// The precision of an offset from UTC formatting item.
300#[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)]
301pub enum OffsetPrecision {
302/// Format offset from UTC as only hours. Not recommended, it is not uncommon for timezones to
303 /// have an offset of 30 minutes, 15 minutes, etc.
304 /// Any minutes and seconds get truncated.
305Hours,
306/// Format offset from UTC as hours and minutes.
307 /// Any seconds will be rounded to the nearest minute.
308Minutes,
309/// Format offset from UTC as hours, minutes and seconds.
310Seconds,
311/// Format offset from UTC as hours, and optionally with minutes.
312 /// Any seconds will be rounded to the nearest minute.
313OptionalMinutes,
314/// Format offset from UTC as hours and minutes, and optionally seconds.
315OptionalSeconds,
316/// Format offset from UTC as hours and optionally minutes and seconds.
317OptionalMinutesAndSeconds,
318}
319320/// The separator between hours and minutes in an offset.
321#[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)]
322pub enum Colons {
323/// No separator
324None,
325/// Colon (`:`) as separator
326Colon,
327/// No separator when formatting, colon allowed when parsing.
328Maybe,
329}
330331/// A single formatting item. This is used for both formatting and parsing.
332#[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)]
333pub enum Item<'a> {
334/// A literally printed and parsed text.
335Literal(&'a str),
336/// Same as `Literal` but with the string owned by the item.
337#[cfg(feature = "alloc")]
338OwnedLiteral(Box<str>),
339/// Whitespace. Prints literally but reads zero or more whitespace.
340Space(&'a str),
341/// Same as `Space` but with the string owned by the item.
342#[cfg(feature = "alloc")]
343OwnedSpace(Box<str>),
344/// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
345 /// the parser simply ignores any padded whitespace and zeroes.
346Numeric(Numeric, Pad),
347/// Fixed-format item.
348Fixed(Fixed),
349/// Issues a formatting error. Used to signal an invalid format string.
350Error,
351}
352353const fn num(numeric: Numeric) -> Item<'static> {
354 Item::Numeric(numeric, Pad::None)
355}
356357const fn num0(numeric: Numeric) -> Item<'static> {
358 Item::Numeric(numeric, Pad::Zero)
359}
360361const fn nums(numeric: Numeric) -> Item<'static> {
362 Item::Numeric(numeric, Pad::Space)
363}
364365const fn fixed(fixed: Fixed) -> Item<'static> {
366 Item::Fixed(fixed)
367}
368369const fn internal_fixed(val: InternalInternal) -> Item<'static> {
370 Item::Fixed(Fixed::Internal(InternalFixed { val }))
371}
372373impl Item<'_> {
374/// Convert items that contain a reference to the format string into an owned variant.
375#[cfg(any(feature = "alloc", feature = "std"))]
376pub fn to_owned(self) -> Item<'static> {
377match self{
378 Item::Literal(s) => Item::OwnedLiteral(Box::from(s)),
379 Item::Space(s) => Item::OwnedSpace(Box::from(s)),
380 Item::Numeric(n, p) => Item::Numeric(n, p),
381 Item::Fixed(f) => Item::Fixed(f),
382 Item::OwnedLiteral(l) => Item::OwnedLiteral(l),
383 Item::OwnedSpace(s) => Item::OwnedSpace(s),
384 Item::Error => Item::Error,
385 }
386 }
387}
388389/// An error from the `parse` function.
390#[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)]
391pub struct ParseError(ParseErrorKind);
392393impl ParseError {
394/// The category of parse error
395pub const fn kind(&self) -> ParseErrorKind {
396self.0
397}
398}
399400/// The category of parse error
401#[allow(clippy::manual_non_exhaustive)]
402#[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)]
403pub enum ParseErrorKind {
404/// Given field is out of permitted range.
405OutOfRange,
406407/// There is no possible date and time value with given set of fields.
408 ///
409 /// This does not include the out-of-range conditions, which are trivially invalid.
410 /// It includes the case that there are one or more fields that are inconsistent to each other.
411Impossible,
412413/// Given set of fields is not enough to make a requested date and time value.
414 ///
415 /// Note that there *may* be a case that given fields constrain the possible values so much
416 /// that there is a unique possible value. Chrono only tries to be correct for
417 /// most useful sets of fields however, as such constraint solving can be expensive.
418NotEnough,
419420/// The input string has some invalid character sequence for given formatting items.
421Invalid,
422423/// The input string has been prematurely ended.
424TooShort,
425426/// All formatting items have been read but there is a remaining input.
427TooLong,
428429/// There was an error on the formatting string, or there were non-supported formatting items.
430BadFormat,
431432// TODO: Change this to `#[non_exhaustive]` (on the enum) with the next breaking release.
433#[doc(hidden)]
434__Nonexhaustive,
435}
436437/// Same as `Result<T, ParseError>`.
438pub type ParseResult<T> = Result<T, ParseError>;
439440impl fmt::Displayfor ParseError {
441fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
442match self.0 {
443 ParseErrorKind::OutOfRange => f.write_fmt(format_args!("input is out of range"))write!(f, "input is out of range"),
444 ParseErrorKind::Impossible => f.write_fmt(format_args!("no possible date and time matching input"))write!(f, "no possible date and time matching input"),
445 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"),
446 ParseErrorKind::Invalid => f.write_fmt(format_args!("input contains invalid characters"))write!(f, "input contains invalid characters"),
447 ParseErrorKind::TooShort => f.write_fmt(format_args!("premature end of input"))write!(f, "premature end of input"),
448 ParseErrorKind::TooLong => f.write_fmt(format_args!("trailing input"))write!(f, "trailing input"),
449 ParseErrorKind::BadFormat => f.write_fmt(format_args!("bad or unsupported format string"))write!(f, "bad or unsupported format string"),
450_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
451 }
452 }
453}
454455#[cfg(any(feature = "core-error", feature = "std"))]
456impl Errorfor ParseError {
457#[allow(deprecated)]
458fn description(&self) -> &str {
459"parser error, see to_string() for details"
460}
461}
462463// to be used in this module and submodules
464pub(crate) const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
465const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible);
466const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough);
467const INVALID: ParseError = ParseError(ParseErrorKind::Invalid);
468const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort);
469pub(crate) const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong);
470const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat);
471472// this implementation is here only because we need some private code from `scan`
473474/// Parsing a `str` into a `Weekday` uses the format [`%A`](./format/strftime/index.html).
475///
476/// # Example
477///
478/// ```
479/// use chrono::Weekday;
480///
481/// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
482/// assert!("any day".parse::<Weekday>().is_err());
483/// ```
484///
485/// The parsing is case-insensitive.
486///
487/// ```
488/// # use chrono::Weekday;
489/// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
490/// ```
491///
492/// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
493///
494/// ```
495/// # use chrono::Weekday;
496/// assert!("thurs".parse::<Weekday>().is_err());
497/// ```
498impl FromStrfor Weekday {
499type Err = ParseWeekdayError;
500501fn from_str(s: &str) -> Result<Self, Self::Err> {
502if let Ok(("", w)) = scan::short_or_long_weekday(s) {
503Ok(w)
504 } else {
505Err(ParseWeekdayError { _dummy: () })
506 }
507 }
508}
509510/// Parsing a `str` into a `Month` uses the format [`%B`](./format/strftime/index.html).
511///
512/// # Example
513///
514/// ```
515/// use chrono::Month;
516///
517/// assert_eq!("January".parse::<Month>(), Ok(Month::January));
518/// assert!("any day".parse::<Month>().is_err());
519/// ```
520///
521/// The parsing is case-insensitive.
522///
523/// ```
524/// # use chrono::Month;
525/// assert_eq!("fEbruARy".parse::<Month>(), Ok(Month::February));
526/// ```
527///
528/// Only the shortest form (e.g. `jan`) and the longest form (e.g. `january`) is accepted.
529///
530/// ```
531/// # use chrono::Month;
532/// assert!("septem".parse::<Month>().is_err());
533/// assert!("Augustin".parse::<Month>().is_err());
534/// ```
535impl FromStrfor Month {
536type Err = ParseMonthError;
537538fn from_str(s: &str) -> Result<Self, Self::Err> {
539if let Ok(("", w)) = scan::short_or_long_month0(s) {
540match w {
5410 => Ok(Month::January),
5421 => Ok(Month::February),
5432 => Ok(Month::March),
5443 => Ok(Month::April),
5454 => Ok(Month::May),
5465 => Ok(Month::June),
5476 => Ok(Month::July),
5487 => Ok(Month::August),
5498 => Ok(Month::September),
5509 => Ok(Month::October),
55110 => Ok(Month::November),
55211 => Ok(Month::December),
553_ => Err(ParseMonthError { _dummy: () }),
554 }
555 } else {
556Err(ParseMonthError { _dummy: () })
557 }
558 }
559}