1use crate::{Error, EvaluationError, Map, Value};
5use core::fmt;
6
7const SECONDS_PER_DAY: i64 = 86_400;
9
10const MICROS_PER_SECOND: u32 = 1_000_000;
12
13fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
16 let year = i64::from(year) - i64::from(month <= 2);
17 let era = year.div_euclid(400);
18 let year_of_era = year.rem_euclid(400);
19 let month_from_march = (i64::from(month) + 9) % 12;
20 let day_of_year = (153 * month_from_march + 2) / 5 + i64::from(day) - 1;
21 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
22 era * 146_097 + day_of_era - 719_468
23}
24
25fn civil_from_days(days: i64) -> Option<Date> {
28 let shifted = days.checked_add(719_468)?;
29 let era = shifted.div_euclid(146_097);
30 let day_of_era = shifted.rem_euclid(146_097);
31 let year_of_era =
32 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
33 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
34 let month_from_march = (5 * day_of_year + 2) / 153;
35 let day = day_of_year - (153 * month_from_march + 2) / 5 + 1;
36 let month = if month_from_march < 10 {
37 month_from_march + 3
38 } else {
39 month_from_march - 9
40 };
41 let year = era
42 .checked_mul(400)?
43 .checked_add(year_of_era + i64::from(month <= 2))?;
44 Some(Date {
45 year: i32::try_from(year).ok()?,
46 month: u8::try_from(month).ok()?,
47 day: u8::try_from(day).ok()?,
48 })
49}
50
51fn is_leap_year(year: i32) -> bool {
52 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
53}
54
55fn days_in_month(year: i32, month: u32) -> u32 {
56 match month {
57 2 if is_leap_year(year) => 29,
58 2 => 28,
59 4 | 6 | 9 | 11 => 30,
60 _ => 31,
61 }
62}
63
64#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct Date {
78 year: i32,
79 month: u8,
80 day: u8,
81}
82
83impl Date {
84 pub fn new(year: i32, month: u32, day: u32) -> Option<Date> {
95 if !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
96 return None;
97 }
98 Some(Date {
99 year,
100 month: u8::try_from(month).ok()?,
101 day: u8::try_from(day).ok()?,
102 })
103 }
104
105 pub fn year(&self) -> i32 {
113 self.year
114 }
115
116 pub fn month(&self) -> u32 {
124 u32::from(self.month)
125 }
126
127 pub fn day(&self) -> u32 {
135 u32::from(self.day)
136 }
137
138 pub(crate) fn days(self) -> i64 {
140 days_from_civil(self.year, self.month(), self.day())
141 }
142
143 pub(crate) fn from_days(days: i64) -> Option<Date> {
146 civil_from_days(days)
147 }
148
149 pub(crate) fn parse(text: &str) -> Option<Date> {
152 let mut parts = Digits::new(text);
153 let year = parts.number(4)?;
154 parts.literal(b'-')?;
155 let month = parts.number(2)?;
156 parts.literal(b'-')?;
157 let day = parts.number(2)?;
158 parts.end()?;
159 Date::new(i32::try_from(year).ok()?, month, day)
160 }
161}
162
163impl fmt::Display for Date {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 let sign = if self.year < 0 { "-" } else { "" };
168 write!(
169 f,
170 "{sign}{:04}-{:02}-{:02}",
171 self.year.unsigned_abs(),
172 self.month,
173 self.day
174 )
175 }
176}
177
178impl fmt::Debug for Date {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 write!(f, "Date({self})")
181 }
182}
183
184#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
203pub struct DateTime {
204 date: Date,
205 second_of_day: u32,
206 microsecond: u32,
207}
208
209impl DateTime {
210 pub fn new(
223 date: Date,
224 hour: u32,
225 minute: u32,
226 second: u32,
227 microsecond: u32,
228 ) -> Option<DateTime> {
229 if hour > 23 || minute > 59 || second > 59 || microsecond >= MICROS_PER_SECOND {
230 return None;
231 }
232 Some(DateTime {
233 date,
234 second_of_day: hour * 3600 + minute * 60 + second,
235 microsecond,
236 })
237 }
238
239 pub fn from_unix(seconds: i64, microsecond: u32) -> Option<DateTime> {
251 if microsecond >= MICROS_PER_SECOND {
252 return None;
253 }
254 Some(DateTime {
255 date: civil_from_days(seconds.div_euclid(SECONDS_PER_DAY))?,
256 second_of_day: u32::try_from(seconds.rem_euclid(SECONDS_PER_DAY)).ok()?,
257 microsecond,
258 })
259 }
260
261 pub fn unix_seconds(&self) -> i64 {
271 self.date.days() * SECONDS_PER_DAY + i64::from(self.second_of_day)
272 }
273
274 pub fn microsecond(&self) -> u32 {
283 self.microsecond
284 }
285
286 pub fn date(&self) -> Date {
295 self.date
296 }
297
298 pub fn hour(&self) -> u32 {
306 self.second_of_day / 3600
307 }
308
309 pub fn minute(&self) -> u32 {
317 self.second_of_day % 3600 / 60
318 }
319
320 pub fn second(&self) -> u32 {
328 self.second_of_day % 60
329 }
330
331 pub(crate) fn parse(text: &str) -> Option<DateTime> {
338 let mut parts = Digits::new(text);
339 let year = parts.number(4)?;
340 parts.literal(b'-')?;
341 let month = parts.number(2)?;
342 parts.literal(b'-')?;
343 let day = parts.number(2)?;
344 if parts.literal(b'T').is_none() {
345 parts.literal(b' ')?;
346 }
347 let hour = parts.number(2)?;
348 parts.literal(b':')?;
349 let minute = parts.number(2)?;
350 parts.literal(b':')?;
351 let second = parts.number(2)?;
352 let microsecond = match parts.peek() {
353 Some(b'.' | b',') => {
354 parts.skip();
355 parts.fraction()?
356 }
357 _ => 0,
358 };
359 let offset = parts.offset()?;
360 parts.end()?;
361 let date = Date::new(i32::try_from(year).ok()?, month, day)?;
362 let local = DateTime::new(date, hour, minute, second, microsecond)?;
363 let instant = DateTime::from_unix(local.unix_seconds() - offset, microsecond)?;
364 (0..=9999).contains(&instant.date.year).then_some(instant)
365 }
366}
367
368impl fmt::Display for DateTime {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 write!(
373 f,
374 "{}T{:02}:{:02}:{:02}",
375 self.date,
376 self.hour(),
377 self.minute(),
378 self.second()
379 )?;
380 if self.microsecond != 0 {
381 write!(f, ".{:06}", self.microsecond)?;
382 }
383 f.write_str("Z")
384 }
385}
386
387impl fmt::Debug for DateTime {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 write!(f, "DateTime({self})")
390 }
391}
392
393#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
411pub struct Duration {
412 pub years: i64,
414 pub months: i64,
416 pub weeks: i64,
418 pub days: i64,
420 pub hours: i64,
422 pub minutes: i64,
424 pub seconds: i64,
426 pub milliseconds: i64,
428}
429
430impl Duration {
431 pub(crate) fn units(&self) -> [(&'static str, &'static str, i64); 8] {
433 [
434 ("years", "y", self.years),
435 ("months", "mo", self.months),
436 ("weeks", "w", self.weeks),
437 ("days", "d", self.days),
438 ("hours", "h", self.hours),
439 ("minutes", "m", self.minutes),
440 ("seconds", "s", self.seconds),
441 ("milliseconds", "ms", self.milliseconds),
442 ]
443 }
444
445 pub(crate) fn unit_mut(&mut self, name: &str) -> Option<&mut i64> {
447 match name {
448 "years" => Some(&mut self.years),
449 "months" => Some(&mut self.months),
450 "weeks" => Some(&mut self.weeks),
451 "days" => Some(&mut self.days),
452 "hours" => Some(&mut self.hours),
453 "minutes" => Some(&mut self.minutes),
454 "seconds" => Some(&mut self.seconds),
455 "milliseconds" => Some(&mut self.milliseconds),
456 _ => None,
457 }
458 }
459
460 pub(crate) fn unit_map(&self) -> Map {
462 self.units()
463 .into_iter()
464 .map(|(name, _, amount)| (name, Value::Integer(amount)))
465 .collect()
466 }
467
468 pub(crate) fn from_unit_map(map: &Map, required: &[&str]) -> Option<Duration> {
473 if required.iter().any(|name| map.get_str(name).is_none()) {
474 return None;
475 }
476 let mut duration = Duration::default();
477 for (name, _, _) in Duration::default().units() {
478 match map.get_str(name) {
479 None => {}
480 Some(Value::Integer(amount)) => *duration.unit_mut(name)? = *amount,
481 Some(_) => return None,
482 }
483 }
484 Some(duration)
485 }
486
487 pub(crate) fn parse(text: &str) -> Result<Duration, DurationText> {
499 let mut duration = Duration::default();
500 let mut rest = text.as_bytes();
501 if rest.is_empty() {
502 return Err(DurationText::Malformed);
503 }
504 while !rest.is_empty() {
505 let (whole, after) = digit_run(rest);
506 let (fraction, after) = match after.split_first() {
507 Some((b'.', after)) => match digit_run(after) {
508 ([], _) => return Err(DurationText::Malformed),
509 run => run,
510 },
511 _ => (&[][..], after),
512 };
513 if whole.is_empty() {
514 return Err(DurationText::Malformed);
515 }
516 let (unit, after) = duration_unit(after).ok_or(DurationText::Malformed)?;
517 duration.add_component(whole, fraction, unit)?;
518 rest = after;
519 }
520 Ok(duration)
521 }
522
523 fn add_component(
525 &mut self,
526 whole: &[u8],
527 fraction: &[u8],
528 unit: &str,
529 ) -> Result<(), DurationText> {
530 let amount = whole.iter().try_fold(0_i64, |amount, digit| {
531 amount.checked_mul(10)?.checked_add(i64::from(digit - b'0'))
532 });
533 self.add_unit(unit, amount.ok_or(DurationText::Overflow)?)?;
534 let mut fraction = fraction;
537 while let Some((b'0', head)) = fraction.split_last() {
538 fraction = head;
539 }
540 if fraction.is_empty() {
541 return Ok(());
542 }
543 if fraction.len() > 11 {
544 return Err(DurationText::Malformed);
545 }
546 let numerator = fraction
547 .iter()
548 .fold(0_i128, |sum, digit| sum * 10 + i128::from(digit - b'0'));
549 let denominator = fraction.iter().fold(1_i128, |power, _| power * 10);
550 let total = numerator * unit_milliseconds(unit);
551 if total % denominator != 0 {
552 return Err(DurationText::Malformed);
553 }
554 let mut left = total / denominator;
555 for (suffix, size) in [
556 ("d", 86_400_000),
557 ("h", 3_600_000),
558 ("m", 60_000),
559 ("s", 1_000),
560 ("ms", 1),
561 ] {
562 let count = left / size;
563 left %= size;
564 if count > 0 {
565 self.add_unit(
566 suffix,
567 i64::try_from(count).map_err(|_| DurationText::Overflow)?,
568 )?;
569 }
570 }
571 Ok(())
572 }
573
574 fn add_unit(&mut self, suffix: &str, amount: i64) -> Result<(), DurationText> {
576 let slot = match suffix {
577 "y" => &mut self.years,
578 "mo" => &mut self.months,
579 "w" => &mut self.weeks,
580 "d" => &mut self.days,
581 "h" => &mut self.hours,
582 "m" => &mut self.minutes,
583 "s" => &mut self.seconds,
584 _ => &mut self.milliseconds,
585 };
586 *slot = slot.checked_add(amount).ok_or(DurationText::Overflow)?;
587 Ok(())
588 }
589}
590
591pub fn parse_duration(text: &str) -> Result<Duration, Error> {
616 Duration::parse(text).map_err(|refused| {
617 match refused {
618 DurationText::Malformed => EvaluationError::new(
619 "invalid_duration_format",
620 format!("Invalid duration format: {text}"),
621 ),
622 DurationText::Overflow => EvaluationError::new(
623 "integer_overflow",
624 format!("the duration {text:?} has a unit outside the 64-bit range"),
625 ),
626 }
627 .into()
628 })
629}
630
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633pub(crate) enum DurationText {
634 Malformed,
637 Overflow,
639}
640
641fn digit_run(bytes: &[u8]) -> (&[u8], &[u8]) {
643 let count = bytes
644 .iter()
645 .take_while(|byte| byte.is_ascii_digit())
646 .count();
647 bytes.split_at_checked(count).unwrap_or((bytes, &[]))
648}
649
650fn duration_unit(bytes: &[u8]) -> Option<(&'static str, &[u8])> {
653 for unit in ["mo", "ms", "y", "w", "d", "h", "m", "s"] {
654 if let Some(rest) = bytes.strip_prefix(unit.as_bytes()) {
655 return Some((unit, rest));
656 }
657 }
658 None
659}
660
661fn unit_milliseconds(unit: &str) -> i128 {
663 match unit {
664 "y" => 31_536_000_000,
665 "mo" => 2_592_000_000,
666 "w" => 604_800_000,
667 "d" => 86_400_000,
668 "h" => 3_600_000,
669 "m" => 60_000,
670 "s" => 1_000,
671 _ => 1,
672 }
673}
674
675impl fmt::Display for Duration {
676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 let mut written = false;
678 for (_, suffix, amount) in self.units() {
679 if amount != 0 {
680 write!(f, "{amount}{suffix}")?;
681 written = true;
682 }
683 }
684 if written { Ok(()) } else { f.write_str("0s") }
685 }
686}
687
688struct Digits<'a> {
691 bytes: &'a [u8],
692 at: usize,
693}
694
695impl<'a> Digits<'a> {
696 fn new(text: &'a str) -> Self {
697 Digits {
698 bytes: text.as_bytes(),
699 at: 0,
700 }
701 }
702
703 fn peek(&self) -> Option<u8> {
704 self.bytes.get(self.at).copied()
705 }
706
707 fn skip(&mut self) {
708 self.at += 1;
709 }
710
711 fn digit(&mut self) -> Option<u32> {
712 let byte = self.peek().filter(u8::is_ascii_digit)?;
713 self.skip();
714 Some(u32::from(byte - b'0'))
715 }
716
717 fn number(&mut self, count: usize) -> Option<u32> {
719 let mut value = 0;
720 for _ in 0..count {
721 value = value * 10 + self.digit()?;
722 }
723 Some(value)
724 }
725
726 fn literal(&mut self, byte: u8) -> Option<()> {
727 (self.peek()? == byte).then(|| self.skip())
728 }
729
730 fn fraction(&mut self) -> Option<u32> {
733 let mut micros = 0;
734 let mut count = 0;
735 while let Some(digit) = self.digit() {
736 if count < 6 {
737 micros = micros * 10 + digit;
738 }
739 count += 1;
740 }
741 if count == 0 {
742 return None;
743 }
744 for _ in count..6 {
745 micros *= 10;
746 }
747 Some(micros)
748 }
749
750 fn offset(&mut self) -> Option<i64> {
753 let sign = match self.peek()? {
754 b'Z' => {
755 self.skip();
756 return Some(0);
757 }
758 b'+' => 1,
759 b'-' => -1,
760 _ => return None,
761 };
762 self.skip();
763 let hours = self.number(2)?;
764 let colon = self.literal(b':').is_some();
765 let minutes = match self.peek() {
766 Some(byte) if byte.is_ascii_digit() => self.number(2)?,
767 _ if colon => return None,
768 _ => 0,
769 };
770 if hours > 23 || minutes > 59 || (sign < 0 && colon && hours == 0 && minutes == 0) {
771 return None;
772 }
773 Some(sign * i64::from(hours * 3600 + minutes * 60))
774 }
775
776 fn end(&self) -> Option<()> {
777 (self.at == self.bytes.len()).then_some(())
778 }
779}
780
781#[cfg(test)]
782mod tests {
783 use super::*;
784
785 fn date(year: i32, month: u32, day: u32) -> Date {
786 Date::new(year, month, day).unwrap()
787 }
788
789 #[test]
792 fn a_date_is_a_calendar_date() {
793 assert!(Date::new(2024, 2, 29).is_some());
794 assert!(Date::new(2000, 2, 29).is_some());
795 assert!(Date::new(1900, 2, 29).is_none());
796 assert!(Date::new(2023, 2, 29).is_none());
797 assert!(Date::new(2026, 4, 31).is_none());
798 assert!(Date::new(2026, 13, 1).is_none());
799 assert!(Date::new(2026, 0, 1).is_none());
800 assert!(Date::new(2026, 1, 0).is_none());
801 assert_eq!(date(2026, 1, 31).day(), 31);
802 }
803
804 #[test]
807 fn day_numbers_round_trip_across_eras() {
808 assert_eq!(date(1970, 1, 1).days(), 0);
809 assert_eq!(date(2000, 3, 1).days(), 11_017);
810 assert_eq!(date(1969, 12, 31).days(), -1);
811 for days in [
812 -1_000_000, -719_528, -1, 0, 59, 60, 11_016, 2_932_896, 9_000_000,
813 ] {
814 let back = civil_from_days(days).unwrap();
815 assert_eq!(back.days(), days, "{back:?}");
816 }
817 assert_eq!(civil_from_days(-719_528), Some(date(0, 1, 1)));
818 assert_eq!(civil_from_days(2_932_896), Some(date(9999, 12, 31)));
819 assert_eq!(civil_from_days(i64::MAX), None);
820 let last = date(i32::MAX, 12, 31);
821 assert_eq!(civil_from_days(last.days()), Some(last));
822 assert_eq!(civil_from_days(last.days() + 1), None);
823 let first = date(i32::MIN, 1, 1);
824 assert_eq!(civil_from_days(first.days()), Some(first));
825 assert_eq!(civil_from_days(first.days() - 1), None);
826 }
827
828 #[test]
831 fn a_date_writes_and_reads_iso_text() {
832 assert_eq!(date(2026, 8, 6).to_string(), "2026-08-06");
833 assert_eq!(date(7, 1, 2).to_string(), "0007-01-02");
834 assert_eq!(date(12_026, 1, 2).to_string(), "12026-01-02");
835 assert_eq!(date(-1, 1, 2).to_string(), "-0001-01-02");
836 assert_eq!(format!("{:?}", date(2026, 8, 6)), "Date(2026-08-06)");
837 assert_eq!(Date::parse("2026-08-06"), Some(date(2026, 8, 6)));
838 for text in [
839 "2026-8-06",
840 "20260806",
841 "+2026-08-06",
842 "2026-02-30",
843 "2026-08-06 ",
844 "12026-01-01",
845 ] {
846 assert_eq!(Date::parse(text), None, "{text}");
847 }
848 }
849
850 #[test]
852 fn an_instant_holds_the_microsecond_and_far_years() {
853 let instant = DateTime::new(date(2026, 8, 9), 10, 30, 0, 500_000).unwrap();
854 assert_eq!(instant.to_string(), "2026-08-09T10:30:00.500000Z");
855 assert_eq!(
856 (instant.hour(), instant.minute(), instant.second()),
857 (10, 30, 0)
858 );
859 assert_eq!(instant.microsecond(), 500_000);
860 assert_eq!(
861 format!("{instant:?}"),
862 "DateTime(2026-08-09T10:30:00.500000Z)"
863 );
864 assert!(DateTime::new(date(2026, 8, 9), 24, 0, 0, 0).is_none());
865 assert!(DateTime::new(date(2026, 8, 9), 0, 60, 0, 0).is_none());
866 assert!(DateTime::new(date(2026, 8, 9), 0, 0, 60, 0).is_none());
867 assert!(DateTime::new(date(2026, 8, 9), 0, 0, 0, 1_000_000).is_none());
868 assert!(DateTime::from_unix(0, 1_000_000).is_none());
869 let before = DateTime::from_unix(-1, 999_999).unwrap();
870 assert_eq!(before.to_string(), "1969-12-31T23:59:59.999999Z");
871 let far = DateTime::new(date(i32::MAX, 12, 31), 23, 59, 59, 999_999).unwrap();
872 assert_eq!(DateTime::from_unix(far.unix_seconds(), 999_999), Some(far));
873 assert!(DateTime::from_unix(far.unix_seconds() + 1, 0).is_none());
874 assert!(DateTime::from_unix(i64::MIN, 0).is_none());
875 assert!(before < DateTime::from_unix(0, 0).unwrap());
876 }
877
878 #[test]
881 fn an_instant_reads_the_forms_the_reference_reads() {
882 let read = |text: &str| DateTime::parse(text).map(|instant| instant.to_string());
883 assert_eq!(
884 read("2026-08-06T12:00:00Z").as_deref(),
885 Some("2026-08-06T12:00:00Z")
886 );
887 assert_eq!(
888 read("2026-08-06 12:00:00Z").as_deref(),
889 Some("2026-08-06T12:00:00Z")
890 );
891 assert_eq!(
892 read("2026-08-06T12:00:00,5Z").as_deref(),
893 Some("2026-08-06T12:00:00.500000Z")
894 );
895 assert_eq!(
896 read("2026-08-06T12:00:00.1234567Z").as_deref(),
897 Some("2026-08-06T12:00:00.123456Z")
898 );
899 assert_eq!(
900 read("2026-08-06T12:00:00+0130").as_deref(),
901 Some("2026-08-06T10:30:00Z")
902 );
903 assert_eq!(
904 read("2026-08-06T12:00:00+01").as_deref(),
905 Some("2026-08-06T11:00:00Z")
906 );
907 assert_eq!(
908 read("2026-08-06T12:00:00-01:00").as_deref(),
909 Some("2026-08-06T13:00:00Z")
910 );
911 assert_eq!(
912 read("2026-08-06T12:00:00-0000").as_deref(),
913 Some("2026-08-06T12:00:00Z")
914 );
915 for text in [
916 "2026-08-06t12:00:00z",
917 "2026-08-06T12:00:00-00:00",
918 "2026-08-06T12:00:00",
919 "2026-08-06T24:00:00Z",
920 "2026-08-06T12:00:60Z",
921 "2026-08-06T12:00Z",
922 "2026-08-06T12:00:00.Z",
923 "2026-08-06T12:00:00+01:",
924 "2026-08-06T12:00:00+24:00",
925 "2026-08-06T12:00:00Z ",
926 "20260806T120000Z",
927 "9999-12-31T23:30:00-01:00",
928 "0000-01-01T00:30:00+01:00",
929 ] {
930 assert_eq!(read(text), None, "{text}");
931 }
932 }
933
934 #[test]
937 fn a_duration_writes_its_units_largest_first() {
938 let every = Duration {
939 years: 1,
940 months: 2,
941 weeks: 3,
942 days: 4,
943 hours: 5,
944 minutes: 6,
945 seconds: 7,
946 milliseconds: 8,
947 };
948 assert_eq!(every.to_string(), "1y2mo3w4d5h6m7s8ms");
949 assert_eq!(
950 Duration {
951 seconds: -90,
952 ..Duration::default()
953 }
954 .to_string(),
955 "-90s"
956 );
957 assert_eq!(Duration::default().to_string(), "0s");
958 let mut written = Duration::default();
959 for (name, _, _) in every.units() {
960 *written.unit_mut(name).unwrap() = 1;
961 }
962 assert!(written.units().iter().all(|(_, _, amount)| *amount == 1));
963 assert!(written.unit_mut("fortnights").is_none());
964 }
965
966 fn read(text: &str) -> String {
968 match Duration::parse(text) {
969 Ok(duration) => format!("{duration:?}"),
970 Err(why) => format!("{why:?}"),
971 }
972 }
973
974 fn of(duration: Duration) -> String {
975 format!("{duration:?}")
976 }
977
978 #[test]
981 fn a_duration_reads_the_literal_grammar_with_its_fractions() {
982 assert_eq!(
983 read("3d8h30m"),
984 of(Duration {
985 days: 3,
986 hours: 8,
987 minutes: 30,
988 ..Duration::default()
989 })
990 );
991 assert_eq!(
992 read("1mo1ms1m"),
993 of(Duration {
994 months: 1,
995 milliseconds: 1,
996 minutes: 1,
997 ..Duration::default()
998 })
999 );
1000 assert_eq!(
1001 read("1d2d"),
1002 of(Duration {
1003 days: 3,
1004 ..Duration::default()
1005 })
1006 );
1007 assert_eq!(read("0s"), of(Duration::default()));
1008 assert_eq!(
1009 read("1.5s"),
1010 of(Duration {
1011 seconds: 1,
1012 milliseconds: 500,
1013 ..Duration::default()
1014 })
1015 );
1016 assert_eq!(
1017 read("0.5mo"),
1018 of(Duration {
1019 days: 15,
1020 ..Duration::default()
1021 })
1022 );
1023 assert_eq!(
1024 read("0.5y"),
1025 of(Duration {
1026 days: 182,
1027 hours: 12,
1028 ..Duration::default()
1029 })
1030 );
1031 assert_eq!(
1032 read("1.25d0.5d"),
1033 of(Duration {
1034 days: 1,
1035 hours: 18,
1036 ..Duration::default()
1037 })
1038 );
1039 assert_eq!(
1040 read(&format!("2.{}s", "0".repeat(40))),
1041 of(Duration {
1042 seconds: 2,
1043 ..Duration::default()
1044 })
1045 );
1046 assert_eq!(
1047 read("0.00000000001mo"),
1048 "Malformed",
1049 "eleven digits leave less than a millisecond"
1050 );
1051 assert_eq!(
1052 read("0.0009765625mo"),
1053 of(Duration {
1054 minutes: 42,
1055 seconds: 11,
1056 milliseconds: 250,
1057 ..Duration::default()
1058 })
1059 );
1060 for refused in [
1061 "", "0.5ms", "1.s", ".5s", "1", "d", "1d ", " 1d", "-1d", "1x", "1mos", "1d\n", "1D",
1062 ] {
1063 assert_eq!(read(refused), "Malformed", "{refused:?}");
1064 }
1065 assert_eq!(read("9223372036854775808s"), "Overflow");
1066 assert_eq!(read("9223372036854775807d1d"), "Overflow");
1067 assert_eq!(read("9223372036854775807h0.5d"), "Overflow");
1068 assert_eq!(
1069 read("9223372036854775807ms"),
1070 of(Duration {
1071 milliseconds: i64::MAX,
1072 ..Duration::default()
1073 })
1074 );
1075 }
1076
1077 #[test]
1080 fn parse_duration_answers_the_duration_or_names_its_refusal() {
1081 assert_eq!(
1082 parse_duration("3d8h30m"),
1083 Ok(Duration {
1084 days: 3,
1085 hours: 8,
1086 minutes: 30,
1087 ..Duration::default()
1088 })
1089 );
1090 let reason = |text: &str| {
1091 parse_duration(text).map_err(|error| (error.type_name(), error.reason().to_owned()))
1092 };
1093 assert_eq!(
1094 reason(""),
1095 Err(("EvaluationError", "invalid_duration_format".to_owned()))
1096 );
1097 assert_eq!(
1098 reason("0.5ms"),
1099 Err(("EvaluationError", "invalid_duration_format".to_owned()))
1100 );
1101 assert_eq!(
1102 reason("9223372036854775808s"),
1103 Err(("EvaluationError", "integer_overflow".to_owned()))
1104 );
1105 }
1106}