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 [one built-in syntax closely resembling
16 //! C's `strftime` format](./strftime/index.html).
17 
18 #![allow(ellipsis_inclusive_range_patterns)]
19 
20 use core::borrow::Borrow;
21 use core::fmt;
22 use core::str::FromStr;
23 #[cfg(any(feature = "std", test))]
24 use std::error::Error;
25 #[cfg(feature = "alloc")]
26 use alloc::boxed::Box;
27 #[cfg(feature = "alloc")]
28 use alloc::string::{String, ToString};
29 
30 #[cfg(any(feature = "alloc", feature = "std", test))]
31 use {Datelike, Timelike};
32 use {Weekday, ParseWeekdayError};
33 #[cfg(any(feature = "alloc", feature = "std", test))]
34 use div::{div_floor, mod_floor};
35 #[cfg(any(feature = "alloc", feature = "std", test))]
36 use offset::{Offset, FixedOffset};
37 #[cfg(any(feature = "alloc", feature = "std", test))]
38 use naive::{NaiveDate, NaiveTime};
39 
40 pub use self::strftime::StrftimeItems;
41 pub use self::parsed::Parsed;
42 pub use self::parse::parse;
43 
44 /// An uninhabited type used for `InternalNumeric` and `InternalFixed` below.
45 #[derive(Clone, PartialEq, Eq)]
46 enum Void {}
47 
48 /// Padding characters for numeric items.
49 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
50 pub enum Pad {
51     /// No padding.
52     None,
53     /// Zero (`0`) padding.
54     Zero,
55     /// Space padding.
56     Space,
57 }
58 
59 /// Numeric item types.
60 /// They have associated formatting width (FW) and parsing width (PW).
61 ///
62 /// The **formatting width** is the minimal width to be formatted.
63 /// If the number is too short, and the padding is not [`Pad::None`](./enum.Pad.html#variant.None),
64 /// then it is left-padded.
65 /// If the number is too long or (in some cases) negative, it is printed as is.
66 ///
67 /// The **parsing width** is the maximal width to be scanned.
68 /// The parser only tries to consume from one to given number of digits (greedily).
69 /// It also trims the preceding whitespace if any.
70 /// It cannot parse the negative number, so some date and time cannot be formatted then
71 /// parsed with the same formatting items.
72 #[derive(Clone, PartialEq, Eq, Debug)]
73 pub enum Numeric {
74     /// Full Gregorian year (FW=4, PW=∞).
75     /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
76     Year,
77     /// Gregorian year divided by 100 (century number; FW=PW=2). Implies the non-negative year.
78     YearDiv100,
79     /// Gregorian year modulo 100 (FW=PW=2). Cannot be negative.
80     YearMod100,
81     /// Year in the ISO week date (FW=4, PW=∞).
82     /// May accept years before 1 BCE or after 9999 CE, given an initial sign.
83     IsoYear,
84     /// Year in the ISO week date, divided by 100 (FW=PW=2). Implies the non-negative year.
85     IsoYearDiv100,
86     /// Year in the ISO week date, modulo 100 (FW=PW=2). Cannot be negative.
87     IsoYearMod100,
88     /// Month (FW=PW=2).
89     Month,
90     /// Day of the month (FW=PW=2).
91     Day,
92     /// Week number, where the week 1 starts at the first Sunday of January (FW=PW=2).
93     WeekFromSun,
94     /// Week number, where the week 1 starts at the first Monday of January (FW=PW=2).
95     WeekFromMon,
96     /// Week number in the ISO week date (FW=PW=2).
97     IsoWeek,
98     /// Day of the week, where Sunday = 0 and Saturday = 6 (FW=PW=1).
99     NumDaysFromSun,
100     /// Day of the week, where Monday = 1 and Sunday = 7 (FW=PW=1).
101     WeekdayFromMon,
102     /// Day of the year (FW=PW=3).
103     Ordinal,
104     /// Hour number in the 24-hour clocks (FW=PW=2).
105     Hour,
106     /// Hour number in the 12-hour clocks (FW=PW=2).
107     Hour12,
108     /// The number of minutes since the last whole hour (FW=PW=2).
109     Minute,
110     /// The number of seconds since the last whole minute (FW=PW=2).
111     Second,
112     /// The number of nanoseconds since the last whole second (FW=PW=9).
113     /// Note that this is *not* left-aligned;
114     /// see also [`Fixed::Nanosecond`](./enum.Fixed.html#variant.Nanosecond).
115     Nanosecond,
116     /// The number of non-leap seconds since the midnight UTC on January 1, 1970 (FW=1, PW=∞).
117     /// For formatting, it assumes UTC upon the absence of time zone offset.
118     Timestamp,
119 
120     /// Internal uses only.
121     ///
122     /// This item exists so that one can add additional internal-only formatting
123     /// without breaking major compatibility (as enum variants cannot be selectively private).
124     Internal(InternalNumeric),
125 }
126 
127 /// An opaque type representing numeric item types for internal uses only.
128 pub struct InternalNumeric {
129     _dummy: Void,
130 }
131 
132 impl Clone for InternalNumeric {
clone(&self) -> Self133     fn clone(&self) -> Self {
134         match self._dummy {}
135     }
136 }
137 
138 impl PartialEq for InternalNumeric {
eq(&self, _other: &InternalNumeric) -> bool139     fn eq(&self, _other: &InternalNumeric) -> bool {
140         match self._dummy {}
141     }
142 }
143 
144 impl Eq for InternalNumeric {
145 }
146 
147 impl fmt::Debug for InternalNumeric {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result148     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149         write!(f, "<InternalNumeric>")
150     }
151 }
152 
153 /// Fixed-format item types.
154 ///
155 /// They have their own rules of formatting and parsing.
156 /// Otherwise noted, they print in the specified cases but parse case-insensitively.
157 #[derive(Clone, PartialEq, Eq, Debug)]
158 pub enum Fixed {
159     /// Abbreviated month names.
160     ///
161     /// Prints a three-letter-long name in the title case, reads the same name in any case.
162     ShortMonthName,
163     /// Full month names.
164     ///
165     /// Prints a full name in the title case, reads either a short or full name in any case.
166     LongMonthName,
167     /// Abbreviated day of the week names.
168     ///
169     /// Prints a three-letter-long name in the title case, reads the same name in any case.
170     ShortWeekdayName,
171     /// Full day of the week names.
172     ///
173     /// Prints a full name in the title case, reads either a short or full name in any case.
174     LongWeekdayName,
175     /// AM/PM.
176     ///
177     /// Prints in lower case, reads in any case.
178     LowerAmPm,
179     /// AM/PM.
180     ///
181     /// Prints in upper case, reads in any case.
182     UpperAmPm,
183     /// An optional dot plus one or more digits for left-aligned nanoseconds.
184     /// May print nothing, 3, 6 or 9 digits according to the available accuracy.
185     /// See also [`Numeric::Nanosecond`](./enum.Numeric.html#variant.Nanosecond).
186     Nanosecond,
187     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3.
188     Nanosecond3,
189     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6.
190     Nanosecond6,
191     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9.
192     Nanosecond9,
193     /// Timezone name.
194     ///
195     /// It does not support parsing, its use in the parser is an immediate failure.
196     TimezoneName,
197     /// Offset from the local time to UTC (`+09:00` or `-04:00` or `+00:00`).
198     ///
199     /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace.
200     /// The offset is limited from `-24:00` to `+24:00`,
201     /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
202     TimezoneOffsetColon,
203     /// Offset from the local time to UTC (`+09:00` or `-04:00` or `Z`).
204     ///
205     /// In the parser, the colon can be omitted and/or surrounded with any amount of whitespace,
206     /// and `Z` can be either in upper case or in lower case.
207     /// The offset is limited from `-24:00` to `+24:00`,
208     /// which is the same as [`FixedOffset`](../offset/struct.FixedOffset.html)'s range.
209     TimezoneOffsetColonZ,
210     /// Same as [`TimezoneOffsetColon`](#variant.TimezoneOffsetColon) but prints no colon.
211     /// Parsing allows an optional colon.
212     TimezoneOffset,
213     /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ) but prints no colon.
214     /// Parsing allows an optional colon.
215     TimezoneOffsetZ,
216     /// RFC 2822 date and time syntax. Commonly used for email and MIME date and time.
217     RFC2822,
218     /// RFC 3339 & ISO 8601 date and time syntax.
219     RFC3339,
220 
221     /// Internal uses only.
222     ///
223     /// This item exists so that one can add additional internal-only formatting
224     /// without breaking major compatibility (as enum variants cannot be selectively private).
225     Internal(InternalFixed),
226 }
227 
228 /// An opaque type representing fixed-format item types for internal uses only.
229 #[derive(Debug, Clone, PartialEq, Eq)]
230 pub struct InternalFixed {
231     val: InternalInternal,
232 }
233 
234 #[derive(Debug, Clone, PartialEq, Eq)]
235 enum InternalInternal {
236     /// Same as [`TimezoneOffsetColonZ`](#variant.TimezoneOffsetColonZ), but
237     /// allows missing minutes (per [ISO 8601][iso8601]).
238     ///
239     /// # Panics
240     ///
241     /// If you try to use this for printing.
242     ///
243     /// [iso8601]: https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
244     TimezoneOffsetPermissive,
245     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 3 and there is no leading dot.
246     Nanosecond3NoDot,
247     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 6 and there is no leading dot.
248     Nanosecond6NoDot,
249     /// Same as [`Nanosecond`](#variant.Nanosecond) but the accuracy is fixed to 9 and there is no leading dot.
250     Nanosecond9NoDot,
251 }
252 
253 /// A single formatting item. This is used for both formatting and parsing.
254 #[derive(Clone, PartialEq, Eq, Debug)]
255 pub enum Item<'a> {
256     /// A literally printed and parsed text.
257     Literal(&'a str),
258     /// Same as `Literal` but with the string owned by the item.
259     #[cfg(any(feature = "alloc", feature = "std", test))]
260     OwnedLiteral(Box<str>),
261     /// Whitespace. Prints literally but reads zero or more whitespace.
262     Space(&'a str),
263     /// Same as `Space` but with the string owned by the item.
264     #[cfg(any(feature = "alloc", feature = "std", test))]
265     OwnedSpace(Box<str>),
266     /// Numeric item. Can be optionally padded to the maximal length (if any) when formatting;
267     /// the parser simply ignores any padded whitespace and zeroes.
268     Numeric(Numeric, Pad),
269     /// Fixed-format item.
270     Fixed(Fixed),
271     /// Issues a formatting error. Used to signal an invalid format string.
272     Error,
273 }
274 
275 macro_rules! lit  { ($x:expr) => (Item::Literal($x)) }
276 macro_rules! sp   { ($x:expr) => (Item::Space($x)) }
277 macro_rules! num  { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::None)) }
278 macro_rules! num0 { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Zero)) }
279 macro_rules! nums { ($x:ident) => (Item::Numeric(Numeric::$x, Pad::Space)) }
280 macro_rules! fix  { ($x:ident) => (Item::Fixed(Fixed::$x)) }
281 macro_rules! internal_fix { ($x:ident) => (Item::Fixed(Fixed::Internal(InternalFixed { val: InternalInternal::$x })))}
282 
283 /// An error from the `parse` function.
284 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
285 pub struct ParseError(ParseErrorKind);
286 
287 /// The category of parse error
288 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
289 enum ParseErrorKind {
290     /// Given field is out of permitted range.
291     OutOfRange,
292 
293     /// There is no possible date and time value with given set of fields.
294     ///
295     /// This does not include the out-of-range conditions, which are trivially invalid.
296     /// It includes the case that there are one or more fields that are inconsistent to each other.
297     Impossible,
298 
299     /// Given set of fields is not enough to make a requested date and time value.
300     ///
301     /// Note that there *may* be a case that given fields constrain the possible values so much
302     /// that there is a unique possible value. Chrono only tries to be correct for
303     /// most useful sets of fields however, as such constraint solving can be expensive.
304     NotEnough,
305 
306     /// The input string has some invalid character sequence for given formatting items.
307     Invalid,
308 
309     /// The input string has been prematurely ended.
310     TooShort,
311 
312     /// All formatting items have been read but there is a remaining input.
313     TooLong,
314 
315     /// There was an error on the formatting string, or there were non-supported formating items.
316     BadFormat,
317 }
318 
319 /// Same as `Result<T, ParseError>`.
320 pub type ParseResult<T> = Result<T, ParseError>;
321 
322 impl fmt::Display for ParseError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result323     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324         match self.0 {
325             ParseErrorKind::OutOfRange => write!(f, "input is out of range"),
326             ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"),
327             ParseErrorKind::NotEnough => write!(f, "input is not enough for unique date and time"),
328             ParseErrorKind::Invalid => write!(f, "input contains invalid characters"),
329             ParseErrorKind::TooShort => write!(f, "premature end of input"),
330             ParseErrorKind::TooLong => write!(f, "trailing input"),
331             ParseErrorKind::BadFormat => write!(f, "bad or unsupported format string"),
332         }
333     }
334 }
335 
336 #[cfg(any(feature = "std", test))]
337 impl Error for ParseError {
338     #[allow(deprecated)]
description(&self) -> &str339     fn description(&self) -> &str {
340         "parser error, see to_string() for details"
341     }
342 }
343 
344 // to be used in this module and submodules
345 const OUT_OF_RANGE: ParseError = ParseError(ParseErrorKind::OutOfRange);
346 const IMPOSSIBLE:   ParseError = ParseError(ParseErrorKind::Impossible);
347 const NOT_ENOUGH:   ParseError = ParseError(ParseErrorKind::NotEnough);
348 const INVALID:      ParseError = ParseError(ParseErrorKind::Invalid);
349 const TOO_SHORT:    ParseError = ParseError(ParseErrorKind::TooShort);
350 const TOO_LONG:     ParseError = ParseError(ParseErrorKind::TooLong);
351 const BAD_FORMAT:   ParseError = ParseError(ParseErrorKind::BadFormat);
352 
353 /// Tries to format given arguments with given formatting items.
354 /// Internally used by `DelayedFormat`.
355 #[cfg(any(feature = "alloc", feature = "std", test))]
format<'a, I, B>( w: &mut fmt::Formatter, date: Option<&NaiveDate>, time: Option<&NaiveTime>, off: Option<&(String, FixedOffset)>, items: I, ) -> fmt::Result where I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>356 pub fn format<'a, I, B>(
357     w: &mut fmt::Formatter,
358     date: Option<&NaiveDate>,
359     time: Option<&NaiveTime>,
360     off: Option<&(String, FixedOffset)>,
361     items: I,
362 ) -> fmt::Result
363     where I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>
364 {
365     // full and abbreviated month and weekday names
366     static SHORT_MONTHS: [&'static str; 12] =
367         ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
368     static LONG_MONTHS: [&'static str; 12] =
369         ["January", "February", "March", "April", "May", "June",
370          "July", "August", "September", "October", "November", "December"];
371     static SHORT_WEEKDAYS: [&'static str; 7] =
372         ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
373     static LONG_WEEKDAYS: [&'static str; 7] =
374         ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
375 
376     use core::fmt::Write;
377     let mut result = String::new();
378 
379     for item in items {
380         match item.borrow() {
381             &Item::Literal(s) | &Item::Space(s) => result.push_str(s),
382             #[cfg(any(feature = "alloc", feature = "std", test))]
383             &Item::OwnedLiteral(ref s) | &Item::OwnedSpace(ref s) => result.push_str(s),
384 
385             &Item::Numeric(ref spec, ref pad) => {
386                 use self::Numeric::*;
387 
388                 let week_from_sun = |d: &NaiveDate|
389                     (d.ordinal() as i32 - d.weekday().num_days_from_sunday() as i32 + 7) / 7;
390                 let week_from_mon = |d: &NaiveDate|
391                     (d.ordinal() as i32 - d.weekday().num_days_from_monday() as i32 + 7) / 7;
392 
393                 let (width, v) = match spec {
394                     &Year           => (4, date.map(|d| i64::from(d.year()))),
395                     &YearDiv100     => (2, date.map(|d| div_floor(i64::from(d.year()), 100))),
396                     &YearMod100     => (2, date.map(|d| mod_floor(i64::from(d.year()), 100))),
397                     &IsoYear        => (4, date.map(|d| i64::from(d.iso_week().year()))),
398                     &IsoYearDiv100  => (2, date.map(|d| div_floor(
399                         i64::from(d.iso_week().year()), 100))),
400                     &IsoYearMod100  => (2, date.map(|d| mod_floor(
401                         i64::from(d.iso_week().year()), 100))),
402                     &Month          => (2, date.map(|d| i64::from(d.month()))),
403                     &Day            => (2, date.map(|d| i64::from(d.day()))),
404                     &WeekFromSun    => (2, date.map(|d| i64::from(week_from_sun(d)))),
405                     &WeekFromMon    => (2, date.map(|d| i64::from(week_from_mon(d)))),
406                     &IsoWeek        => (2, date.map(|d| i64::from(d.iso_week().week()))),
407                     &NumDaysFromSun => (1, date.map(|d| i64::from(d.weekday()
408                                                                   .num_days_from_sunday()))),
409                     &WeekdayFromMon => (1, date.map(|d| i64::from(d.weekday()
410                                                                   .number_from_monday()))),
411                     &Ordinal        => (3, date.map(|d| i64::from(d.ordinal()))),
412                     &Hour           => (2, time.map(|t| i64::from(t.hour()))),
413                     &Hour12         => (2, time.map(|t| i64::from(t.hour12().1))),
414                     &Minute         => (2, time.map(|t| i64::from(t.minute()))),
415                     &Second         => (2, time.map(|t| i64::from(t.second() +
416                                                         t.nanosecond() / 1_000_000_000))),
417                     &Nanosecond     => (9, time.map(|t| i64::from(t.nanosecond() % 1_000_000_000))),
418                     &Timestamp      => (1, match (date, time, off) {
419                         (Some(d), Some(t), None) =>
420                             Some(d.and_time(*t).timestamp()),
421                         (Some(d), Some(t), Some(&(_, off))) =>
422                             Some((d.and_time(*t) - off).timestamp()),
423                         (_, _, _) => None
424                     }),
425 
426                     // for the future expansion
427                     &Internal(ref int) => match int._dummy {},
428                 };
429 
430 
431                 if let Some(v) = v {
432                     if (spec == &Year || spec == &IsoYear) && !(0 <= v && v < 10_000) {
433                         // non-four-digit years require an explicit sign as per ISO 8601
434                         match pad {
435                             &Pad::None => write!(result, "{:+}", v),
436                             &Pad::Zero => write!(result, "{:+01$}", v, width + 1),
437                             &Pad::Space => write!(result, "{:+1$}", v, width + 1),
438                         }
439                     } else {
440                         match pad {
441                             &Pad::None => write!(result, "{}", v),
442                             &Pad::Zero => write!(result, "{:01$}", v, width),
443                             &Pad::Space => write!(result, "{:1$}", v, width),
444                         }
445                     }?
446                 } else {
447                     return Err(fmt::Error) // insufficient arguments for given format
448                 }
449             },
450 
451             &Item::Fixed(ref spec) => {
452                 use self::Fixed::*;
453 
454                 /// Prints an offset from UTC in the format of `+HHMM` or `+HH:MM`.
455                 /// `Z` instead of `+00[:]00` is allowed when `allow_zulu` is true.
456                 fn write_local_minus_utc(
457                     result: &mut String,
458                     off: FixedOffset,
459                     allow_zulu: bool,
460                     use_colon: bool,
461                 ) -> fmt::Result {
462                     let off = off.local_minus_utc();
463                     if !allow_zulu || off != 0 {
464                         let (sign, off) = if off < 0 {('-', -off)} else {('+', off)};
465                         if use_colon {
466                             write!(result, "{}{:02}:{:02}", sign, off / 3600, off / 60 % 60)
467                         } else {
468                             write!(result, "{}{:02}{:02}", sign, off / 3600, off / 60 % 60)
469                         }
470                     } else {
471                         result.push_str("Z");
472                         Ok(())
473                     }
474                 }
475 
476                 let ret = match spec {
477                     &ShortMonthName =>
478                         date.map(|d| {
479                             result.push_str(SHORT_MONTHS[d.month0() as usize]);
480                             Ok(())
481                         }),
482                     &LongMonthName =>
483                         date.map(|d| {
484                             result.push_str(LONG_MONTHS[d.month0() as usize]);
485                             Ok(())
486                         }),
487                     &ShortWeekdayName =>
488                         date.map(|d| {
489                             result.push_str(
490                                 SHORT_WEEKDAYS[d.weekday().num_days_from_monday() as usize]
491                             );
492                             Ok(())
493                         }),
494                     &LongWeekdayName =>
495                         date.map(|d| {
496                             result.push_str(
497                                 LONG_WEEKDAYS[d.weekday().num_days_from_monday() as usize]
498                             );
499                             Ok(())
500                         }),
501                     &LowerAmPm =>
502                         time.map(|t| {
503                             result.push_str(if t.hour12().0 {"pm"} else {"am"});
504                             Ok(())
505                         }),
506                     &UpperAmPm =>
507                         time.map(|t| {
508                             result.push_str(if t.hour12().0 {"PM"} else {"AM"});
509                             Ok(())
510                         }),
511                     &Nanosecond =>
512                         time.map(|t| {
513                             let nano = t.nanosecond() % 1_000_000_000;
514                             if nano == 0 {
515                                 Ok(())
516                             } else if nano % 1_000_000 == 0 {
517                                 write!(result, ".{:03}", nano / 1_000_000)
518                             } else if nano % 1_000 == 0 {
519                                 write!(result, ".{:06}", nano / 1_000)
520                             } else {
521                                 write!(result, ".{:09}", nano)
522                             }
523                         }),
524                     &Nanosecond3 =>
525                         time.map(|t| {
526                             let nano = t.nanosecond() % 1_000_000_000;
527                             write!(result, ".{:03}", nano / 1_000_000)
528                         }),
529                     &Nanosecond6 =>
530                         time.map(|t| {
531                             let nano = t.nanosecond() % 1_000_000_000;
532                             write!(result, ".{:06}", nano / 1_000)
533                         }),
534                     &Nanosecond9 =>
535                         time.map(|t| {
536                             let nano = t.nanosecond() % 1_000_000_000;
537                             write!(result, ".{:09}", nano)
538                         }),
539                     &Internal(InternalFixed { val: InternalInternal::Nanosecond3NoDot }) =>
540                         time.map(|t| {
541                             let nano = t.nanosecond() % 1_000_000_000;
542                             write!(result, "{:03}", nano / 1_000_000)
543                         }),
544                     &Internal(InternalFixed { val: InternalInternal::Nanosecond6NoDot }) =>
545                         time.map(|t| {
546                             let nano = t.nanosecond() % 1_000_000_000;
547                             write!(result, "{:06}", nano / 1_000)
548                         }),
549                     &Internal(InternalFixed { val: InternalInternal::Nanosecond9NoDot }) =>
550                         time.map(|t| {
551                             let nano = t.nanosecond() % 1_000_000_000;
552                             write!(result, "{:09}", nano)
553                         }),
554                     &TimezoneName =>
555                         off.map(|&(ref name, _)| {
556                             result.push_str(name);
557                             Ok(())
558                         }),
559                     &TimezoneOffsetColon =>
560                         off.map(|&(_, off)| write_local_minus_utc(&mut result, off, false, true)),
561                     &TimezoneOffsetColonZ =>
562                         off.map(|&(_, off)| write_local_minus_utc(&mut result, off, true, true)),
563                     &TimezoneOffset =>
564                         off.map(|&(_, off)| write_local_minus_utc(&mut result, off, false, false)),
565                     &TimezoneOffsetZ =>
566                         off.map(|&(_, off)| write_local_minus_utc(&mut result, off, true, false)),
567                     &Internal(InternalFixed { val: InternalInternal::TimezoneOffsetPermissive }) =>
568                         panic!("Do not try to write %#z it is undefined"),
569                     &RFC2822 => // same as `%a, %e %b %Y %H:%M:%S %z`
570                         if let (Some(d), Some(t), Some(&(_, off))) = (date, time, off) {
571                             let sec = t.second() + t.nanosecond() / 1_000_000_000;
572                             write!(
573                                 result,
574                                 "{}, {:02} {} {:04} {:02}:{:02}:{:02} ",
575                                 SHORT_WEEKDAYS[d.weekday().num_days_from_monday() as usize],
576                                 d.day(), SHORT_MONTHS[d.month0() as usize], d.year(),
577                                 t.hour(), t.minute(), sec
578                             )?;
579                             Some(write_local_minus_utc(&mut result, off, false, false))
580                         } else {
581                             None
582                         },
583                     &RFC3339 => // same as `%Y-%m-%dT%H:%M:%S%.f%:z`
584                         if let (Some(d), Some(t), Some(&(_, off))) = (date, time, off) {
585                             // reuse `Debug` impls which already print ISO 8601 format.
586                             // this is faster in this way.
587                             write!(result, "{:?}T{:?}", d, t)?;
588                             Some(write_local_minus_utc(&mut result, off, false, true))
589                         } else {
590                             None
591                         },
592                 };
593 
594                 match ret {
595                     Some(ret) => ret?,
596                     None => return Err(fmt::Error), // insufficient arguments for given format
597                 }
598             },
599 
600             &Item::Error => return Err(fmt::Error),
601         }
602     }
603 
604     w.pad(&result)
605 }
606 
607 mod parsed;
608 
609 // due to the size of parsing routines, they are in separate modules.
610 mod scan;
611 mod parse;
612 
613 pub mod strftime;
614 
615 /// A *temporary* object which can be used as an argument to `format!` or others.
616 /// This is normally constructed via `format` methods of each date and time type.
617 #[cfg(any(feature = "alloc", feature = "std", test))]
618 #[derive(Debug)]
619 pub struct DelayedFormat<I> {
620     /// The date view, if any.
621     date: Option<NaiveDate>,
622     /// The time view, if any.
623     time: Option<NaiveTime>,
624     /// The name and local-to-UTC difference for the offset (timezone), if any.
625     off: Option<(String, FixedOffset)>,
626     /// An iterator returning formatting items.
627     items: I,
628 }
629 
630 #[cfg(any(feature = "alloc", feature = "std", test))]
631 impl<'a, I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>> DelayedFormat<I> {
632     /// Makes a new `DelayedFormat` value out of local date and time.
new(date: Option<NaiveDate>, time: Option<NaiveTime>, items: I) -> DelayedFormat<I>633     pub fn new(date: Option<NaiveDate>, time: Option<NaiveTime>, items: I) -> DelayedFormat<I> {
634         DelayedFormat { date: date, time: time, off: None, items: items }
635     }
636 
637     /// Makes a new `DelayedFormat` value out of local date and time and UTC offset.
new_with_offset<Off>(date: Option<NaiveDate>, time: Option<NaiveTime>, offset: &Off, items: I) -> DelayedFormat<I> where Off: Offset + fmt::Display638     pub fn new_with_offset<Off>(date: Option<NaiveDate>, time: Option<NaiveTime>,
639                                 offset: &Off, items: I) -> DelayedFormat<I>
640             where Off: Offset + fmt::Display {
641         let name_and_diff = (offset.to_string(), offset.fix());
642         DelayedFormat { date: date, time: time, off: Some(name_and_diff), items: items }
643     }
644 }
645 
646 #[cfg(any(feature = "alloc", feature = "std", test))]
647 impl<'a, I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>>> fmt::Display for DelayedFormat<I> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result648     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
649         format(f, self.date.as_ref(), self.time.as_ref(), self.off.as_ref(), self.items.clone())
650     }
651 }
652 
653 // this implementation is here only because we need some private code from `scan`
654 
655 /// Parsing a `str` into a `Weekday` uses the format [`%W`](./format/strftime/index.html).
656 ///
657 /// # Example
658 ///
659 /// ~~~~
660 /// use chrono::Weekday;
661 ///
662 /// assert_eq!("Sunday".parse::<Weekday>(), Ok(Weekday::Sun));
663 /// assert!("any day".parse::<Weekday>().is_err());
664 /// ~~~~
665 ///
666 /// The parsing is case-insensitive.
667 ///
668 /// ~~~~
669 /// # use chrono::Weekday;
670 /// assert_eq!("mON".parse::<Weekday>(), Ok(Weekday::Mon));
671 /// ~~~~
672 ///
673 /// Only the shortest form (e.g. `sun`) and the longest form (e.g. `sunday`) is accepted.
674 ///
675 /// ~~~~
676 /// # use chrono::Weekday;
677 /// assert!("thurs".parse::<Weekday>().is_err());
678 /// ~~~~
679 impl FromStr for Weekday {
680     type Err = ParseWeekdayError;
681 
from_str(s: &str) -> Result<Self, Self::Err>682     fn from_str(s: &str) -> Result<Self, Self::Err> {
683         if let Ok(("", w)) = scan::short_or_long_weekday(s) {
684             Ok(w)
685         } else {
686             Err(ParseWeekdayError { _dummy: () })
687         }
688     }
689 }
690