Debian Codegraph @

debian/rust-vendor/jiff/src/tz/zic.rs

raw
1 /*!
2 !!!!! THIS FILE IS NOT CURRENTLY INCLUDED IN JIFF !!!!!
3
4 WIP: I have dreams of providing a time zone database that could be backed by
5 tzdb's plain text files (which are the input to the `zic` TZif compiler).
6 But while I got as far as writing a complete parser for the format, actually
7 turning the data into something that can be used as a `TimeZone` has proven
8 quite difficult. I've read the code in `zic.c` quite a bit, but it's
9 essentially inscrutable. I think I could probably port it, but the problem is
10 that it's designed to convert these data types into a TZif file, where as I'd
11 more like to use them directly to implement the `TimeZone` methods. Howard
12 Hinnant's `tz` C++ library does this, but its implementation is quite tortured
13 as well.
14
15 The main complexity here is that in order to interpret any given AT field
16 (including a Zone's UNTIL field), you need to resolve any previous rules
17 in order to compute the correct SAVE offset. That's because AT (and UNTIL)
18 fields can be in "wall," "standard" or "universal" time, with "wall" being the
19 default and most common. In "wall" time, you need to know the right offset to
20 apply.
21
22 This seems also especially precarious for dealing with ambiguous (gaps & folds)
23 times. What happens when they straddle a Zone boundary for example?
24
25 My thinking here is that the right way to move forward is the following:
26
27 * A zic-backed time zone database would be a `ZicP` internally.
28 * When a specific time zone is requested, an in-memory TZif data type is
29 generated for just that time zone. We don't need to generate the TZif binary
30 data, but rather, use the `crate::tz::iana::binary::Tzif` data type directly.
31 * This includes generating POSIX TZ strings for future datetimes (which is
32 apparently not always possible since zic data is more expressive than what
33 POSIX TZ strings can represent).
34
35 If we can do that, then we're home free because `Tzif` does everything we want.
36 I think this is probably the right approach for the following reasons:
37
38 1. The zic format is clearly designed for this particular usage scenario.
39 So we'd be doing something for which there is known working (albeit in
40 inscrubtable C) code that accomplishes the same goal.
41 2. Time zone lookups would be much faster. That is, even if we figured out how
42 to adapt the zic data types below to do time zone lookups, they are likely
43 going to involve more overhead than what Tzif does. And if we were to try
44 and speed them up, it's likely we'd just wind up converging to the Tzif data
45 type anyway.
46
47 Basically, we need to write our own zic compiler to make this work. I decided
48 this was beyond the scope of what I wanted to do for the initial Jiff release,
49 so I abandoned this approach.
50
51 Also, why even bother with the plain text zic files in the first place? Well,
52 it's nice for a couple reasons:
53
54 1. It's a fair bit smaller than the full collection of binary files. Somewhere
55 around half the size.
56 2. They can be concatenated into one giant text file. And indeed, on some Unix
57 systems, `/usr/share/zoneinfo/tzdata.zi` is the complete database in plain
58 text format.
59 3. The plain text version has "links," which lets one determine the aliases for
60 various time zones. Although it seems like `backward` would help, it isn't
61 always included in `/usr/share/zoneinfo`. And, well, `tzdata.zi` isn't either,
62 for example, on macOS.
63
64 -----
65
66 This module provides support for zic plain text files from the [Time Zone
67 Database].
68
69 These text files are used by tzdb's `zic` compiler to produce the binary
70 TZif files commonly found in the `/usr/share/zoneinfo` directory of Unix
71 systems. The text files are sometimes found in the same directory. For example,
72 `/usr/share/zoneinfo/tzdata.zi` is a single file on my Archlinux system that
73 contains the entire set of time zones from tzdb. But my macOS system does not
74 have this file.
75
76 Generally speaking, the main benefit of the text file is that it is much
77 smaller. The entirety of tzdb can fit into a single 100KB zic file, where as
78 the corresponding binary data is at least 10 times as big. Moreover, the zic
79 files contain symbolic links between time zones such that it's possible to
80 determine whether two time zones are distinct or not.
81
82 The main down side of the zic formatted files is that they don't contain
83 pre-computed instants and are generally more complex to deal with. This in turn
84 means that offset lookups for both instants and civil datetimes are typically
85 slower than for a TZif backed time zone.
86
87 Note that the format parsed here is described in `man zic`.
88
89 # Organization
90
91 Types ending with `P` (for "parsed") are meant to be a structured
92 representation of the data from the zic file. The data at this point is
93 validated as much as possible, but it does not include all validation. For
94 example, a `ZoneFirstP` with a named reference to a set of rules that does not
95 exist is perfectly fine. But conversion to higher level non-`P` types will fail
96 in such cases.
97
98 [Time Zone Database]: https://www.iana.org/time-zones
99 */
100
101 #![allow(dead_code)]
102
103 use core::{ops::RangeInclusive, str::FromStr};
104
105 use alloc::{
106 collections::BTreeMap,
107 string::{String, ToString},
108 vec,
109 vec::Vec,
110 };
111
112 use jcore::bounds::Sign;
113
114 use crate::{
115 civil::{Date, DateTime, Time, Weekday},
116 error::{
117 tz::zic::{Error as E, MAX_LINE_LEN},
118 Error, ErrorContext,
119 },
120 span::ToSpan,
121 timestamp::Timestamp,
122 tz::{Dst, Offset},
123 util::{b, parse, sync::Arc},
124 SignedDuration,
125 };
126
127 #[derive(Debug, Default, Eq, PartialEq)]
128 struct Zic {
129 zones: BTreeMap<String, Zone>,
130 links: BTreeMap<String, Zone>,
131 }
132
133 impl Zic {
134 fn new(_zicp: ZicP) -> Result<Zic, Error> {
135 todo!()
136 }
137 }
138
139 #[derive(Debug, Eq, PartialEq)]
140 struct TimeZone {
141 inner: Arc<TimeZoneInner>,
142 }
143
144 #[derive(Debug, Eq, PartialEq)]
145 struct TimeZoneInner {
146 /// The canonical name for a time zone, according to tzdb. There can only
147 /// be one of these, and it is the name with which the `Zone` line used.
148 name: String,
149 /// A list of zero or more aliases for this time zone created via `Link`
150 /// lines.
151 aliases: Vec<String>,
152 /// A sequence of one or more "zones" that make up this time zone. Each
153 /// zone is active until a certain point in time, at which some other zone
154 /// takes over. Each zone can reference a distinct set of rules, and thus
155 /// the specific zone to use for any given time dictates how DST is
156 /// computed for that time.
157 zones: Vec<Zone>,
158 }
159
160 #[derive(Debug, Eq, PartialEq)]
161 struct Zone {
162 /// The offset to add to UTC to get standard time for this time zone.
163 offset: Offset,
164 /// The rules for determining the offset from standard time to use for this
165 /// time zone.
166 rules: Rules,
167 /// The format to use when rendering a time zone abbreviation.
168 format: ZoneFormatP,
169 /// The timestamp until which this zone is active (exclusive).
170 until_timestamp: Timestamp,
171 /// The wall clock time until which this zone is active (exclusive).
172 until_wall: DateTime,
173 }
174
175 #[derive(Debug, Eq, PartialEq)]
176 struct Rules {
177 inner: Arc<RulesInner>,
178 }
179
180 #[derive(Debug, Eq, PartialEq)]
181 struct RulesInner {
182 name: String,
183 rules: Vec<Rule>,
184 }
185
186 impl Rules {
187 /// Create a single rule group from a set of parsed rules.
188 ///
189 /// This can also return an error if converting from the more flexible
190 /// parsed type to the more structured `Rule` fails in some way. For
191 /// example, if the SAVE field has an offset bigger (or smaller) than what
192 /// Jiff supports.
193 ///
194 /// # Panics
195 ///
196 /// Callers must ensure that the given group is non-empty and that every
197 /// rule in the group has the same name.
198 fn new(rulesp: Vec<RuleP>) -> Result<Rules, Error> {
199 assert!(!rulesp.is_empty(), "rule group must be non-empty");
200 let mut inner =
201 RulesInner { name: rulesp[0].name.name.clone(), rules: vec![] };
202 for r in rulesp {
203 assert_eq!(
204 inner.name, r.name.name,
205 "every name in rule group must be identical"
206 );
207 let dst = Dst::from(r.save.suffix() == RuleSaveSuffixP::Dst);
208 let offset = r.save.to_offset().with_context(|| {
209 E::FailedRule { name: inner.name.as_str().into() }
210 })?;
211 let years = r.years().with_context(|| E::FailedRule {
212 name: inner.name.as_str().into(),
213 })?;
214 let month = r.inn.month;
215 let letters = r.letters.part;
216 let day = r.on;
217 let at = r.at;
218 let rule = Rule { dst, offset, letters, years, month, day, at };
219 inner.rules.push(rule);
220 }
221 Ok(Rules { inner: Arc::new(inner) })
222 }
223 }
224
225 #[derive(Debug, Eq, PartialEq)]
226 struct Rule {
227 dst: Dst,
228 offset: Offset,
229 letters: String,
230 years: RangeInclusive<i16>,
231 month: i8,
232 day: RuleOnP,
233 at: RuleAtP,
234 }
235
236 /// A collection of parsed lines from zero or more zic input files.
237 #[derive(Debug, Default, Eq, PartialEq)]
238 struct ZicP {
239 rules: BTreeMap<String, Vec<RuleP>>,
240 zones: BTreeMap<String, ZoneP>,
241 links: BTreeMap<String, LinkP>,
242 }
243
244 impl ZicP {
245 /// Parse the zic data given into this zic value.
246 fn parse(&mut self, src: &str) -> Result<(), Error> {
247 self.parse_with_fields(FieldParser::new(src))
248 }
249
250 /// Parse the zic data given into this zic value. If the data given isn't
251 /// valid UTF-8, then this returns an error.
252 fn parse_bytes(&mut self, src: &[u8]) -> Result<(), Error> {
253 self.parse_with_fields(FieldParser::from_bytes(src)?)
254 }
255
256 /// Parse the zic data from the given field parser.
257 fn parse_with_fields(
258 &mut self,
259 mut parser: FieldParser<'_>,
260 ) -> Result<(), Error> {
261 while parser.read_next_fields()? {
262 self.parse_one(&mut parser)
263 .context(E::Line { number: parser.line_number })?;
264 }
265 if let Some(ref name) = parser.continuation_zone_for {
266 return Err(Error::from(E::ExpectedContinuationZoneLine {
267 name: name.as_str().into(),
268 }));
269 }
270 Ok(())
271 }
272
273 /// Parse a single line as a sequence of fields into this zic data.
274 fn parse_one(&mut self, p: &mut FieldParser<'_>) -> Result<(), Error> {
275 // Guaranteed by 'read_next_fields'
276 assert!(!p.fields.is_empty());
277
278 if let Some(name) = p.continuation_zone_for.take() {
279 let zone = ZoneContinuationP::parse(&p.fields)
280 .context(E::FailedContinuationZone)?;
281 let more_continuations = zone.until.is_some();
282 // OK because `p.continuation_zone_for` is only set when we have
283 // seen a first zone with the corresponding name.
284 self.zones.get_mut(&name).unwrap().continuations.push(zone);
285 // Update our parser state if we expect another continuation line.
286 if more_continuations {
287 p.continuation_zone_for = Some(name);
288 }
289 return Ok(());
290 }
291
292 let (first, rest) = (&p.fields[0], &p.fields[1..]);
293 if first.starts_with("R") && "Rule".starts_with(first) {
294 let rule = RuleP::parse(rest).context(E::FailedRuleLine)?;
295 let name = rule.name.name.clone();
296 self.rules.entry(name).or_default().push(rule);
297 } else if first.starts_with("Z") && "Zone".starts_with(first) {
298 let first = ZoneFirstP::parse(rest).context(E::FailedZoneFirst)?;
299 let name = first.name.name.clone();
300 if first.until.is_some() {
301 p.continuation_zone_for = Some(name.clone());
302 }
303 let zone = ZoneP { first, continuations: vec![] };
304 if self.links.contains_key(&name) {
305 return Err(Error::from(E::DuplicateZoneLink {
306 name: name.into(),
307 }));
308 }
309 if let Some(previous_zone) = self.zones.insert(name, zone) {
310 return Err(Error::from(E::DuplicateZone {
311 name: previous_zone.first.name.name.into(),
312 }));
313 }
314 } else if first.starts_with("L") && "Link".starts_with(first) {
315 let link = LinkP::parse(rest).context(E::FailedLinkLine)?;
316 let name = link.name.name.clone();
317 if self.zones.contains_key(&name) {
318 return Err(Error::from(E::DuplicateLinkZone {
319 name: name.into(),
320 }));
321 }
322 if let Some(previous_link) = self.links.insert(name, link) {
323 return Err(Error::from(E::DuplicateLink {
324 name: previous_link.name.name.into(),
325 }));
326 }
327 // N.B. We don't check that the link's target name refers to some
328 // other zone/link here, because the corresponding zone/link might
329 // be defined later.
330 } else {
331 return Err(Error::from(E::UnrecognizedZicLine)
332 .context(E::Line { number: p.line_number }));
333 }
334 Ok(())
335 }
336 }
337
338 /// A rule that determines when a particular amount of time should be added to
339 /// a zone's standard time.
340 #[derive(Clone, Debug, Eq, PartialEq)]
341 struct RuleP {
342 /// The name of this rule. The name can be referenced by zero or more
343 /// zones in their RULES field. It is guaranteed to be non-empty.
344 name: RuleNameP,
345 /// The year at which this rule begins, inclusive.
346 from: RuleFromP,
347 /// The year at which this rule ends, inclusive.
348 to: RuleToP,
349 /// The month at which this rule becomes active.
350 inn: RuleInP,
351 /// The day of the month at which this rule becomes active.
352 on: RuleOnP,
353 /// The time of day at which this rule becomes active.
354 at: RuleAtP,
355 /// The amount of time to add to standard time when this rule is active.
356 save: RuleSaveP,
357 /// The latters that make up the variable part of a zone's abbreviation.
358 letters: RuleLettersP,
359 }
360
361 impl RuleP {
362 fn parse(fields: &[&str]) -> Result<RuleP, Error> {
363 if fields.len() != 9 {
364 return Err(Error::from(E::ExpectedRuleNineFields {
365 got: fields.len(),
366 }));
367 }
368 let (name_field, fields) = (fields[0], &fields[1..]);
369 let (from_field, fields) = (fields[0], &fields[1..]);
370 let (to_field, fields) = (fields[0], &fields[1..]);
371 let (_reserved_field, fields) = (fields[0], &fields[1..]);
372 let (in_field, fields) = (fields[0], &fields[1..]);
373 let (on_field, fields) = (fields[0], &fields[1..]);
374 let (at_field, fields) = (fields[0], &fields[1..]);
375 let (save_field, fields) = (fields[0], &fields[1..]);
376 let letters_field = fields[0];
377
378 let name = name_field
379 .parse::<RuleNameP>()
380 .context(E::FailedParseFieldName)?;
381 let from = from_field
382 .parse::<RuleFromP>()
383 .context(E::FailedParseFieldFrom)?;
384 let to = to_field.parse::<RuleToP>().context(E::FailedParseFieldTo)?;
385 let inn =
386 in_field.parse::<RuleInP>().context(E::FailedParseFieldIn)?;
387 let on = on_field.parse::<RuleOnP>().context(E::FailedParseFieldOn)?;
388 let at = at_field.parse::<RuleAtP>().context(E::FailedParseFieldAt)?;
389 let save = save_field
390 .parse::<RuleSaveP>()
391 .context(E::FailedParseFieldSave)?;
392 let letters = letters_field
393 .parse::<RuleLettersP>()
394 .context(E::FailedParseFieldLetters)?;
395
396 Ok(RuleP { name, from, to, inn, on, at, save, letters })
397 }
398
399 fn years(&self) -> Result<RangeInclusive<i16>, Error> {
400 let start = self.from.year;
401 let end = match self.to {
402 RuleToP::Max => b::Year::MAX,
403 RuleToP::Only => start,
404 RuleToP::Year { year } => year,
405 };
406 if start > end {
407 return Err(Error::from(E::InvalidRuleYear {
408 start: start,
409 end: end,
410 }));
411 }
412 Ok(start..=end)
413 }
414 }
415
416 /// A group of one or more `Zone` lines.
417 ///
418 /// A group of zones always starts with a `Zone` line that has a name, and is
419 /// followed by zero or more continuation `Zone` lines.
420 #[derive(Clone, Debug, Eq, PartialEq)]
421 struct ZoneP {
422 /// The first zone line, always present.
423 first: ZoneFirstP,
424 /// All continuation lines, may be empty.
425 continuations: Vec<ZoneContinuationP>,
426 }
427
428 /// The parser representation of a `Zone` line.
429 #[derive(Clone, Debug, Eq, PartialEq)]
430 struct ZoneFirstP {
431 /// The name of the zone.
432 name: ZoneNameP,
433 /// The offset to add to UTC to get "standard" time for this zone.
434 stdoff: ZoneStdoffP,
435 /// The rules to apply for this zone. When `None`, standard time always
436 /// applies.
437 rules: ZoneRulesP,
438 /// The format to use when rendering a time zone abbreviation.
439 format: ZoneFormatP,
440 /// The zone is active until this time.
441 ///
442 /// When present, it implies the existence of a continuation zone following
443 /// this one. When absent, it is the last zone for the given name.
444 until: Option<ZoneUntilP>,
445 }
446
447 impl ZoneFirstP {
448 fn parse(fields: &[&str]) -> Result<ZoneFirstP, Error> {
449 if fields.len() < 4 {
450 return Err(Error::from(E::ExpectedFirstZoneFourFields));
451 }
452 let (name_field, fields) = (fields[0], &fields[1..]);
453 let (stdoff_field, fields) = (fields[0], &fields[1..]);
454 let (rules_field, fields) = (fields[0], &fields[1..]);
455 let (format_field, fields) = (fields[0], &fields[1..]);
456 let name = name_field
457 .parse::<ZoneNameP>()
458 .context(E::FailedParseFieldName)?;
459 let stdoff = stdoff_field
460 .parse::<ZoneStdoffP>()
461 .context(E::FailedParseFieldStdOff)?;
462 let rules = rules_field
463 .parse::<ZoneRulesP>()
464 .context(E::FailedParseFieldRules)?;
465 let format = format_field
466 .parse::<ZoneFormatP>()
467 .context(E::FailedParseFieldFormat)?;
468 let until = if fields.is_empty() {
469 None
470 } else {
471 Some(ZoneUntilP::parse(fields).context(E::FailedParseFieldUntil)?)
472 };
473 Ok(ZoneFirstP { name, stdoff, rules, format, until })
474 }
475 }
476
477 /// The parser representation of a `Zone` line.
478 #[derive(Clone, Debug, Eq, PartialEq)]
479 struct ZoneContinuationP {
480 /// The offset to add to UTC to get "standard" time for this zone.
481 stdoff: ZoneStdoffP,
482 /// The rules to apply for this zone. When `None`, standard time always
483 /// applies.
484 rules: ZoneRulesP,
485 /// The format to use when rendering a time zone abbreviation.
486 format: ZoneFormatP,
487 /// The zone is active until this time.
488 ///
489 /// When present, it implies the existence of a continuation zone following
490 /// this one. When absent, it is the last zone line for a particular name.
491 until: Option<ZoneUntilP>,
492 }
493
494 impl ZoneContinuationP {
495 fn parse(fields: &[&str]) -> Result<ZoneContinuationP, Error> {
496 if fields.len() < 3 {
497 return Err(Error::from(E::ExpectedContinuationZoneThreeFields));
498 }
499 let (stdoff_field, fields) = (fields[0], &fields[1..]);
500 let (rules_field, fields) = (fields[0], &fields[1..]);
501 let (format_field, fields) = (fields[0], &fields[1..]);
502 let stdoff = stdoff_field
503 .parse::<ZoneStdoffP>()
504 .context(E::FailedParseFieldStdOff)?;
505 let rules = rules_field
506 .parse::<ZoneRulesP>()
507 .context(E::FailedParseFieldRules)?;
508 let format = format_field
509 .parse::<ZoneFormatP>()
510 .context(E::FailedParseFieldFormat)?;
511 let until = if fields.is_empty() {
512 None
513 } else {
514 Some(ZoneUntilP::parse(fields).context(E::FailedParseFieldUntil)?)
515 };
516 Ok(ZoneContinuationP { stdoff, rules, format, until })
517 }
518 }
519
520 /// The parsed representation of a `Link` line.
521 #[derive(Clone, Debug, Eq, PartialEq)]
522 struct LinkP {
523 /// The time zone being linked. This must be the name of some other `Zone`
524 /// or `Link`.
525 target: ZoneNameP,
526 /// The name of the link.
527 name: ZoneNameP,
528 }
529
530 impl LinkP {
531 fn parse(fields: &[&str]) -> Result<LinkP, Error> {
532 if fields.len() != 2 {
533 return Err(Error::from(E::ExpectedLinkTwoFields));
534 }
535 let target = fields[0]
536 .parse::<ZoneNameP>()
537 .context(E::FailedParseFieldLinkTarget)?;
538 let name = fields[1]
539 .parse::<ZoneNameP>()
540 .context(E::FailedParseFieldLinkName)?;
541 Ok(LinkP { target, name })
542 }
543 }
544
545 /// The name of a rule.
546 #[derive(Clone, Debug, Eq, PartialEq)]
547 struct RuleNameP {
548 name: String,
549 }
550
551 impl FromStr for RuleNameP {
552 type Err = Error;
553
554 fn from_str(name: &str) -> Result<RuleNameP, Error> {
555 // The `man zic` docs say:
556 //
557 // > The name must start with a character that is neither an ASCII
558 // > digit nor "-" nor "+". To allow for future extensions, an
559 // > unquoted name should not contain characters from the set
560 // > "!$%&'()*,/:;<=>?@[\]^`{|}~".
561 //
562 // We check that it doesn't start with [0-9+-] but don't bother
563 // checking whether the name contains any of the other special
564 // characters anywhere. It seems fine to skip that for now, and because
565 // we don't actually know at this point whether the field was quoted
566 // or not. We erase that information. We could rejigger things to keep
567 // that information around, but... Meh.
568 if name.is_empty() {
569 Err(Error::from(E::ExpectedNonEmptyName))
570 } else if name.starts_with(|ch| matches!(ch, '0'..='9' | '+' | '-')) {
571 Err(Error::from(E::ExpectedNameBegin))
572 } else {
573 Ok(RuleNameP { name: name.to_string() })
574 }
575 }
576 }
577
578 /// The year at which this rule begins (inclusive).
579 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
580 struct RuleFromP {
581 year: i16,
582 }
583
584 impl FromStr for RuleFromP {
585 type Err = Error;
586
587 fn from_str(from: &str) -> Result<RuleFromP, Error> {
588 let year = parse_year(from).context(E::FailedParseFieldFrom)?;
589 Ok(RuleFromP { year })
590 }
591 }
592
593 /// The year at which this rule ends (inclusive).
594 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
595 enum RuleToP {
596 /// The indefinite future.
597 Max,
598 /// Repeat the year given in the FROM field.
599 Only,
600 /// A specific year at which the rules ends. The year is an inclusive
601 /// bound, but must be greater than or equal to the year in the FROM
602 /// field of the rule.
603 Year { year: i16 },
604 }
605
606 impl FromStr for RuleToP {
607 type Err = Error;
608
609 fn from_str(to: &str) -> Result<RuleToP, Error> {
610 if to.starts_with("m") && "maximum".starts_with(to) {
611 Ok(RuleToP::Max)
612 } else if to.starts_with("o") && "only".starts_with(to) {
613 Ok(RuleToP::Only)
614 } else {
615 let year = parse_year(to).context(E::FailedParseFieldTo)?;
616 Ok(RuleToP::Year { year })
617 }
618 }
619 }
620
621 /// The month in which a rule becomes active.
622 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
623 struct RuleInP {
624 month: i8,
625 }
626
627 impl FromStr for RuleInP {
628 type Err = Error;
629
630 fn from_str(field: &str) -> Result<RuleInP, Error> {
631 static MONTH_PREFIXES: &[(i8, &str, &str)] = &[
632 (1, "January", "Ja"),
633 (2, "February", "F"),
634 (3, "March", "Mar"),
635 (4, "April", "Ap"),
636 (5, "May", "May"),
637 (6, "June", "Jun"),
638 (7, "July", "Jul"),
639 (8, "August", "Au"),
640 (9, "September", "S"),
641 (10, "October", "O"),
642 (11, "November", "N"),
643 (12, "December", "D"),
644 ];
645 for &(month, name, prefix) in MONTH_PREFIXES {
646 if field.starts_with(prefix) && name.starts_with(field) {
647 return Ok(RuleInP { month });
648 }
649 }
650 Err(Error::from(E::UnrecognizedMonthName))
651 }
652 }
653
654 /// The day of the month in which a rule becomes active.
655 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
656 enum RuleOnP {
657 /// A specific fixed day of a month.
658 Day { day: i8 },
659 /// The last weekday of a month.
660 Last { weekday: Weekday },
661 /// The weekday on or before a particular day of the month.
662 OnOrBefore { weekday: Weekday, day: i8 },
663 /// The weekday on or after a particular day of the month.
664 OnOrAfter { weekday: Weekday, day: i8 },
665 }
666
667 impl RuleOnP {
668 /// Given a year and a month, return the specific date for this "day of the
669 /// month" specification.
670 fn date(&self, year: i16, month: i8) -> Result<Date, Error> {
671 match *self {
672 RuleOnP::Day { day } => Date::new(year, month, day),
673 RuleOnP::Last { weekday } => {
674 // Always a valid date given that year/month are valid.
675 let date = Date::new(year, month, 1).unwrap();
676 date.nth_weekday_of_month(-1, weekday)
677 }
678 RuleOnP::OnOrBefore { weekday, day } => {
679 let start =
680 Date::new(year, month, day)?.checked_add(1.day())?;
681 // nth_weekday returns "before" instead of "on or before," so
682 // offset the date by a day to get "on or before" semantics.
683 start.nth_weekday(-1, weekday)
684 }
685 RuleOnP::OnOrAfter { weekday, day } => {
686 let start =
687 Date::new(year, month, day)?.checked_sub(1.day())?;
688 // nth_weekday returns "after" instead of "on or after," so
689 // offset the date by a day to get "on or after" semantics.
690 start.nth_weekday(1, weekday)
691 }
692 }
693 }
694 }
695
696 impl FromStr for RuleOnP {
697 type Err = Error;
698
699 fn from_str(field: &str) -> Result<RuleOnP, Error> {
700 if field.starts_with("last") {
701 let weekday = parse_weekday(&field[4..])?;
702 Ok(RuleOnP::Last { weekday })
703 } else if let Some(i) = field.find("<=") {
704 let weekday = parse_weekday(&field[..i])?;
705 let day = parse_day(&field[i + 2..])?;
706 Ok(RuleOnP::OnOrBefore { weekday, day })
707 } else if let Some(i) = field.find(">=") {
708 let weekday = parse_weekday(&field[..i])?;
709 let day = parse_day(&field[i + 2..])?;
710 Ok(RuleOnP::OnOrAfter { weekday, day })
711 } else if field.chars().all(|ch| ch.is_ascii_digit()) {
712 let day = parse_day(field)?;
713 // We don't check that `day` is valid for the month given in the IN
714 // field. That gets checked at a higher level.
715 Ok(RuleOnP::Day { day })
716 } else {
717 Err(Error::from(E::UnrecognizedDayOfMonthFormat))
718 }
719 }
720 }
721
722 /// The time of day at which a rule becomes active.
723 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
724 struct RuleAtP {
725 /// The amount of time to add to the start of the day specified by
726 /// `RuleOnP`. This may be negative.
727 dur: SignedDuration,
728 /// An optional suffix indicating how to interpret the overall time at
729 /// which a rule takes effect. As I understand it, this applies to the
730 /// entire datetime that is specified by IN, ON and AT and not just the
731 /// AT portion. (Because the suffix may cause the datetime to have an
732 /// offset applied to it, and that offset can change the day!)
733 ///
734 /// When not present, wall clock time is assumed.
735 suffix: Option<RuleAtSuffixP>,
736 }
737
738 impl RuleAtP {
739 /// Returns the suffix for this AT field.
740 ///
741 /// When the suffix is absent, a default is selected.
742 fn suffix(&self) -> RuleAtSuffixP {
743 self.suffix.unwrap_or_default()
744 }
745 }
746
747 impl FromStr for RuleAtP {
748 type Err = Error;
749
750 fn from_str(at: &str) -> Result<RuleAtP, Error> {
751 if at.is_empty() {
752 return Err(Error::from(E::ExpectedNonEmptyAt));
753 }
754 let (span_string, suffix_string) = at.split_at(at.len() - 1);
755 if suffix_string.chars().all(|ch| ch.is_ascii_alphabetic()) {
756 let span = parse_duration(span_string)?;
757 let suffix = suffix_string.parse()?;
758 Ok(RuleAtP { dur: span, suffix: Some(suffix) })
759 } else {
760 let span = parse_duration(at)?;
761 Ok(RuleAtP { dur: span, suffix: None })
762 }
763 }
764 }
765
766 /// The optional suffix that may be applied to the AT field of a rule.
767 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
768 enum RuleAtSuffixP {
769 #[default]
770 Wall,
771 Standard,
772 Universal,
773 }
774
775 impl FromStr for RuleAtSuffixP {
776 type Err = Error;
777
778 fn from_str(suffix: &str) -> Result<RuleAtSuffixP, Error> {
779 match suffix {
780 "w" => Ok(RuleAtSuffixP::Wall),
781 "s" => Ok(RuleAtSuffixP::Standard),
782 "u" | "g" | "z" => Ok(RuleAtSuffixP::Universal),
783 _ => Err(Error::from(E::UnrecognizedAtTimeSuffix)),
784 }
785 }
786 }
787
788 /// The amount of time to add to standard time when the corresponding rule is
789 /// in effect.
790 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
791 struct RuleSaveP {
792 /// The amount of time to add. This may be negative.
793 dur: SignedDuration,
794 /// An optional suffix indicating how the resulting time after applying
795 /// this rule should be interpreted. When absent, this defaults to DST.
796 suffix: Option<RuleSaveSuffixP>,
797 }
798
799 impl RuleSaveP {
800 /// Returns this "save" time as an offset.
801 ///
802 /// If the span is too long to fit in an offset, then an error is returned.
803 fn to_offset(&self) -> Result<Offset, Error> {
804 // TODO: I think `zic` rounds to the nearest second, breaking ties to
805 // the nearest even second?
806 let seconds = b::OffsetTotalSeconds::check(self.dur.as_secs())?;
807 Offset::from_seconds(seconds)
808 }
809
810 /// Returns the suffix for this SAVE field.
811 ///
812 /// When the suffix is absent, a default is selected based on the time
813 /// span in the field.
814 fn suffix(&self) -> RuleSaveSuffixP {
815 self.suffix.unwrap_or_else(|| {
816 if self.dur.is_zero() {
817 RuleSaveSuffixP::Standard
818 } else {
819 RuleSaveSuffixP::Dst
820 }
821 })
822 }
823 }
824
825 impl FromStr for RuleSaveP {
826 type Err = Error;
827
828 fn from_str(at: &str) -> Result<RuleSaveP, Error> {
829 if at.is_empty() {
830 return Err(Error::from(E::ExpectedNonEmptySave));
831 }
832 let (span_string, suffix_string) = at.split_at(at.len() - 1);
833 if suffix_string.chars().all(|ch| ch.is_ascii_alphabetic()) {
834 let span = parse_duration(span_string)?;
835 let suffix = suffix_string.parse()?;
836 Ok(RuleSaveP { dur: span, suffix: Some(suffix) })
837 } else {
838 let span = parse_duration(at)?;
839 Ok(RuleSaveP { dur: span, suffix: None })
840 }
841 }
842 }
843
844 /// The optional suffix for the `SAVE` field of a `Rule` line.
845 ///
846 /// The default for this depends on the time duration. When it's `0`, the
847 /// default suffix is `Standard`. Otherwise, it's `Dst`.
848 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
849 enum RuleSaveSuffixP {
850 /// The resulting time after applying the corresponding rule should be
851 /// treated as standard time.
852 Standard,
853 /// The resulting time after applying the corresponding rule should be
854 /// treated as DST time.
855 Dst,
856 }
857
858 impl FromStr for RuleSaveSuffixP {
859 type Err = Error;
860
861 fn from_str(suffix: &str) -> Result<RuleSaveSuffixP, Error> {
862 match suffix {
863 "s" => Ok(RuleSaveSuffixP::Standard),
864 "d" => Ok(RuleSaveSuffixP::Dst),
865 _ => Err(Error::from(E::UnrecognizedSaveTimeSuffix)),
866 }
867 }
868 }
869
870 /// The latters that make up the variable part of a zone's abbreviation.
871 ///
872 /// For example, if a zone's format is `E%sT`, then the letters might be
873 /// `S` or `D` for standard time and DST, respectively.
874 #[derive(Clone, Debug, Eq, PartialEq)]
875 struct RuleLettersP {
876 /// The actual value that should be interpolated. It may be absent, in
877 /// which case, the empty string should be substituted.
878 part: String,
879 }
880
881 impl FromStr for RuleLettersP {
882 type Err = Error;
883
884 fn from_str(letters: &str) -> Result<RuleLettersP, Error> {
885 let part =
886 if letters == "-" { String::new() } else { letters.to_string() };
887 Ok(RuleLettersP { part })
888 }
889 }
890
891 /// The name of a zone.
892 #[derive(Clone, Debug, Eq, PartialEq)]
893 struct ZoneNameP {
894 name: String,
895 }
896
897 impl FromStr for ZoneNameP {
898 type Err = Error;
899
900 fn from_str(name: &str) -> Result<ZoneNameP, Error> {
901 if name.is_empty() {
902 return Err(Error::from(E::ExpectedNonEmptyZoneName));
903 }
904 for component in name.split('/') {
905 if component == "." || component == ".." {
906 return Err(Error::from(E::ExpectedZoneNameComponentNoDots {
907 component: component.into(),
908 }));
909 }
910 }
911 Ok(ZoneNameP { name: name.to_string() })
912 }
913 }
914
915 /// The offset to add to UTC to get "standard" time for a zone.
916 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
917 struct ZoneStdoffP {
918 /// The duration. This only uses units of hours or lower.
919 dur: SignedDuration,
920 }
921
922 impl FromStr for ZoneStdoffP {
923 type Err = Error;
924
925 fn from_str(stdoff: &str) -> Result<ZoneStdoffP, Error> {
926 let dur = parse_duration(stdoff)?;
927 Ok(ZoneStdoffP { dur })
928 }
929 }
930
931 /// The rule specification for a zone.
932 #[derive(Clone, Debug, Eq, PartialEq)]
933 enum ZoneRulesP {
934 /// No rules are used. Standard time always applies.
935 None,
936 /// This zone uses a set of rules with the given name.
937 Named(RuleNameP),
938 /// An inline rule corresponding to a fixed offset from standard time for
939 /// this zone.
940 Save(RuleSaveP),
941 }
942
943 impl FromStr for ZoneRulesP {
944 type Err = Error;
945
946 fn from_str(rules: &str) -> Result<ZoneRulesP, Error> {
947 if rules.starts_with(|ch: char| ch == '-' || ch.is_ascii_digit()) {
948 // RuleSaveP actually accounts for the lone '-' case, so this is
949 // technically redundant case analysis. But it is called out
950 // specifically in the docs, so we parse it separately anyway.
951 if rules == "-" {
952 Ok(ZoneRulesP::None)
953 } else {
954 Ok(ZoneRulesP::Save(rules.parse()?))
955 }
956 } else {
957 Ok(ZoneRulesP::Named(rules.parse()?))
958 }
959 }
960 }
961
962 /// The format of the abbreviation for this zone, including when it's in DST.
963 #[derive(Clone, Debug, Eq, PartialEq)]
964 enum ZoneFormatP {
965 /// This corresponds to a format that contains a `%s`, where the `%s` is
966 /// meant to be interpolated with the letters specified in a matching rule.
967 Variable {
968 /// The text before a `%s`.
969 before: String,
970 /// The text after a `%s`.
971 after: String,
972 },
973 /// This corresponds to the `%z` format, where the abbreviation should
974 /// be a human readable rendering of the offset applied.
975 Offset,
976 /// This corresponds to the `STD/DST` format, where `STD` is the abbreviation
977 /// for standard time, and `DST` is the abbreviation for DST.
978 Pair {
979 /// The abbreviation to use for standard time.
980 std: String,
981 /// The abbreviation to use for DST time.
982 dst: String,
983 },
984 /// A static string that never changes.
985 Static {
986 /// The format string which is never interpolated.
987 format: String,
988 },
989 }
990
991 impl FromStr for ZoneFormatP {
992 type Err = Error;
993
994 fn from_str(format: &str) -> Result<ZoneFormatP, Error> {
995 fn check_abbrev(abbrev: &str) -> Result<String, Error> {
996 if abbrev.is_empty() {
997 return Err(Error::from(E::ExpectedNonEmptyAbbreviation));
998 }
999 let is_ok =
1000 |ch| matches!(ch, '+'|'-'|'0'..='9'|'A'..='Z'|'a'..='z');
1001 if !abbrev.chars().all(is_ok) {
1002 return Err(Error::from(E::InvalidAbbreviation));
1003 }
1004 Ok(abbrev.to_string())
1005 }
1006 if format == "%z" {
1007 Ok(ZoneFormatP::Offset)
1008 } else if let Some((before, after)) = format.split_once("%s") {
1009 Ok(ZoneFormatP::Variable {
1010 before: check_abbrev(before)?,
1011 after: check_abbrev(after)?,
1012 })
1013 } else if let Some((std, dst)) = format.split_once("/") {
1014 Ok(ZoneFormatP::Pair {
1015 std: check_abbrev(std)?,
1016 dst: check_abbrev(dst)?,
1017 })
1018 } else {
1019 Ok(ZoneFormatP::Static { format: check_abbrev(format)? })
1020 }
1021 }
1022 }
1023
1024 /// The time until a particular zone is active.
1025 ///
1026 /// This time is treated as an exclusive boundary. That is, times at precisely
1027 /// this point are not governed by its corresponding zone.
1028 #[derive(Clone, Debug, Eq, PartialEq)]
1029 enum ZoneUntilP {
1030 Year {
1031 year: i16,
1032 },
1033 YearMonth {
1034 year: i16,
1035 month: RuleInP,
1036 },
1037 YearMonthDay {
1038 year: i16,
1039 month: RuleInP,
1040 day: RuleOnP,
1041 },
1042 YearMonthDayTime {
1043 year: i16,
1044 month: RuleInP,
1045 day: RuleOnP,
1046 /// Note that adding a span to the year/month/day could overflow
1047 /// the allowed maximum time. This isn't handled until this type is
1048 /// converted into higher level data types.
1049 duration: RuleAtP,
1050 },
1051 }
1052
1053 impl ZoneUntilP {
1054 fn parse(fields: &[&str]) -> Result<ZoneUntilP, Error> {
1055 if fields.is_empty() {
1056 return Err(Error::from(E::ExpectedUntilYear));
1057 }
1058
1059 let (year_field, fields) = (fields[0], &fields[1..]);
1060 let year = parse_year(year_field).context(E::FailedParseYear)?;
1061 if fields.is_empty() {
1062 return Ok(ZoneUntilP::Year { year });
1063 }
1064
1065 let (month_field, fields) = (fields[0], &fields[1..]);
1066 let month =
1067 month_field.parse::<RuleInP>().context(E::FailedParseMonth)?;
1068 if fields.is_empty() {
1069 return Ok(ZoneUntilP::YearMonth { year, month });
1070 }
1071
1072 let (day_field, fields) = (fields[0], &fields[1..]);
1073 let day = day_field.parse::<RuleOnP>().context(E::FailedParseDay)?;
1074 if fields.is_empty() {
1075 return Ok(ZoneUntilP::YearMonthDay { year, month, day });
1076 }
1077
1078 let (duration_field, fields) = (fields[0], &fields[1..]);
1079 let duration = duration_field
1080 .parse::<RuleAtP>()
1081 .context(E::FailedParseTimeDuration)?;
1082 if !fields.is_empty() {
1083 return Err(Error::from(E::ExpectedNothingAfterTime));
1084 }
1085 Ok(ZoneUntilP::YearMonthDayTime { year, month, day, duration })
1086 }
1087
1088 fn to_datetime(&self) -> Result<DateTime, Error> {
1089 let date = self.on().date(self.year(), self.month())?;
1090 let dt =
1091 date.to_datetime(Time::midnight()).checked_add(self.at().dur)?;
1092 Ok(dt)
1093 }
1094
1095 fn year(&self) -> i16 {
1096 use self::ZoneUntilP::*;
1097
1098 match *self {
1099 Year { year }
1100 | YearMonth { year, .. }
1101 | YearMonthDay { year, .. }
1102 | YearMonthDayTime { year, .. } => year,
1103 }
1104 }
1105
1106 fn month(&self) -> i8 {
1107 use self::ZoneUntilP::*;
1108
1109 match *self {
1110 Year { .. } => 1,
1111 YearMonth { month, .. }
1112 | YearMonthDay { month, .. }
1113 | YearMonthDayTime { month, .. } => month.month,
1114 }
1115 }
1116
1117 fn on(&self) -> RuleOnP {
1118 use self::ZoneUntilP::*;
1119
1120 match *self {
1121 Year { .. } | YearMonth { .. } => RuleOnP::Day { day: 1 },
1122 YearMonthDay { day, .. } | YearMonthDayTime { day, .. } => day,
1123 }
1124 }
1125
1126 fn at(&self) -> RuleAtP {
1127 use self::ZoneUntilP::*;
1128
1129 match *self {
1130 Year { .. } | YearMonth { .. } | YearMonthDay { .. } => {
1131 RuleAtP { dur: SignedDuration::ZERO, suffix: None }
1132 }
1133 YearMonthDayTime { duration, .. } => duration,
1134 }
1135 }
1136 }
1137
1138 /// Parse a signed year value.
1139 ///
1140 /// This ensures the year is within the range supported by Jiff.
1141 fn parse_year(year: &str) -> Result<i16, Error> {
1142 let (sign, rest) = if year.starts_with("-") {
1143 (Sign::Negative, &year[1..])
1144 } else {
1145 (Sign::Positive, year)
1146 };
1147 let year =
1148 parse::bi64::<b::Year>(rest.as_bytes()).context(E::FailedParseYear)?;
1149 Ok(sign * year)
1150 }
1151
1152 /// Parse a duration of time expressed in hours, minutes and seconds.
1153 ///
1154 /// The format is something like: `[-]H+[:M+[:S+[.N+]]]`, where `H` is any
1155 /// ASCII digit. Minutes and seconds are limited to the values `0-59`,
1156 /// inclusive. Nanoseconds are limited to a fraction of a second. (And the
1157 /// format doesn't actually specify a maximum precision, but we don't support
1158 /// anything beyond nanoseconds, and in practice, the value will get rounded to
1159 /// the nearest second at a higher level.) Hours can seemingly be any number we
1160 /// can reasonably represent. The leading `-` sign means it can be negative.
1161 /// And as a special case, a `-` all on its own is equivalent to `0`.
1162 fn parse_duration(span: &str) -> Result<SignedDuration, Error> {
1163 // This function is just brutal. I feel like I'm over-complicating it. I
1164 // suppoose we could probably do a little better here with a better set of
1165 // parser combinator helpers. But it's all inter-woven with parsing numbers
1166 // too.
1167
1168 let rest = span;
1169 let (sign, rest) = if rest.starts_with("-") {
1170 // Special case where if the duration is just `-`, then it's equivalent
1171 // to zero.
1172 if span.len() == 1 {
1173 return Ok(SignedDuration::ZERO);
1174 }
1175 (Sign::Negative, &rest[1..])
1176 } else {
1177 (Sign::Positive, rest)
1178 };
1179 let mut dur = SignedDuration::ZERO;
1180
1181 // Pluck out the hour component.
1182 let hour_len = rest.chars().take_while(|c| c.is_ascii_digit()).count();
1183 let (hour_digits, rest) = rest.split_at(hour_len);
1184 if hour_digits.is_empty() {
1185 return Err(Error::from(E::ExpectedTimeOneHour));
1186 }
1187 let hours = parse::bi64::<b::SpanHours>(hour_digits.as_bytes())
1188 .context(E::FailedParseHour)?;
1189 dur += SignedDuration::from_hours(sign * i64::from(hours));
1190 if rest.is_empty() {
1191 return Ok(dur);
1192 }
1193
1194 // Now pluck out the minute component.
1195 if !rest.starts_with(":") {
1196 return Err(Error::from(E::ExpectedColonAfterHour));
1197 }
1198 let rest = &rest[1..];
1199 let minute_len = rest.chars().take_while(|c| c.is_ascii_digit()).count();
1200 let (minute_digits, rest) = rest.split_at(minute_len);
1201 if minute_digits.is_empty() {
1202 return Err(Error::from(E::ExpectedMinuteAfterHours));
1203 }
1204 let minutes = parse::bi64::<b::Minute>(minute_digits.as_bytes())
1205 .context(E::FailedParseMinute)?;
1206 dur += SignedDuration::from_mins(sign * i64::from(minutes));
1207 if rest.is_empty() {
1208 return Ok(dur);
1209 }
1210
1211 // Now pluck out the second component.
1212 if !rest.starts_with(":") {
1213 return Err(Error::from(E::ExpectedColonAfterMinute));
1214 }
1215 let rest = &rest[1..];
1216 let second_len = rest.chars().take_while(|c| c.is_ascii_digit()).count();
1217 let (second_digits, rest) = rest.split_at(second_len);
1218 if second_digits.is_empty() {
1219 return Err(Error::from(E::ExpectedSecondAfterMinutes));
1220 }
1221 let seconds = parse::bi64::<b::Second>(second_digits.as_bytes())
1222 .context(E::FailedParseSecond)?;
1223 dur += SignedDuration::from_secs(sign * i64::from(seconds));
1224 if rest.is_empty() {
1225 return Ok(dur);
1226 }
1227
1228 // Now look for the fractional nanosecond component.
1229 if !rest.starts_with(".") {
1230 return Err(Error::from(E::ExpectedDotAfterSeconds));
1231 }
1232 let rest = &rest[1..];
1233 let nanosecond_len =
1234 rest.chars().take_while(|c| c.is_ascii_digit()).count();
1235 let (nanosecond_digits, rest) = rest.split_at(nanosecond_len);
1236 if nanosecond_digits.is_empty() {
1237 return Err(Error::from(E::ExpectedNanosecondDigits));
1238 }
1239 let nanoseconds = parse::fraction(nanosecond_digits.as_bytes())
1240 .context(E::FailedParseNanosecond)?;
1241 // OK because `parse::fraction` can't return anything more than
1242 // `999_999_999` nanoseconds.
1243 dur += SignedDuration::from_nanos(sign * i64::from(nanoseconds));
1244
1245 // We should have consumed everything at this point.
1246 if !rest.is_empty() {
1247 return Err(Error::from(E::UnrecognizedTrailingTimeDuration));
1248 }
1249 Ok(dur)
1250 }
1251
1252 /// Parses a day of the month.
1253 ///
1254 /// This checks that the day is in the range 1-31, but otherwise doesn't
1255 /// check that it is valid for a particular month.
1256 fn parse_day(string: &str) -> Result<i8, Error> {
1257 parse::bi64::<b::Day>(string.as_bytes()).context(E::FailedParseDay)
1258 }
1259
1260 /// Parses a possibly abbreviated weekday from the given string.
1261 fn parse_weekday(string: &str) -> Result<Weekday, Error> {
1262 static WEEKDAY_PREFIXES: &[(Weekday, &str, &str)] = &[
1263 (Weekday::Monday, "Monday", "M"),
1264 (Weekday::Tuesday, "Tuesday", "Tu"),
1265 (Weekday::Wednesday, "Wednesday", "W"),
1266 (Weekday::Thursday, "Thursday", "Th"),
1267 (Weekday::Friday, "Friday", "F"),
1268 (Weekday::Saturday, "Saturday", "Sa"),
1269 (Weekday::Sunday, "Sunday", "Su"),
1270 ];
1271 for &(weekday, name, prefix) in WEEKDAY_PREFIXES {
1272 if string.starts_with(prefix) && name.starts_with(string) {
1273 return Ok(weekday);
1274 }
1275 }
1276 Err(Error::from(E::UnrecognizedDayOfWeek))
1277 }
1278
1279 /// A parser that emits lines as sequences of fields.
1280 ///
1281 /// It is responsible for managing the state regarding whether to expect a
1282 /// zone continuation line or not. It also knows to skip empty or commented
1283 /// out lines.
1284 struct FieldParser<'a> {
1285 /// The full underlying source data as an iterator of lines.
1286 lines: core::str::Lines<'a>,
1287 /// The current line number, starting at 1.
1288 line_number: usize,
1289 /// The fields from the current line, initially empty.
1290 fields: Vec<&'a str>,
1291 /// Set to the name of the zone when a continuation line for that zone is
1292 /// expected.
1293 continuation_zone_for: Option<String>,
1294 }
1295
1296 impl<'a> FieldParser<'a> {
1297 /// Create a new parser from a UTF-8 encoded sequence of bytes.
1298 fn new(src: &'a str) -> FieldParser<'a> {
1299 FieldParser {
1300 lines: src.lines(),
1301 line_number: 0,
1302 fields: vec![],
1303 continuation_zone_for: None,
1304 }
1305 }
1306
1307 /// Create a new parser from a sequence of bytes.
1308 ///
1309 /// This returns an error if the given bytes are not valid UTF-8.
1310 fn from_bytes(src: &'a [u8]) -> Result<FieldParser<'a>, Error> {
1311 let src = core::str::from_utf8(src)
1312 .map_err(|_| Error::from(E::InvalidUtf8))?;
1313 Ok(FieldParser::new(src))
1314 }
1315
1316 /// Advances the parser's line iterator and splits it into `self.fields`.
1317 ///
1318 /// If there are no more lines, then this returns `Ok(false)`. Otherwise,
1319 /// if the next line exists and was successfully parsed into a sequence of
1320 /// fields, then `Ok(true)` is returned.
1321 ///
1322 /// This guarantees that when `true` is returned, `self.fields` is
1323 /// non-empty.
1324 fn read_next_fields(&mut self) -> Result<bool, Error> {
1325 self.fields.clear();
1326 loop {
1327 let Some(line) = self.lines.next() else { return Ok(false) };
1328 self.line_number =
1329 self.line_number.checked_add(1).ok_or(E::LineOverflow)?;
1330 parse_fields(&line, &mut self.fields)
1331 .context(E::Line { number: self.line_number })?;
1332 if self.fields.is_empty() {
1333 continue;
1334 }
1335 return Ok(true);
1336 }
1337 }
1338 }
1339
1340 /// Splits the line given into fields.
1341 ///
1342 /// This returns an error if there is an unclosed quoted field.
1343 ///
1344 /// It is possible for this to return successfully without having written any
1345 /// fields. Indeed, when an unquoted `#` appears, it and everything after it is
1346 /// ignored.
1347 ///
1348 /// Note that the specification in `man zic` for this is a little ambiguous.
1349 /// For example, it doesn't quite say how data like `foo"bar baz"quux` should
1350 /// be parsed. That is, it doesn't say that quoted fields must begin and end
1351 /// with a quote. This parse will treat such things as two distinct unquoted
1352 /// fields: `foo"bar` and `baz"quux`.
1353 ///
1354 /// This always clears the `fields` given.
1355 ///
1356 /// # Panics
1357 ///
1358 /// This panics if a `\n` is seen while parsing the `line`.
1359 fn parse_fields<'a>(
1360 line: &'a str,
1361 fields: &mut Vec<&'a str>,
1362 ) -> Result<(), Error> {
1363 /// Returns true if the given character corresponds to whitespace as
1364 /// defined in `man zic`.
1365 fn is_space(ch: char) -> bool {
1366 matches!(ch, ' ' | '\x0C' | '\n' | '\r' | '\t' | '\x0B')
1367 }
1368
1369 // The different possible states of the field parser below.
1370 enum State {
1371 Whitespace,
1372 InUnquote,
1373 InQuote,
1374 AfterQuote,
1375 }
1376
1377 fields.clear();
1378 if line.len() > MAX_LINE_LEN {
1379 return Err(Error::from(E::LineMaxLength));
1380 }
1381 // Do a quick scan for a NUL terminator. They are illegal in all cases.
1382 if line.contains('\x00') {
1383 return Err(Error::from(E::LineNul));
1384 }
1385 // The current state of the parser. We start at whitespace, since it also
1386 // means "before a field."
1387 let mut state = State::Whitespace;
1388 // The start of the current field. This is reset whenever we enter a state
1389 // corresponding to the beginning of a field's content.
1390 let mut start = 0;
1391 for (i, ch) in line.char_indices() {
1392 assert_ne!(ch, '\n', "no line terminators allowed within a line");
1393 state = match state {
1394 State::Whitespace => {
1395 if is_space(ch) {
1396 State::Whitespace
1397 } else if ch == '#' {
1398 return Ok(());
1399 } else if ch == '"' {
1400 start = i + ch.len_utf8();
1401 State::InQuote
1402 } else {
1403 start = i;
1404 State::InUnquote
1405 }
1406 }
1407 State::InUnquote => {
1408 if is_space(ch) {
1409 fields.push(&line[start..i]);
1410 State::Whitespace
1411 } else if ch == '#' {
1412 fields.push(&line[start..i]);
1413 return Ok(());
1414 } else {
1415 State::InUnquote
1416 }
1417 }
1418 State::InQuote => {
1419 if ch == '"' {
1420 fields.push(&line[start..i]);
1421 State::AfterQuote
1422 } else {
1423 State::InQuote
1424 }
1425 }
1426 State::AfterQuote => {
1427 if !is_space(ch) {
1428 return Err(Error::from(
1429 E::ExpectedWhitespaceAfterQuotedField,
1430 ));
1431 }
1432 State::Whitespace
1433 }
1434 };
1435 }
1436 match state {
1437 State::Whitespace | State::AfterQuote => {}
1438 State::InUnquote => {
1439 fields.push(&line[start..]);
1440 }
1441 State::InQuote => {
1442 return Err(Error::from(E::ExpectedCloseQuote));
1443 }
1444 }
1445 Ok(())
1446 }
1447
1448 #[cfg(test)]
1449 mod tests {
1450 use crate::civil::date;
1451
1452 use super::*;
1453
1454 fn td(seconds: i64, nanoseconds: i32) -> SignedDuration {
1455 SignedDuration::new(seconds, nanoseconds)
1456 }
1457
1458 #[test]
1459 fn zone_until_to_datetime() {
1460 let until = ZoneUntilP::parse(&["2024"]).unwrap();
1461 let wall = until.to_datetime().unwrap();
1462 assert_eq!(wall, date(2024, 1, 1).at(0, 0, 0, 0));
1463
1464 let until = ZoneUntilP::parse(&["2024", "Mar"]).unwrap();
1465 let wall = until.to_datetime().unwrap();
1466 assert_eq!(wall, date(2024, 3, 1).at(0, 0, 0, 0));
1467
1468 let until = ZoneUntilP::parse(&["2024", "Mar", "Sun>=8"]).unwrap();
1469 let wall = until.to_datetime().unwrap();
1470 assert_eq!(wall, date(2024, 3, 10).at(0, 0, 0, 0));
1471
1472 let until =
1473 ZoneUntilP::parse(&["2024", "Mar", "Sun>=8", "2:00"]).unwrap();
1474 let wall = until.to_datetime().unwrap();
1475 assert_eq!(wall, date(2024, 3, 10).at(2, 0, 0, 0));
1476
1477 let until =
1478 ZoneUntilP::parse(&["2024", "Mar", "Sun>=10", "2:00"]).unwrap();
1479 let wall = until.to_datetime().unwrap();
1480 assert_eq!(wall, date(2024, 3, 10).at(2, 0, 0, 0));
1481
1482 let until =
1483 ZoneUntilP::parse(&["2024", "Mar", "Sun<=10", "2:00"]).unwrap();
1484 let wall = until.to_datetime().unwrap();
1485 assert_eq!(wall, date(2024, 3, 10).at(2, 0, 0, 0));
1486
1487 let until =
1488 ZoneUntilP::parse(&["2024", "Mar", "Sun<=10", "2:00u"]).unwrap();
1489 let wall = until.to_datetime().unwrap();
1490 assert_eq!(wall, date(2024, 3, 10).at(2, 0, 0, 0));
1491 }
1492
1493 #[cfg(not(miri))]
1494 #[test]
1495 fn parse_zic_man1() {
1496 // An example from `man zic`.
1497 let data = "
1498 # Rule NAME FROM TO - IN ON AT SAVE LETTER/S
1499 Rule US 1967 2006 - Oct lastSun 2:00 0 S
1500 Rule US 1967 1973 - Apr lastSun 2:00 1:00 D
1501 # Zone NAME STDOFF RULES FORMAT [UNTIL]
1502 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1503 -6:00 US C%sT
1504 ";
1505 let mut zic = ZicP::default();
1506 zic.parse(data).unwrap();
1507 insta::assert_debug_snapshot!(zic);
1508 }
1509
1510 #[cfg(not(miri))]
1511 #[test]
1512 fn parse_zic_man2() {
1513 // An example from `man zic`.
1514 let data = "
1515 # Rule NAME FROM TO - IN ON AT SAVE LETTER/S
1516 Rule Swiss 1941 1942 - May Mon>=1 1:00 1:00 S
1517 Rule Swiss 1941 1942 - Oct Mon>=1 2:00 0 -
1518 Rule EU 1977 1980 - Apr Sun>=1 1:00u 1:00 S
1519 Rule EU 1977 only - Sep lastSun 1:00u 0 -
1520 Rule EU 1978 only - Oct 1 1:00u 0 -
1521 Rule EU 1979 1995 - Sep lastSun 1:00u 0 -
1522 Rule EU 1981 max - Mar lastSun 1:00u 1:00 S
1523 Rule EU 1996 max - Oct lastSun 1:00u 0 -
1524
1525 # Zone NAME STDOFF RULES FORMAT [UNTIL]
1526 Zone Europe/Zurich 0:34:08 - LMT 1853 Jul 16
1527 0:29:45.50 - BMT 1894 Jun
1528 1:00 Swiss CE%sT 1981
1529 1:00 EU CE%sT
1530
1531 Link Europe/Zurich Europe/Vaduz
1532 ";
1533 let mut zic = ZicP::default();
1534 zic.parse(data).unwrap();
1535 insta::assert_debug_snapshot!(zic);
1536 }
1537
1538 #[test]
1539 fn parse_zic_err() {
1540 // A continuation zone line where one wasn't expected.
1541 let data = "
1542 Zone America/Menominee -5:00 - EST
1543 -6:00 US C%sT
1544 ";
1545 assert!(ZicP::default().parse(data).is_err());
1546
1547 // No continuation line where one was expected but got Link instead.
1548 let data = "
1549 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1550 Link America/Menominee Foo
1551 ";
1552 assert!(ZicP::default().parse(data).is_err());
1553
1554 // No continuation line where one was expected but got EOF instead.
1555 let data = "
1556 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1557 ";
1558 assert!(ZicP::default().parse(data).is_err());
1559
1560 // Link conflicts with zone.
1561 let data = "
1562 Zone America/New_York -5:00 - EST 1973 Apr 29 2:00
1563 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1564 Link America/New_York America/Menominee
1565 ";
1566 assert!(ZicP::default().parse(data).is_err());
1567
1568 // Zone conflicts with link.
1569 let data = "
1570 Link America/New_York America/Menominee
1571 Zone America/New_York -5:00 - EST 1973 Apr 29 2:00
1572 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1573 ";
1574 assert!(ZicP::default().parse(data).is_err());
1575
1576 // Zone conflicts with zone.
1577 let data = "
1578 Zone America/New_York -5:00 - EST 1973 Apr 29 2:00
1579 Zone America/New_York -5:00 - EST 1973 Apr 29 2:00
1580 ";
1581 assert!(ZicP::default().parse(data).is_err());
1582
1583 // Link conflicts with link.
1584 let data = "
1585 Zone America/New_York -5:00 - EST 1973 Apr 29 2:00
1586 Zone America/Menominee -5:00 - EST 1973 Apr 29 2:00
1587 Link America/New_York Foo
1588 Link America/Menominee Foo
1589 ";
1590 assert!(ZicP::default().parse(data).is_err());
1591 }
1592
1593 #[cfg(not(miri))]
1594 #[test]
1595 fn parse_rule_ok() {
1596 let rule: RuleP = RuleP::parse(&[
1597 "US", "1967", "1973", "-", "Apr", "lastSun", "2:00w", "1:00d", "D",
1598 ])
1599 .unwrap();
1600 insta::assert_debug_snapshot!(rule, @r#"
1601 RuleP {
1602 name: RuleNameP {
1603 name: "US",
1604 },
1605 from: RuleFromP {
1606 year: 1967,
1607 },
1608 to: Year {
1609 year: 1973,
1610 },
1611 inn: RuleInP {
1612 month: 4,
1613 },
1614 on: Last {
1615 weekday: Sunday,
1616 },
1617 at: RuleAtP {
1618 dur: 7200s,
1619 suffix: Some(
1620 Wall,
1621 ),
1622 },
1623 save: RuleSaveP {
1624 dur: 3600s,
1625 suffix: Some(
1626 Dst,
1627 ),
1628 },
1629 letters: RuleLettersP {
1630 part: "D",
1631 },
1632 }
1633 "#);
1634 }
1635
1636 #[test]
1637 fn parse_rule_err() {
1638 assert!(RuleP::parse(&[
1639 "US", "1967", "1973", "-", "Apr", "lastSun", "2:00w", "1:00d",
1640 "D", "E",
1641 ])
1642 .is_err());
1643 assert!(RuleP::parse(&[
1644 "US", "1967", "1973", "-", "Apr", "lastSun", "2:00w", "1:00d",
1645 ])
1646 .is_err());
1647 }
1648
1649 #[cfg(not(miri))]
1650 #[test]
1651 fn parse_zone_first_ok() {
1652 let zone: ZoneFirstP =
1653 ZoneFirstP::parse(&["America/Menominee", "-5:00", "-", "EST"])
1654 .unwrap();
1655 insta::assert_debug_snapshot!(zone, @r#"
1656 ZoneFirstP {
1657 name: ZoneNameP {
1658 name: "America/Menominee",
1659 },
1660 stdoff: ZoneStdoffP {
1661 dur: -18000s,
1662 },
1663 rules: None,
1664 format: Static {
1665 format: "EST",
1666 },
1667 until: None,
1668 }
1669 "#);
1670
1671 let zone: ZoneFirstP = ZoneFirstP::parse(&[
1672 "America/Menominee",
1673 "-5:00",
1674 "-",
1675 "EST",
1676 "1973",
1677 "Apr",
1678 "29",
1679 "2:00",
1680 ])
1681 .unwrap();
1682 insta::assert_debug_snapshot!(zone, @r#"
1683 ZoneFirstP {
1684 name: ZoneNameP {
1685 name: "America/Menominee",
1686 },
1687 stdoff: ZoneStdoffP {
1688 dur: -18000s,
1689 },
1690 rules: None,
1691 format: Static {
1692 format: "EST",
1693 },
1694 until: Some(
1695 YearMonthDayTime {
1696 year: 1973,
1697 month: RuleInP {
1698 month: 4,
1699 },
1700 day: Day {
1701 day: 29,
1702 },
1703 duration: RuleAtP {
1704 dur: 7200s,
1705 suffix: None,
1706 },
1707 },
1708 ),
1709 }
1710 "#);
1711 }
1712
1713 #[test]
1714 fn parse_zone_first_err() {
1715 assert!(ZoneFirstP::parse(&[]).is_err());
1716 assert!(ZoneFirstP::parse(&["foo"]).is_err());
1717 assert!(ZoneFirstP::parse(&["foo", "-5"]).is_err());
1718 assert!(ZoneFirstP::parse(&["foo", "-5", "-"]).is_err());
1719 assert!(ZoneFirstP::parse(&[
1720 "foo", "-5", "-", "EST", "1973", "Apr", "29", "2:00", "w",
1721 ])
1722 .is_err());
1723 }
1724
1725 #[cfg(not(miri))]
1726 #[test]
1727 fn parse_zone_continuation_ok() {
1728 let zone: ZoneContinuationP =
1729 ZoneContinuationP::parse(&["-5:00", "-", "EST"]).unwrap();
1730 insta::assert_debug_snapshot!(zone, @r#"
1731 ZoneContinuationP {
1732 stdoff: ZoneStdoffP {
1733 dur: -18000s,
1734 },
1735 rules: None,
1736 format: Static {
1737 format: "EST",
1738 },
1739 until: None,
1740 }
1741 "#);
1742
1743 let zone: ZoneContinuationP = ZoneContinuationP::parse(&[
1744 "-5:00", "-", "EST", "1973", "Apr", "29", "2:00",
1745 ])
1746 .unwrap();
1747 insta::assert_debug_snapshot!(zone, @r#"
1748 ZoneContinuationP {
1749 stdoff: ZoneStdoffP {
1750 dur: -18000s,
1751 },
1752 rules: None,
1753 format: Static {
1754 format: "EST",
1755 },
1756 until: Some(
1757 YearMonthDayTime {
1758 year: 1973,
1759 month: RuleInP {
1760 month: 4,
1761 },
1762 day: Day {
1763 day: 29,
1764 },
1765 duration: RuleAtP {
1766 dur: 7200s,
1767 suffix: None,
1768 },
1769 },
1770 ),
1771 }
1772 "#);
1773 }
1774
1775 #[test]
1776 fn parse_zone_continuation_err() {
1777 assert!(ZoneContinuationP::parse(&[]).is_err());
1778 assert!(ZoneContinuationP::parse(&["-5"]).is_err());
1779 assert!(ZoneContinuationP::parse(&["-5", "-"]).is_err());
1780 assert!(ZoneContinuationP::parse(&[
1781 "-5", "-", "EST", "1973", "Apr", "29", "2:00", "w",
1782 ])
1783 .is_err());
1784 }
1785
1786 #[test]
1787 fn parse_link_ok() {
1788 let link: LinkP = LinkP::parse(&["Greenwich", "G_M_T"]).unwrap();
1789 assert_eq!(
1790 link,
1791 LinkP {
1792 target: ZoneNameP { name: "Greenwich".to_string() },
1793 name: ZoneNameP { name: "G_M_T".to_string() },
1794 }
1795 );
1796 }
1797
1798 #[test]
1799 fn parse_link_err() {
1800 assert!(LinkP::parse(&["Greenwich"]).is_err());
1801 assert!(LinkP::parse(&["Greenwich", "G_M_T", "foo"]).is_err());
1802 assert!(LinkP::parse(&["", "G_M_T"]).is_err());
1803 assert!(LinkP::parse(&["Greenwich", ""]).is_err());
1804 }
1805
1806 #[test]
1807 fn parse_rule_name_ok() {
1808 let name: RuleNameP = "US".parse().unwrap();
1809 assert_eq!(name, RuleNameP { name: "US".to_string() });
1810
1811 let name: RuleNameP = "U571".parse().unwrap();
1812 assert_eq!(name, RuleNameP { name: "U571".to_string() });
1813
1814 let name: RuleNameP = "U+-1".parse().unwrap();
1815 assert_eq!(name, RuleNameP { name: "U+-1".to_string() });
1816
1817 // We allow this because it's a little tricky to forbid them in
1818 // unquoted name fields only, and because it doesn't seem too
1819 // horrible to do so. Although if these characters are given special
1820 // significance in the future, we could wind up misinterpreting them.
1821 let name: RuleNameP =
1822 r#"U!$%&'()*,/:;<=>?@[\]^`{|}~S"#.parse().unwrap();
1823 assert_eq!(
1824 name,
1825 RuleNameP { name: r#"U!$%&'()*,/:;<=>?@[\]^`{|}~S"#.to_string() }
1826 );
1827 }
1828
1829 #[test]
1830 fn parse_rule_name_err() {
1831 assert!("".parse::<RuleNameP>().is_err());
1832 assert!("+U".parse::<RuleNameP>().is_err());
1833 assert!("-U".parse::<RuleNameP>().is_err());
1834 assert!("0U".parse::<RuleNameP>().is_err());
1835 assert!("9U".parse::<RuleNameP>().is_err());
1836 }
1837
1838 #[test]
1839 fn parse_rule_from_ok() {
1840 let to: RuleFromP = "2025".parse().unwrap();
1841 assert_eq!(to, RuleFromP { year: 2025 });
1842 let to: RuleFromP = "9999".parse().unwrap();
1843 assert_eq!(to, RuleFromP { year: 9999 });
1844 let to: RuleFromP = "-9999".parse().unwrap();
1845 assert_eq!(to, RuleFromP { year: -9999 });
1846 }
1847
1848 #[test]
1849 fn parse_rule_from_err() {
1850 assert!("10000".parse::<RuleFromP>().is_err());
1851 assert!("-10000".parse::<RuleFromP>().is_err());
1852 }
1853
1854 #[test]
1855 fn parse_rule_to_ok() {
1856 let to: RuleToP = "2025".parse().unwrap();
1857 assert_eq!(to, RuleToP::Year { year: 2025 });
1858 let to: RuleToP = "9999".parse().unwrap();
1859 assert_eq!(to, RuleToP::Year { year: 9999 });
1860 let to: RuleToP = "-9999".parse().unwrap();
1861 assert_eq!(to, RuleToP::Year { year: -9999 });
1862
1863 let to: RuleToP = "o".parse().unwrap();
1864 assert_eq!(to, RuleToP::Only);
1865 let to: RuleToP = "only".parse().unwrap();
1866 assert_eq!(to, RuleToP::Only);
1867
1868 let to: RuleToP = "m".parse().unwrap();
1869 assert_eq!(to, RuleToP::Max);
1870 let to: RuleToP = "max".parse().unwrap();
1871 assert_eq!(to, RuleToP::Max);
1872 let to: RuleToP = "maximum".parse().unwrap();
1873 assert_eq!(to, RuleToP::Max);
1874 }
1875
1876 #[test]
1877 fn parse_rule_to_err() {
1878 assert!("10000".parse::<RuleToP>().is_err());
1879 assert!("-10000".parse::<RuleToP>().is_err());
1880
1881 assert!("oonly".parse::<RuleToP>().is_err());
1882 assert!("ononly".parse::<RuleToP>().is_err());
1883 assert!("onlyy".parse::<RuleToP>().is_err());
1884 assert!("only ".parse::<RuleToP>().is_err());
1885
1886 assert!("mmaximum".parse::<RuleToP>().is_err());
1887 assert!("mamaximum".parse::<RuleToP>().is_err());
1888 assert!("maxmaximum".parse::<RuleToP>().is_err());
1889 assert!("maximumm".parse::<RuleToP>().is_err());
1890 assert!("maximum ".parse::<RuleToP>().is_err());
1891 }
1892
1893 #[test]
1894 fn parse_rule_in_ok() {
1895 let inn: RuleInP = "Ja".parse().unwrap();
1896 assert_eq!(inn.month, 1);
1897 let inn: RuleInP = "January".parse().unwrap();
1898 assert_eq!(inn.month, 1);
1899
1900 let inn: RuleInP = "F".parse().unwrap();
1901 assert_eq!(inn.month, 2);
1902 let inn: RuleInP = "February".parse().unwrap();
1903 assert_eq!(inn.month, 2);
1904
1905 let inn: RuleInP = "Mar".parse().unwrap();
1906 assert_eq!(inn.month, 3);
1907 let inn: RuleInP = "March".parse().unwrap();
1908 assert_eq!(inn.month, 3);
1909
1910 let inn: RuleInP = "Ap".parse().unwrap();
1911 assert_eq!(inn.month, 4);
1912 let inn: RuleInP = "April".parse().unwrap();
1913 assert_eq!(inn.month, 4);
1914
1915 let inn: RuleInP = "May".parse().unwrap();
1916 assert_eq!(inn.month, 5);
1917
1918 let inn: RuleInP = "Jun".parse().unwrap();
1919 assert_eq!(inn.month, 6);
1920 let inn: RuleInP = "June".parse().unwrap();
1921 assert_eq!(inn.month, 6);
1922
1923 let inn: RuleInP = "Jul".parse().unwrap();
1924 assert_eq!(inn.month, 7);
1925 let inn: RuleInP = "July".parse().unwrap();
1926 assert_eq!(inn.month, 7);
1927
1928 let inn: RuleInP = "Au".parse().unwrap();
1929 assert_eq!(inn.month, 8);
1930 let inn: RuleInP = "August".parse().unwrap();
1931 assert_eq!(inn.month, 8);
1932
1933 let inn: RuleInP = "S".parse().unwrap();
1934 assert_eq!(inn.month, 9);
1935 let inn: RuleInP = "September".parse().unwrap();
1936 assert_eq!(inn.month, 9);
1937
1938 let inn: RuleInP = "O".parse().unwrap();
1939 assert_eq!(inn.month, 10);
1940 let inn: RuleInP = "October".parse().unwrap();
1941 assert_eq!(inn.month, 10);
1942
1943 let inn: RuleInP = "N".parse().unwrap();
1944 assert_eq!(inn.month, 11);
1945 let inn: RuleInP = "November".parse().unwrap();
1946 assert_eq!(inn.month, 11);
1947
1948 let inn: RuleInP = "D".parse().unwrap();
1949 assert_eq!(inn.month, 12);
1950 let inn: RuleInP = "December".parse().unwrap();
1951 assert_eq!(inn.month, 12);
1952 }
1953
1954 #[test]
1955 fn parse_rule_in_err() {
1956 assert!("J".parse::<RuleInP>().is_err());
1957 assert!("Januaryy".parse::<RuleInP>().is_err());
1958 assert!("JJanuary".parse::<RuleInP>().is_err());
1959 assert!("JaJanuary".parse::<RuleInP>().is_err());
1960 }
1961
1962 #[test]
1963 fn parse_rule_on_ok() {
1964 // Specific day.
1965 let on: RuleOnP = "5".parse().unwrap();
1966 assert_eq!(on, RuleOnP::Day { day: 5 });
1967 let on: RuleOnP = "05".parse().unwrap();
1968 assert_eq!(on, RuleOnP::Day { day: 5 });
1969 let on: RuleOnP = "31".parse().unwrap();
1970 assert_eq!(on, RuleOnP::Day { day: 31 });
1971
1972 // Last weekday of month.
1973 let on: RuleOnP = "lastSu".parse().unwrap();
1974 assert_eq!(on, RuleOnP::Last { weekday: Weekday::Sunday });
1975 let on: RuleOnP = "lastSun".parse().unwrap();
1976 assert_eq!(on, RuleOnP::Last { weekday: Weekday::Sunday });
1977 let on: RuleOnP = "lastSund".parse().unwrap();
1978 assert_eq!(on, RuleOnP::Last { weekday: Weekday::Sunday });
1979 let on: RuleOnP = "lastSunda".parse().unwrap();
1980 assert_eq!(on, RuleOnP::Last { weekday: Weekday::Sunday });
1981 let on: RuleOnP = "lastSunday".parse().unwrap();
1982 assert_eq!(on, RuleOnP::Last { weekday: Weekday::Sunday });
1983
1984 // Weekday on or before a day of the month.
1985 let on: RuleOnP = "Sun<=25".parse().unwrap();
1986 assert_eq!(
1987 on,
1988 RuleOnP::OnOrBefore { weekday: Weekday::Sunday, day: 25 }
1989 );
1990 let on: RuleOnP = "Sunday<=25".parse().unwrap();
1991 assert_eq!(
1992 on,
1993 RuleOnP::OnOrBefore { weekday: Weekday::Sunday, day: 25 }
1994 );
1995
1996 // Weekday on or after a day of the month.
1997 let on: RuleOnP = "Sun>=8".parse().unwrap();
1998 assert_eq!(
1999 on,
2000 RuleOnP::OnOrAfter { weekday: Weekday::Sunday, day: 8 }
2001 );
2002 let on: RuleOnP = "Sunday>=8".parse().unwrap();
2003 assert_eq!(
2004 on,
2005 RuleOnP::OnOrAfter { weekday: Weekday::Sunday, day: 8 }
2006 );
2007 }
2008
2009 #[test]
2010 fn parse_rule_on_err() {
2011 // Invalid specific day.
2012 assert!("0".parse::<RuleOnP>().is_err());
2013 assert!("00000".parse::<RuleOnP>().is_err());
2014 assert!("00000000000000000000000000".parse::<RuleOnP>().is_err());
2015 assert!("32".parse::<RuleOnP>().is_err());
2016
2017 // Invalid last weekday of month.
2018 assert!("lastS".parse::<RuleOnP>().is_err());
2019 assert!("lastSSunday".parse::<RuleOnP>().is_err());
2020 assert!("lastSuSunday".parse::<RuleOnP>().is_err());
2021 assert!("lastSundayy".parse::<RuleOnP>().is_err());
2022 assert!("lastZ".parse::<RuleOnP>().is_err());
2023 assert!("last".parse::<RuleOnP>().is_err());
2024
2025 // Invalid weekday on or before a day of the month.
2026 assert!("S<=25".parse::<RuleOnP>().is_err());
2027 assert!("Sun<=0".parse::<RuleOnP>().is_err());
2028 assert!("Sun<=32".parse::<RuleOnP>().is_err());
2029
2030 // Invalid weekday on or after a day of the month.
2031 assert!("S>=25".parse::<RuleOnP>().is_err());
2032 assert!("Sun>=0".parse::<RuleOnP>().is_err());
2033 assert!("Sun>=32".parse::<RuleOnP>().is_err());
2034
2035 // Unrecognized format.
2036 assert!("abc".parse::<RuleOnP>().is_err());
2037 assert!("Sun<25".parse::<RuleOnP>().is_err());
2038 assert!("Sun>25".parse::<RuleOnP>().is_err());
2039 assert!("Sun < 25".parse::<RuleOnP>().is_err());
2040 assert!("Sun > 25".parse::<RuleOnP>().is_err());
2041 assert!("Sun <= 25".parse::<RuleOnP>().is_err());
2042 assert!("Sun >= 25".parse::<RuleOnP>().is_err());
2043 }
2044
2045 #[test]
2046 fn parse_rule_at_ok() {
2047 let at: RuleAtP = "5".parse().unwrap();
2048 assert_eq!(at, RuleAtP { dur: td(5 * 60 * 60, 0), suffix: None });
2049
2050 let at: RuleAtP = "5w".parse().unwrap();
2051 assert_eq!(
2052 at,
2053 RuleAtP {
2054 dur: td(5 * 60 * 60, 0),
2055 suffix: Some(RuleAtSuffixP::Wall)
2056 }
2057 );
2058
2059 let at: RuleAtP = "-5w".parse().unwrap();
2060 assert_eq!(
2061 at,
2062 RuleAtP {
2063 dur: td(-5 * 60 * 60, 0),
2064 suffix: Some(RuleAtSuffixP::Wall)
2065 }
2066 );
2067
2068 let at: RuleAtP = "-".parse().unwrap();
2069 assert_eq!(at, RuleAtP { dur: td(0, 0), suffix: None });
2070
2071 let at: RuleAtP = "-s".parse().unwrap();
2072 assert_eq!(
2073 at,
2074 RuleAtP { dur: td(0, 0), suffix: Some(RuleAtSuffixP::Standard) }
2075 );
2076 }
2077
2078 #[test]
2079 fn parse_rule_at_err() {
2080 assert!("".parse::<RuleAtP>().is_err());
2081 assert!("w".parse::<RuleAtP>().is_err());
2082 }
2083
2084 #[test]
2085 fn parse_rule_at_suffix_ok() {
2086 let suffix: RuleAtSuffixP = "w".parse().unwrap();
2087 assert_eq!(suffix, RuleAtSuffixP::Wall);
2088 let suffix: RuleAtSuffixP = "s".parse().unwrap();
2089 assert_eq!(suffix, RuleAtSuffixP::Standard);
2090 let suffix: RuleAtSuffixP = "u".parse().unwrap();
2091 assert_eq!(suffix, RuleAtSuffixP::Universal);
2092 let suffix: RuleAtSuffixP = "g".parse().unwrap();
2093 assert_eq!(suffix, RuleAtSuffixP::Universal);
2094 let suffix: RuleAtSuffixP = "z".parse().unwrap();
2095 assert_eq!(suffix, RuleAtSuffixP::Universal);
2096 }
2097
2098 #[test]
2099 fn parse_rule_at_suffix_err() {
2100 assert!("W".parse::<RuleAtSuffixP>().is_err());
2101 assert!("w ".parse::<RuleAtSuffixP>().is_err());
2102 assert!(" w".parse::<RuleAtSuffixP>().is_err());
2103 assert!("ww".parse::<RuleAtSuffixP>().is_err());
2104 assert!("".parse::<RuleAtSuffixP>().is_err());
2105 }
2106
2107 #[test]
2108 fn parse_rule_save_ok() {
2109 let at: RuleSaveP = "5".parse().unwrap();
2110 assert_eq!(at, RuleSaveP { dur: td(5 * 60 * 60, 0), suffix: None });
2111
2112 let at: RuleSaveP = "5s".parse().unwrap();
2113 assert_eq!(
2114 at,
2115 RuleSaveP {
2116 dur: td(5 * 60 * 60, 0),
2117 suffix: Some(RuleSaveSuffixP::Standard)
2118 }
2119 );
2120
2121 let at: RuleSaveP = "-5s".parse().unwrap();
2122 assert_eq!(
2123 at,
2124 RuleSaveP {
2125 dur: td(-5 * 60 * 60, 0),
2126 suffix: Some(RuleSaveSuffixP::Standard)
2127 }
2128 );
2129
2130 let at: RuleSaveP = "-".parse().unwrap();
2131 assert_eq!(at, RuleSaveP { dur: td(0, 0), suffix: None });
2132
2133 let at: RuleSaveP = "-s".parse().unwrap();
2134 assert_eq!(
2135 at,
2136 RuleSaveP {
2137 dur: td(0, 0),
2138 suffix: Some(RuleSaveSuffixP::Standard)
2139 }
2140 );
2141 }
2142
2143 #[test]
2144 fn parse_rule_save_err() {
2145 assert!("".parse::<RuleSaveP>().is_err());
2146 assert!("s".parse::<RuleSaveP>().is_err());
2147 }
2148
2149 #[test]
2150 fn parse_rule_save_suffix_ok() {
2151 let suffix: RuleSaveSuffixP = "s".parse().unwrap();
2152 assert_eq!(suffix, RuleSaveSuffixP::Standard);
2153 let suffix: RuleSaveSuffixP = "d".parse().unwrap();
2154 assert_eq!(suffix, RuleSaveSuffixP::Dst);
2155 }
2156
2157 #[test]
2158 fn parse_rule_save_suffix_err() {
2159 assert!("S".parse::<RuleSaveSuffixP>().is_err());
2160 assert!("s ".parse::<RuleSaveSuffixP>().is_err());
2161 assert!(" s".parse::<RuleSaveSuffixP>().is_err());
2162 assert!("ss".parse::<RuleSaveSuffixP>().is_err());
2163 assert!("".parse::<RuleSaveSuffixP>().is_err());
2164 }
2165
2166 #[test]
2167 fn parse_rule_letters_ok() {
2168 let letters: RuleLettersP = "-".parse().unwrap();
2169 assert_eq!(letters, RuleLettersP { part: "".to_string() });
2170
2171 let letters: RuleLettersP = "S".parse().unwrap();
2172 assert_eq!(letters, RuleLettersP { part: "S".to_string() });
2173
2174 let letters: RuleLettersP = "D".parse().unwrap();
2175 assert_eq!(letters, RuleLettersP { part: "D".to_string() });
2176 }
2177
2178 #[test]
2179 fn parse_zone_name_ok() {
2180 let name: ZoneNameP = "foo".parse().unwrap();
2181 assert_eq!(name, ZoneNameP { name: "foo".to_string() });
2182
2183 let name: ZoneNameP = "foo/.../bar".parse().unwrap();
2184 assert_eq!(name, ZoneNameP { name: "foo/.../bar".to_string() });
2185
2186 let name: ZoneNameP = "foo bar".parse().unwrap();
2187 assert_eq!(name, ZoneNameP { name: "foo bar".to_string() });
2188 }
2189
2190 #[test]
2191 fn parse_zone_name_err() {
2192 assert!("".parse::<ZoneNameP>().is_err());
2193 assert!("foo/./bar".parse::<ZoneNameP>().is_err());
2194 assert!("foo/../bar".parse::<ZoneNameP>().is_err());
2195 }
2196
2197 #[test]
2198 fn parse_zone_stdoff_ok() {
2199 let stdoff: ZoneStdoffP = "5".parse().unwrap();
2200 assert_eq!(stdoff, ZoneStdoffP { dur: td(5 * 60 * 60, 0) });
2201
2202 let stdoff: ZoneStdoffP = "-5".parse().unwrap();
2203 assert_eq!(stdoff, ZoneStdoffP { dur: td(-5 * 60 * 60, 0) });
2204 }
2205
2206 #[test]
2207 fn parse_zone_stdoff_err() {
2208 assert!("".parse::<ZoneStdoffP>().is_err());
2209 assert!("a".parse::<ZoneStdoffP>().is_err());
2210 assert!("999999999999999999".parse::<ZoneStdoffP>().is_err());
2211 }
2212
2213 #[test]
2214 fn parse_zone_rules_ok() {
2215 let rules: ZoneRulesP = "-".parse().unwrap();
2216 assert_eq!(rules, ZoneRulesP::None);
2217
2218 let rules: ZoneRulesP = "foo".parse().unwrap();
2219 assert_eq!(
2220 rules,
2221 ZoneRulesP::Named(RuleNameP { name: "foo".to_string() })
2222 );
2223
2224 let rules: ZoneRulesP = "5".parse().unwrap();
2225 assert_eq!(
2226 rules,
2227 ZoneRulesP::Save(RuleSaveP {
2228 dur: td(5 * 60 * 60, 0),
2229 suffix: None,
2230 })
2231 );
2232 let rules: ZoneRulesP = "-5".parse().unwrap();
2233 assert_eq!(
2234 rules,
2235 ZoneRulesP::Save(RuleSaveP {
2236 dur: td(-5 * 60 * 60, 0),
2237 suffix: None,
2238 })
2239 );
2240 let rules: ZoneRulesP = "-1d".parse().unwrap();
2241 assert_eq!(
2242 rules,
2243 ZoneRulesP::Save(RuleSaveP {
2244 dur: td(-1 * 60 * 60, 0),
2245 suffix: Some(RuleSaveSuffixP::Dst),
2246 })
2247 );
2248 }
2249
2250 #[test]
2251 fn parse_zone_rules_err() {
2252 assert!("".parse::<ZoneRulesP>().is_err());
2253 assert!("-foo".parse::<ZoneRulesP>().is_err());
2254 assert!("+foo".parse::<ZoneRulesP>().is_err());
2255 assert!("+5".parse::<ZoneRulesP>().is_err());
2256 }
2257
2258 #[test]
2259 fn parse_zone_format_ok() {
2260 let format: ZoneFormatP = "E%sT".parse().unwrap();
2261 assert_eq!(
2262 format,
2263 ZoneFormatP::Variable {
2264 before: "E".to_string(),
2265 after: "T".to_string(),
2266 }
2267 );
2268 let format: ZoneFormatP = "AB%sXYZ".parse().unwrap();
2269 assert_eq!(
2270 format,
2271 ZoneFormatP::Variable {
2272 before: "AB".to_string(),
2273 after: "XYZ".to_string(),
2274 }
2275 );
2276
2277 let format: ZoneFormatP = "%z".parse().unwrap();
2278 assert_eq!(format, ZoneFormatP::Offset,);
2279
2280 let format: ZoneFormatP = "EST/EDT".parse().unwrap();
2281 assert_eq!(
2282 format,
2283 ZoneFormatP::Pair {
2284 std: "EST".to_string(),
2285 dst: "EDT".to_string(),
2286 }
2287 );
2288 let format: ZoneFormatP = "+EST/-EDT".parse().unwrap();
2289 assert_eq!(
2290 format,
2291 ZoneFormatP::Pair {
2292 std: "+EST".to_string(),
2293 dst: "-EDT".to_string(),
2294 }
2295 );
2296
2297 let format: ZoneFormatP = "GMT".parse().unwrap();
2298 assert_eq!(format, ZoneFormatP::Static { format: "GMT".to_string() });
2299 }
2300
2301 #[test]
2302 fn parse_zone_format_err() {
2303 assert!("".parse::<ZoneFormatP>().is_err());
2304 assert!("%s".parse::<ZoneFormatP>().is_err());
2305 assert!("A%s".parse::<ZoneFormatP>().is_err());
2306 assert!("%sZ".parse::<ZoneFormatP>().is_err());
2307 assert!("A/B/C".parse::<ZoneFormatP>().is_err());
2308 assert!("A&Z".parse::<ZoneFormatP>().is_err());
2309 assert!("A&B/YZ".parse::<ZoneFormatP>().is_err());
2310 assert!("AB/Y&Z".parse::<ZoneFormatP>().is_err());
2311 assert!("A&%sZ".parse::<ZoneFormatP>().is_err());
2312 assert!("A%s&Z".parse::<ZoneFormatP>().is_err());
2313 assert!("AB%zYZ".parse::<ZoneFormatP>().is_err());
2314 }
2315
2316 #[test]
2317 fn parse_zone_until_ok() {
2318 let until = ZoneUntilP::parse(&["2025"]).unwrap();
2319 assert_eq!(until, ZoneUntilP::Year { year: 2025 },);
2320 let until = ZoneUntilP::parse(&["9999"]).unwrap();
2321 assert_eq!(until, ZoneUntilP::Year { year: 9999 },);
2322 let until = ZoneUntilP::parse(&["-9999"]).unwrap();
2323 assert_eq!(until, ZoneUntilP::Year { year: -9999 },);
2324
2325 let until = ZoneUntilP::parse(&["2025", "Jan"]).unwrap();
2326 assert_eq!(
2327 until,
2328 ZoneUntilP::YearMonth { year: 2025, month: RuleInP { month: 1 } },
2329 );
2330
2331 let until = ZoneUntilP::parse(&["2025", "Jan", "5"]).unwrap();
2332 assert_eq!(
2333 until,
2334 ZoneUntilP::YearMonthDay {
2335 year: 2025,
2336 month: RuleInP { month: 1 },
2337 day: RuleOnP::Day { day: 5 },
2338 },
2339 );
2340 let until = ZoneUntilP::parse(&["2025", "Jan", "lastSun"]).unwrap();
2341 assert_eq!(
2342 until,
2343 ZoneUntilP::YearMonthDay {
2344 year: 2025,
2345 month: RuleInP { month: 1 },
2346 day: RuleOnP::Last { weekday: Weekday::Sunday },
2347 },
2348 );
2349
2350 let until =
2351 ZoneUntilP::parse(&["2025", "Jan", "lastSun", "-"]).unwrap();
2352 assert_eq!(
2353 until,
2354 ZoneUntilP::YearMonthDayTime {
2355 year: 2025,
2356 month: RuleInP { month: 1 },
2357 day: RuleOnP::Last { weekday: Weekday::Sunday },
2358 duration: RuleAtP { dur: td(0, 0), suffix: None },
2359 },
2360 );
2361 let until =
2362 ZoneUntilP::parse(&["2025", "Jan", "lastSun", "5"]).unwrap();
2363 assert_eq!(
2364 until,
2365 ZoneUntilP::YearMonthDayTime {
2366 year: 2025,
2367 month: RuleInP { month: 1 },
2368 day: RuleOnP::Last { weekday: Weekday::Sunday },
2369 duration: RuleAtP { dur: td(5 * 60 * 60, 0), suffix: None },
2370 },
2371 );
2372 let until =
2373 ZoneUntilP::parse(&["2025", "Jan", "lastSun", "-5"]).unwrap();
2374 assert_eq!(
2375 until,
2376 ZoneUntilP::YearMonthDayTime {
2377 year: 2025,
2378 month: RuleInP { month: 1 },
2379 day: RuleOnP::Last { weekday: Weekday::Sunday },
2380 duration: RuleAtP { dur: td(-5 * 60 * 60, 0), suffix: None },
2381 },
2382 );
2383 let until =
2384 ZoneUntilP::parse(&["2025", "Jan", "lastSun", "1:1:1.000000001"])
2385 .unwrap();
2386 assert_eq!(
2387 until,
2388 ZoneUntilP::YearMonthDayTime {
2389 year: 2025,
2390 month: RuleInP { month: 1 },
2391 day: RuleOnP::Last { weekday: Weekday::Sunday },
2392 duration: RuleAtP { dur: td(3661, 1), suffix: None },
2393 },
2394 );
2395 let until =
2396 ZoneUntilP::parse(&["2025", "Jan", "lastSun", "5u"]).unwrap();
2397 assert_eq!(
2398 until,
2399 ZoneUntilP::YearMonthDayTime {
2400 year: 2025,
2401 month: RuleInP { month: 1 },
2402 day: RuleOnP::Last { weekday: Weekday::Sunday },
2403 duration: RuleAtP {
2404 dur: td(5 * 60 * 60, 0),
2405 suffix: Some(RuleAtSuffixP::Universal),
2406 },
2407 },
2408 );
2409 }
2410
2411 #[test]
2412 fn parse_zone_until_err() {
2413 assert!(ZoneUntilP::parse(&[]).is_err());
2414
2415 assert!(ZoneUntilP::parse(&["10000"]).is_err());
2416 assert!(ZoneUntilP::parse(&["-10000"]).is_err());
2417
2418 assert!(ZoneUntilP::parse(&["2025", "J"]).is_err());
2419 assert!(ZoneUntilP::parse(&["2025", "Z"]).is_err());
2420
2421 assert!(ZoneUntilP::parse(&["2025", "Jan", "lastS"]).is_err());
2422 assert!(ZoneUntilP::parse(&["2025", "Jan", "0"]).is_err());
2423 assert!(ZoneUntilP::parse(&["2025", "Jan", "32"]).is_err());
2424
2425 assert!(ZoneUntilP::parse(&["2025", "Jan", "lastSun", "w"]).is_err());
2426 assert!(ZoneUntilP::parse(&[
2427 "2025",
2428 "Jan",
2429 "lastSun",
2430 "1:1:1.0000000001"
2431 ])
2432 .is_err());
2433 }
2434
2435 #[test]
2436 fn parse_year_ok() {
2437 assert_eq!(parse_year("0").unwrap(), 0);
2438 assert_eq!(parse_year("1").unwrap(), 1);
2439 assert_eq!(parse_year("-1").unwrap(), -1);
2440 assert_eq!(parse_year("2025").unwrap(), 2025);
2441 assert_eq!(parse_year("9999").unwrap(), 9999);
2442 assert_eq!(parse_year("-9999").unwrap(), -9999);
2443 }
2444
2445 #[test]
2446 fn parse_year_err() {
2447 assert!(parse_year("-10000").is_err());
2448 assert!(parse_year("10000").is_err());
2449 assert!(parse_year("+2025").is_err());
2450 assert!(parse_year(" 2025").is_err());
2451 assert!(parse_year("2025 ").is_err());
2452 assert!(parse_year("9999999999999999999999999999").is_err());
2453 }
2454
2455 #[test]
2456 fn parse_duration_ok() {
2457 assert_eq!(parse_duration("-").unwrap(), td(0, 0));
2458 assert_eq!(parse_duration("0").unwrap(), td(0, 0));
2459 assert_eq!(parse_duration("-0").unwrap(), td(0, 0));
2460
2461 assert_eq!(parse_duration("1").unwrap(), td(3600, 0));
2462 assert_eq!(parse_duration("1:1").unwrap(), td(3660, 0));
2463 assert_eq!(parse_duration("1:1:1").unwrap(), td(3661, 0));
2464 assert_eq!(parse_duration("1:1:1.1").unwrap(), td(3661, 100_000_000));
2465 assert_eq!(
2466 parse_duration("1:1:1.123456789").unwrap(),
2467 td(3661, 123_456_789)
2468 );
2469 assert_eq!(parse_duration("0:1:0").unwrap(), td(60, 0));
2470 assert_eq!(parse_duration("0:0:1").unwrap(), td(1, 0));
2471 assert_eq!(parse_duration("0:0:0.000000001").unwrap(), td(0, 1));
2472 assert_eq!(parse_duration("0:0:0.000000000").unwrap(), td(0, 0));
2473
2474 assert_eq!(parse_duration("-1").unwrap(), td(-3600, 0));
2475 assert_eq!(parse_duration("-1:1").unwrap(), td(-3660, 0));
2476 assert_eq!(parse_duration("-1:1:1").unwrap(), td(-3661, 0));
2477 assert_eq!(
2478 parse_duration("-1:1:1.1").unwrap(),
2479 td(-3661, -100_000_000)
2480 );
2481 assert_eq!(
2482 parse_duration("-1:1:1.123456789").unwrap(),
2483 td(-3661, -123_456_789)
2484 );
2485 assert_eq!(parse_duration("-0:1:0").unwrap(), td(-60, 0));
2486 assert_eq!(parse_duration("-0:0:1").unwrap(), td(-1, 0));
2487 assert_eq!(parse_duration("-0:0:0.000000001").unwrap(), td(0, -1));
2488 }
2489
2490 #[test]
2491 fn parse_duration_err() {
2492 assert!(parse_duration("").is_err());
2493 assert!(parse_duration(" ").is_err());
2494 assert!(parse_duration("a").is_err());
2495 assert!(parse_duration("999999999999999").is_err());
2496 assert!(parse_duration("1:").is_err());
2497 assert!(parse_duration("1:a").is_err());
2498 assert!(parse_duration("1:60").is_err());
2499 assert!(parse_duration("1:01:").is_err());
2500 assert!(parse_duration("1:01:60").is_err());
2501 assert!(parse_duration("1:01:59.").is_err());
2502 assert!(parse_duration("1:01:59.0000000001").is_err());
2503 assert!(parse_duration("1:01:59.0000000000").is_err());
2504 assert!(parse_duration("1:01:59.000000001a").is_err());
2505 assert!(parse_duration("1:01:59.000000001 ").is_err());
2506 assert!(parse_duration("1::59").is_err());
2507 assert!(parse_duration("1::.1").is_err());
2508 assert!(parse_duration("::").is_err());
2509 // Maybe we should support this?
2510 assert!(parse_duration("+1").is_err());
2511
2512 // Tricky cases where the number of hours is at the limit, but there
2513 // are other units present.
2514 assert!(parse_duration("175307616").is_ok());
2515 assert!(parse_duration("175307617").is_err());
2516 assert!(parse_duration("175307616:01").is_ok());
2517 assert!(parse_duration("175307616:00:01").is_ok());
2518 assert!(parse_duration("175307616:00:00.999999999").is_ok());
2519 // Same as above, but for negative hours.
2520 assert!(parse_duration("-175307616").is_ok());
2521 assert!(parse_duration("-175307617").is_err());
2522 assert!(parse_duration("-175307616:01").is_ok());
2523 assert!(parse_duration("-175307616:00:01").is_ok());
2524 assert!(parse_duration("-175307616:00:00.999999999").is_ok());
2525 }
2526
2527 #[test]
2528 fn parse_day_ok() {
2529 assert_eq!(parse_day("1").unwrap(), 1);
2530 assert_eq!(parse_day("2").unwrap(), 2);
2531 assert_eq!(parse_day("20").unwrap(), 20);
2532 assert_eq!(parse_day("30").unwrap(), 30);
2533 assert_eq!(parse_day("31").unwrap(), 31);
2534
2535 assert_eq!(parse_day("01").unwrap(), 1);
2536 assert_eq!(parse_day("00000001").unwrap(), 1);
2537 assert_eq!(parse_day("0000000000000000000001").unwrap(), 1);
2538 }
2539
2540 #[test]
2541 fn parse_day_err() {
2542 assert!(parse_day("").is_err());
2543 assert!(parse_day("0").is_err());
2544 assert!(parse_day("00").is_err());
2545 assert!(parse_day("32").is_err());
2546 assert!(parse_day("032").is_err());
2547 }
2548
2549 #[test]
2550 fn parse_weekday_ok() {
2551 assert_eq!(parse_weekday("M").unwrap(), Weekday::Monday);
2552 assert_eq!(parse_weekday("Monday").unwrap(), Weekday::Monday);
2553
2554 assert_eq!(parse_weekday("Tu").unwrap(), Weekday::Tuesday);
2555 assert_eq!(parse_weekday("Tuesday").unwrap(), Weekday::Tuesday);
2556
2557 assert_eq!(parse_weekday("W").unwrap(), Weekday::Wednesday);
2558 assert_eq!(parse_weekday("Wednesday").unwrap(), Weekday::Wednesday);
2559
2560 assert_eq!(parse_weekday("Th").unwrap(), Weekday::Thursday);
2561 assert_eq!(parse_weekday("Thursday").unwrap(), Weekday::Thursday);
2562
2563 assert_eq!(parse_weekday("F").unwrap(), Weekday::Friday);
2564 assert_eq!(parse_weekday("Friday").unwrap(), Weekday::Friday);
2565
2566 assert_eq!(parse_weekday("Sa").unwrap(), Weekday::Saturday);
2567 assert_eq!(parse_weekday("Saturday").unwrap(), Weekday::Saturday);
2568
2569 assert_eq!(parse_weekday("Su").unwrap(), Weekday::Sunday);
2570 assert_eq!(parse_weekday("Sunday").unwrap(), Weekday::Sunday);
2571 }
2572
2573 #[test]
2574 fn parse_weekday_err() {
2575 assert!(parse_weekday("S").is_err());
2576 assert!(parse_weekday("Sundayy").is_err());
2577 assert!(parse_weekday("SSunday").is_err());
2578 assert!(parse_weekday("SuSunday").is_err());
2579 }
2580
2581 #[test]
2582 fn parse_fields_ok() {
2583 let mut fields: Vec<&str> = vec![];
2584
2585 parse_fields("", &mut fields).unwrap();
2586 assert_eq!(fields, Vec::<&str>::new());
2587
2588 parse_fields("# foo bar baz", &mut fields).unwrap();
2589 assert_eq!(fields, Vec::<&str>::new());
2590
2591 parse_fields("a", &mut fields).unwrap();
2592 assert_eq!(fields, vec!["a"]);
2593
2594 parse_fields("foo", &mut fields).unwrap();
2595 assert_eq!(fields, vec!["foo"]);
2596
2597 parse_fields("foo#foo", &mut fields).unwrap();
2598 assert_eq!(fields, vec!["foo"]);
2599
2600 parse_fields(r#""foo""#, &mut fields).unwrap();
2601 assert_eq!(fields, vec!["foo"]);
2602
2603 parse_fields(r#"fo"o"#, &mut fields).unwrap();
2604 assert_eq!(fields, vec![r#"fo"o"#]);
2605
2606 parse_fields("foo bar", &mut fields).unwrap();
2607 assert_eq!(fields, vec!["foo", "bar"]);
2608
2609 parse_fields(" \x0C\t\x0B foo \t bar ", &mut fields).unwrap();
2610 assert_eq!(fields, vec!["foo", "bar"]);
2611
2612 parse_fields(r#"foo "bar" baz"#, &mut fields).unwrap();
2613 assert_eq!(fields, vec!["foo", "bar", "baz"]);
2614
2615 parse_fields(r#"foo"bar baz"quux"#, &mut fields).unwrap();
2616 assert_eq!(fields, vec![r#"foo"bar"#, r#"baz"quux"#]);
2617
2618 // I believe this is the only way to encode an empty field. It's
2619 // unclear whether this is allowed or not, but it seems fine to allow
2620 // it.
2621 parse_fields(r#""""#, &mut fields).unwrap();
2622 assert_eq!(fields, vec![""]);
2623 }
2624
2625 #[test]
2626 fn parse_fields_err() {
2627 let mut fields: Vec<&str> = vec![];
2628
2629 assert!(parse_fields(r#""foo"bar"#, &mut fields).is_err());
2630 assert!(parse_fields(r#""foo"#, &mut fields).is_err());
2631 assert!(parse_fields("foo\0", &mut fields).is_err());
2632
2633 // Test the line length check.
2634 let fits = "a".repeat(2047);
2635 assert!(parse_fields(&fits, &mut fields).is_ok());
2636 let toobig = "a".repeat(2048);
2637 assert!(parse_fields(&toobig, &mut fields).is_err());
2638 }
2639 }