/src/chrono/src/format/mod.rs
Line | Count | Source |
1 | | // This is a part of Chrono. |
2 | | // See README.md and LICENSE.txt for details. |
3 | | |
4 | | //! 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 | | //! ``` |
33 | | |
34 | | #[cfg(all(feature = "alloc", not(feature = "std"), not(test)))] |
35 | | use alloc::boxed::Box; |
36 | | #[cfg(all(feature = "core-error", not(feature = "std")))] |
37 | | use core::error::Error; |
38 | | use core::fmt; |
39 | | use core::str::FromStr; |
40 | | #[cfg(feature = "std")] |
41 | | use std::error::Error; |
42 | | |
43 | | use crate::{Month, ParseMonthError, ParseWeekdayError, Weekday}; |
44 | | |
45 | | mod formatting; |
46 | | mod parsed; |
47 | | |
48 | | // due to the size of parsing routines, they are in separate modules. |
49 | | mod parse; |
50 | | pub(crate) mod scan; |
51 | | |
52 | | pub mod strftime; |
53 | | |
54 | | #[allow(unused)] |
55 | | // TODO: remove '#[allow(unused)]' once we use this module for parsing or something else that does |
56 | | // not require `alloc`. |
57 | | pub(crate) mod locales; |
58 | | |
59 | | pub use formatting::SecondsFormat; |
60 | | pub(crate) use formatting::write_hundreds; |
61 | | #[cfg(feature = "alloc")] |
62 | | pub(crate) use formatting::write_rfc2822; |
63 | | #[cfg(any(feature = "alloc", feature = "serde"))] |
64 | | pub(crate) use formatting::write_rfc3339; |
65 | | #[cfg(feature = "alloc")] |
66 | | #[allow(deprecated)] |
67 | | pub use formatting::{DelayedFormat, format, format_item}; |
68 | | #[cfg(feature = "unstable-locales")] |
69 | | pub use locales::Locale; |
70 | | pub(crate) use parse::parse_rfc3339; |
71 | | pub use parse::{parse, parse_and_remainder}; |
72 | | pub use parsed::Parsed; |
73 | | pub use strftime::StrftimeItems; |
74 | | |
75 | | /// An uninhabited type used for `InternalNumeric` and `InternalFixed` below. |
76 | | #[derive(Clone, PartialEq, Eq, Hash)] |
77 | | enum Void {} |
78 | | |
79 | | /// Padding characters for numeric items. |
80 | | #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] |
81 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
82 | | pub enum Pad { |
83 | | /// No padding. |
84 | | None, |
85 | | /// Zero (`0`) padding. |
86 | | Zero, |
87 | | /// Space padding. |
88 | | Space, |
89 | | } |
90 | | |
91 | | /// 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(Clone, PartialEq, Eq, Debug, Hash)] |
106 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
107 | | pub enum Numeric { |
108 | | /// Full Gregorian year (FW=4, PW=∞). |
109 | | /// May accept years before 1 BCE or after 9999 CE, given an initial sign (+/-). |
110 | | Year, |
111 | | /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year. |
112 | | YearDiv100, |
113 | | /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative. |
114 | | YearMod100, |
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. |
117 | | IsoYear, |
118 | | /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year. |
119 | | IsoYearDiv100, |
120 | | /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative. |
121 | | IsoYearMod100, |
122 | | /// Quarter (FW=PW=1). |
123 | | Quarter, |
124 | | /// Month (FW=PW=2). |
125 | | Month, |
126 | | /// Day of the month (FW=PW=2). |
127 | | Day, |
128 | | /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2). |
129 | | WeekFromSun, |
130 | | /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2). |
131 | | WeekFromMon, |
132 | | /// Week number in the ISO week date (FW=PW=2). |
133 | | IsoWeek, |
134 | | /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1). |
135 | | NumDaysFromSun, |
136 | | /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1). |
137 | | WeekdayFromMon, |
138 | | /// Day of the year (FW=PW=3). |
139 | | Ordinal, |
140 | | /// Hour number in the 24-hour clocks (FW=PW=2). |
141 | | Hour, |
142 | | /// Hour number in the 12-hour clocks (FW=PW=2). |
143 | | Hour12, |
144 | | /// The number of minutes since the last whole hour (FW=PW=2). |
145 | | Minute, |
146 | | /// The number of seconds since the last whole minute (FW=PW=2). |
147 | | Second, |
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). |
151 | | Nanosecond, |
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. |
154 | | Timestamp, |
155 | | |
156 | | /// 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). |
160 | | Internal(InternalNumeric), |
161 | | } |
162 | | |
163 | | /// An opaque type representing numeric item types for internal uses only. |
164 | | #[derive(Clone, Eq, Hash, PartialEq)] |
165 | | pub struct InternalNumeric { |
166 | | _dummy: Void, |
167 | | } |
168 | | |
169 | | impl fmt::Debug for InternalNumeric { |
170 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
171 | 0 | write!(f, "<InternalNumeric>") |
172 | 0 | } |
173 | | } |
174 | | |
175 | | #[cfg(feature = "defmt")] |
176 | | impl defmt::Format for InternalNumeric { |
177 | | fn format(&self, f: defmt::Formatter) { |
178 | | defmt::write!(f, "<InternalNumeric>") |
179 | | } |
180 | | } |
181 | | |
182 | | /// 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(Clone, PartialEq, Eq, Debug, Hash)] |
188 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
189 | | pub 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. |
193 | | ShortMonthName, |
194 | | /// Full month names. |
195 | | /// |
196 | | /// Prints a full name in the title case, reads either a short or full name in any case. |
197 | | LongMonthName, |
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. |
201 | | ShortWeekdayName, |
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. |
205 | | LongWeekdayName, |
206 | | /// AM/PM. |
207 | | /// |
208 | | /// Prints in lower case, reads in any case. |
209 | | LowerAmPm, |
210 | | /// AM/PM. |
211 | | /// |
212 | | /// Prints in upper case, reads in any case. |
213 | | UpperAmPm, |
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). |
217 | | Nanosecond, |
218 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3. |
219 | | Nanosecond3, |
220 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6. |
221 | | Nanosecond6, |
222 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9. |
223 | | Nanosecond9, |
224 | | /// Timezone name. |
225 | | /// |
226 | | /// It does not support parsing, its use in the parser is an immediate failure. |
227 | | TimezoneName, |
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. |
233 | | TimezoneOffsetColon, |
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. |
239 | | TimezoneOffsetDoubleColon, |
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. |
245 | | TimezoneOffsetTripleColon, |
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. |
252 | | TimezoneOffsetColonZ, |
253 | | /// Same as [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon. |
254 | | /// Parsing allows an optional colon. |
255 | | TimezoneOffset, |
256 | | /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon. |
257 | | /// Parsing allows an optional colon. |
258 | | TimezoneOffsetZ, |
259 | | /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time. |
260 | | RFC2822, |
261 | | /// RFC 3339 & ISO 8601 date and time syntax. |
262 | | RFC3339, |
263 | | |
264 | | /// 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). |
268 | | Internal(InternalFixed), |
269 | | } |
270 | | |
271 | | /// An opaque type representing fixed-format item types for internal uses only. |
272 | | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
273 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
274 | | pub struct InternalFixed { |
275 | | val: InternalInternal, |
276 | | } |
277 | | |
278 | | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
279 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
280 | | enum 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 |
289 | | TimezoneOffsetPermissive, |
290 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot. |
291 | | Nanosecond3NoDot, |
292 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot. |
293 | | Nanosecond6NoDot, |
294 | | /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot. |
295 | | Nanosecond9NoDot, |
296 | | } |
297 | | |
298 | | /// Type for specifying the format of UTC offsets. |
299 | | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
300 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
301 | | pub struct OffsetFormat { |
302 | | /// See `OffsetPrecision`. |
303 | | pub precision: OffsetPrecision, |
304 | | /// Separator between hours, minutes and seconds. |
305 | | pub colons: Colons, |
306 | | /// Represent `+00:00` as `Z`. |
307 | | pub allow_zulu: bool, |
308 | | /// Pad the hour value to two digits. |
309 | | pub padding: Pad, |
310 | | } |
311 | | |
312 | | /// The precision of an offset from UTC formatting item. |
313 | | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
314 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
315 | | pub 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. |
319 | | Hours, |
320 | | /// Format offset from UTC as hours and minutes. |
321 | | /// Any seconds will be rounded to the nearest minute. |
322 | | Minutes, |
323 | | /// Format offset from UTC as hours, minutes and seconds. |
324 | | Seconds, |
325 | | /// Format offset from UTC as hours, and optionally with minutes. |
326 | | /// Any seconds will be rounded to the nearest minute. |
327 | | OptionalMinutes, |
328 | | /// Format offset from UTC as hours and minutes, and optionally seconds. |
329 | | OptionalSeconds, |
330 | | /// Format offset from UTC as hours and optionally minutes and seconds. |
331 | | OptionalMinutesAndSeconds, |
332 | | } |
333 | | |
334 | | /// The separator between hours and minutes in an offset. |
335 | | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
336 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
337 | | pub enum Colons { |
338 | | /// No separator |
339 | | None, |
340 | | /// Colon (`:`) as separator |
341 | | Colon, |
342 | | /// No separator when formatting, colon allowed when parsing. |
343 | | Maybe, |
344 | | } |
345 | | |
346 | | /// A single formatting item. This is used for both formatting and parsing. |
347 | | #[derive(Clone, PartialEq, Eq, Debug, Hash)] |
348 | | pub enum Item<'a> { |
349 | | /// A literally printed and parsed text. |
350 | | Literal(&'a str), |
351 | | /// Same as `Literal` but with the string owned by the item. |
352 | | #[cfg(feature = "alloc")] |
353 | | OwnedLiteral(Box<str>), |
354 | | /// Whitespace. Prints literally but reads zero or more whitespace. |
355 | | Space(&'a str), |
356 | | /// Same as `Space` but with the string owned by the item. |
357 | | #[cfg(feature = "alloc")] |
358 | | OwnedSpace(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. |
361 | | Numeric(Numeric, Pad), |
362 | | /// Fixed-format item. |
363 | | Fixed(Fixed), |
364 | | /// Issues a formatting error. Used to signal an invalid format string. |
365 | | Error, |
366 | | } |
367 | | |
368 | | #[cfg(feature = "defmt")] |
369 | | impl<'a> defmt::Format for Item<'a> { |
370 | | fn format(&self, f: defmt::Formatter) { |
371 | | match self { |
372 | | Item::Literal(v) => defmt::write!(f, "Literal {{ {} }}", v), |
373 | | #[cfg(feature = "alloc")] |
374 | | Item::OwnedLiteral(_) => {} |
375 | | Item::Space(v) => defmt::write!(f, "Space {{ {} }}", v), |
376 | | #[cfg(feature = "alloc")] |
377 | | Item::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 | | } |
384 | | |
385 | 3.72k | const fn num(numeric: Numeric) -> Item<'static> { |
386 | 3.72k | Item::Numeric(numeric, Pad::None) |
387 | 3.72k | } |
388 | | |
389 | 12.2k | const fn num0(numeric: Numeric) -> Item<'static> { |
390 | 12.2k | Item::Numeric(numeric, Pad::Zero) |
391 | 12.2k | } |
392 | | |
393 | 1.01k | const fn nums(numeric: Numeric) -> Item<'static> { |
394 | 1.01k | Item::Numeric(numeric, Pad::Space) |
395 | 1.01k | } |
396 | | |
397 | 31.6k | const fn fixed(fixed: Fixed) -> Item<'static> { |
398 | 31.6k | Item::Fixed(fixed) |
399 | 31.6k | } |
400 | | |
401 | 3.18k | const fn internal_fixed(val: InternalInternal) -> Item<'static> { |
402 | 3.18k | Item::Fixed(Fixed::Internal(InternalFixed { val })) |
403 | 3.18k | } |
404 | | |
405 | | impl Item<'_> { |
406 | | /// Convert items that contain a reference to the format string into an owned variant. |
407 | | #[cfg(any(feature = "alloc", feature = "std"))] |
408 | 0 | pub fn to_owned(self) -> Item<'static> { |
409 | 0 | match self { |
410 | 0 | Item::Literal(s) => Item::OwnedLiteral(Box::from(s)), |
411 | 0 | Item::Space(s) => Item::OwnedSpace(Box::from(s)), |
412 | 0 | Item::Numeric(n, p) => Item::Numeric(n, p), |
413 | 0 | Item::Fixed(f) => Item::Fixed(f), |
414 | 0 | Item::OwnedLiteral(l) => Item::OwnedLiteral(l), |
415 | 0 | Item::OwnedSpace(s) => Item::OwnedSpace(s), |
416 | 0 | Item::Error => Item::Error, |
417 | | } |
418 | 0 | } |
419 | | } |
420 | | |
421 | | /// An error from the `parse` function. |
422 | | #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] |
423 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
424 | | pub struct ParseError(ParseErrorKind); |
425 | | |
426 | | impl ParseError { |
427 | | /// The category of parse error |
428 | 0 | pub const fn kind(&self) -> ParseErrorKind { |
429 | 0 | self.0 |
430 | 0 | } |
431 | | } |
432 | | |
433 | | /// The category of parse error |
434 | | #[allow(clippy::manual_non_exhaustive)] |
435 | | #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] |
436 | | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
437 | | pub enum ParseErrorKind { |
438 | | /// Given field is out of permitted range. |
439 | | OutOfRange, |
440 | | |
441 | | /// 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. |
445 | | Impossible, |
446 | | |
447 | | /// 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. |
452 | | NotEnough, |
453 | | |
454 | | /// The input string has some invalid character sequence for given formatting items. |
455 | | Invalid, |
456 | | |
457 | | /// The input string has been prematurely ended. |
458 | | TooShort, |
459 | | |
460 | | /// All formatting items have been read but there is a remaining input. |
461 | | TooLong, |
462 | | |
463 | | /// There was an error on the formatting string, or there were non-supported formatting items. |
464 | | BadFormat, |
465 | | |
466 | | // TODO: Change this to `#[non_exhaustive]` (on the enum) with the next breaking release. |
467 | | #[doc(hidden)] |
468 | | __Nonexhaustive, |
469 | | } |
470 | | |
471 | | /// Same as `Result<T, ParseError>`. |
472 | | pub type ParseResult<T> = Result<T, ParseError>; |
473 | | |
474 | | impl fmt::Display for ParseError { |
475 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
476 | 0 | match self.0 { |
477 | 0 | ParseErrorKind::OutOfRange => write!(f, "input is out of range"), |
478 | 0 | ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"), |
479 | 0 | ParseErrorKind::NotEnough => write!(f, "input is not enough for unique date and time"), |
480 | 0 | ParseErrorKind::Invalid => write!(f, "input contains invalid characters"), |
481 | 0 | ParseErrorKind::TooShort => write!(f, "premature end of input"), |
482 | 0 | ParseErrorKind::TooLong => write!(f, "trailing input"), |
483 | 0 | ParseErrorKind::BadFormat => write!(f, "bad or unsupported format string"), |
484 | 0 | _ => unreachable!(), |
485 | | } |
486 | 0 | } |
487 | | } |
488 | | |
489 | | #[cfg(any(feature = "core-error", feature = "std"))] |
490 | | impl Error for ParseError { |
491 | | #[allow(deprecated)] |
492 | 0 | fn description(&self) -> &str { |
493 | 0 | "parser error, see to_string() for details" |
494 | 0 | } |
495 | | } |
496 | | |
497 | | // to be used in this module and submodules |
498 | | pub(crate) const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange); |
499 | | const IMPOSSIBLE: ParseError = ParseError(ParseErrorKind::Impossible); |
500 | | const NOT_ENOUGH: ParseError = ParseError(ParseErrorKind::NotEnough); |
501 | | const INVALID: ParseError = ParseError(ParseErrorKind::Invalid); |
502 | | const TOO_SHORT: ParseError = ParseError(ParseErrorKind::TooShort); |
503 | | pub(crate) const TOO_LONG: ParseError = ParseError(ParseErrorKind::TooLong); |
504 | | const BAD_FORMAT: ParseError = ParseError(ParseErrorKind::BadFormat); |
505 | | |
506 | | // this implementation is here only because we need some private code from `scan` |
507 | | |
508 | | /// 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 | | /// ``` |
532 | | impl FromStr for Weekday { |
533 | | type Err = ParseWeekdayError; |
534 | | |
535 | 0 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
536 | 0 | if let Ok(("", w)) = scan::short_or_long_weekday(s) { |
537 | 0 | Ok(w) |
538 | | } else { |
539 | 0 | Err(ParseWeekdayError { _dummy: () }) |
540 | | } |
541 | 0 | } |
542 | | } |
543 | | |
544 | | /// 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 | | /// ``` |
569 | | impl FromStr for Month { |
570 | | type Err = ParseMonthError; |
571 | | |
572 | | fn from_str(s: &str) -> Result<Self, Self::Err> { |
573 | | if let Ok(("", w)) = scan::short_or_long_month0(s) { |
574 | | match w { |
575 | | 0 => Ok(Month::January), |
576 | | 1 => Ok(Month::February), |
577 | | 2 => Ok(Month::March), |
578 | | 3 => Ok(Month::April), |
579 | | 4 => Ok(Month::May), |
580 | | 5 => Ok(Month::June), |
581 | | 6 => Ok(Month::July), |
582 | | 7 => Ok(Month::August), |
583 | | 8 => Ok(Month::September), |
584 | | 9 => Ok(Month::October), |
585 | | 10 => Ok(Month::November), |
586 | | 11 => Ok(Month::December), |
587 | | _ => Err(ParseMonthError { _dummy: () }), |
588 | | } |
589 | | } else { |
590 | | Err(ParseMonthError { _dummy: () }) |
591 | | } |
592 | | } |
593 | | } |