Debian Codegraph @

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