1#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
46#[non_exhaustive]
47pub struct Duration {
48 seconds: i64,
54
55 nanos: i32,
64}
65
66#[derive(thiserror::Error, Debug)]
84#[non_exhaustive]
85pub enum DurationError {
86 #[error("seconds and/or nanoseconds out of range")]
88 OutOfRange,
89
90 #[error("if seconds and nanoseconds are not zero, they must have the same sign")]
92 MismatchedSigns,
93
94 #[error("cannot deserialize the duration: {0}")]
96 Deserialize(#[source] BoxedError),
97}
98
99type BoxedError = Box<dyn std::error::Error + Send + Sync>;
100type Error = DurationError;
101
102impl Duration {
103 const NS: i32 = 1_000_000_000;
104
105 pub const MAX_SECONDS: i64 = 315_576_000_000;
107
108 pub const MIN_SECONDS: i64 = -Self::MAX_SECONDS;
110
111 pub const MAX_NANOS: i32 = Self::NS - 1;
113
114 pub const MIN_NANOS: i32 = -Self::MAX_NANOS;
116
117 pub fn new(seconds: i64, nanos: i32) -> Result<Self, Error> {
151 if !(Self::MIN_SECONDS..=Self::MAX_SECONDS).contains(&seconds) {
152 return Err(Error::OutOfRange);
153 }
154 if !(Self::MIN_NANOS..=Self::MAX_NANOS).contains(&nanos) {
155 return Err(Error::OutOfRange);
156 }
157 if (seconds != 0 && nanos != 0) && ((seconds < 0) != (nanos < 0)) {
158 return Err(Error::MismatchedSigns);
159 }
160 Ok(Self { seconds, nanos })
161 }
162
163 pub fn clamp(seconds: i64, nanos: i32) -> Self {
188 let mut seconds = seconds;
189 seconds = seconds.saturating_add((nanos / Self::NS) as i64);
190 let mut nanos = nanos % Self::NS;
191 if seconds > 0 && nanos < 0 {
192 seconds = seconds.saturating_sub(1);
193 nanos += Self::NS;
194 } else if seconds < 0 && nanos > 0 {
195 seconds = seconds.saturating_add(1);
196 nanos = -(Self::NS - nanos);
197 }
198 if seconds > Self::MAX_SECONDS {
199 return Self {
200 seconds: Self::MAX_SECONDS,
201 nanos: 0,
202 };
203 }
204 if seconds < Self::MIN_SECONDS {
205 return Self {
206 seconds: Self::MIN_SECONDS,
207 nanos: 0,
208 };
209 }
210 Self { seconds, nanos }
211 }
212
213 pub fn seconds(&self) -> i64 {
222 self.seconds
223 }
224
225 pub fn nanos(&self) -> i32 {
234 self.nanos
235 }
236}
237
238impl crate::message::Message for Duration {
239 fn typename() -> &'static str {
240 "type.googleapis.com/google.protobuf.Duration"
241 }
242
243 #[allow(private_interfaces)]
244 fn serializer() -> impl crate::message::MessageSerializer<Self> {
245 crate::message::ValueSerializer::<Self>::new()
246 }
247}
248
249impl From<Duration> for String {
258 fn from(duration: Duration) -> String {
259 let sign = if duration.seconds < 0 || duration.nanos < 0 {
260 "-"
261 } else {
262 ""
263 };
264 if duration.nanos == 0 {
265 return format!("{sign}{}s", duration.seconds.abs());
266 }
267 let ns = format!("{:09}", duration.nanos.abs());
268 format!(
269 "{sign}{}.{}s",
270 duration.seconds.abs(),
271 ns.trim_end_matches('0')
272 )
273 }
274}
275
276impl TryFrom<&str> for Duration {
287 type Error = DurationError;
288 fn try_from(value: &str) -> Result<Self, Self::Error> {
289 if !value.ends_with('s') {
290 return Err(DurationError::Deserialize("missing trailing 's'".into()));
291 }
292 let digits = &value[..(value.len() - 1)];
293 let (sign, digits) = if let Some(stripped) = digits.strip_prefix('-') {
294 (-1, stripped)
295 } else {
296 (1, digits.strip_prefix('+').unwrap_or(digits))
298 };
299 let mut split = digits.splitn(2, '.');
300 let (seconds, nanos) = (split.next(), split.next());
301 let seconds = seconds
302 .map(|s| {
303 if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
305 return Err(DurationError::Deserialize(
306 format!("seconds are not a number [{s}]").into(),
307 ));
308 }
309 s.parse::<i64>()
310 .map_err(|e| DurationError::Deserialize(e.into()))
311 })
312 .transpose()?
313 .unwrap_or(0);
314 let nanos = nanos
315 .map(|s| {
316 if s.is_empty() || !s.chars().all(|c| c.is_ascii_digit()) {
317 return Err(DurationError::Deserialize(
318 format!("nanos are not a number [{s}]").into(),
319 ));
320 }
321 let len = s.len();
322 let (digits, power) = if len > 9 { (&s[..9], 0) } else { (s, 9 - len) };
323 let mut val = digits
324 .parse::<i32>()
325 .map_err(|e| DurationError::Deserialize(e.into()))?;
326 if power > 0 {
327 val *= 10_i32.pow(power as u32)
328 }
329 Ok(val)
330 })
331 .transpose()?
332 .unwrap_or(0);
333
334 Duration::new(sign * seconds, sign as i32 * nanos)
336 }
337}
338
339impl TryFrom<&String> for Duration {
351 type Error = DurationError;
352 fn try_from(value: &String) -> Result<Self, Self::Error> {
353 Duration::try_from(value.as_str())
354 }
355}
356
357impl TryFrom<std::time::Duration> for Duration {
368 type Error = DurationError;
369
370 fn try_from(value: std::time::Duration) -> Result<Self, Self::Error> {
371 if value.as_secs() > (i64::MAX as u64) {
372 return Err(Error::OutOfRange);
373 }
374 assert!(value.as_secs() <= (i64::MAX as u64));
375 assert!(value.subsec_nanos() <= (i32::MAX as u32));
376 Self::new(value.as_secs() as i64, value.subsec_nanos() as i32)
377 }
378}
379
380impl TryFrom<Duration> for std::time::Duration {
395 type Error = DurationError;
396
397 fn try_from(value: Duration) -> Result<Self, Self::Error> {
398 if value.seconds < 0 {
399 return Err(Error::OutOfRange);
400 }
401 if value.nanos < 0 {
402 return Err(Error::OutOfRange);
403 }
404 Ok(Self::new(value.seconds as u64, value.nanos as u32))
405 }
406}
407
408#[cfg(feature = "time")]
421#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
422impl TryFrom<time::Duration> for Duration {
423 type Error = DurationError;
424
425 fn try_from(value: time::Duration) -> Result<Self, Self::Error> {
426 Self::new(value.whole_seconds(), value.subsec_nanoseconds())
427 }
428}
429
430#[cfg(feature = "time")]
444#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
445impl From<Duration> for time::Duration {
446 fn from(value: Duration) -> Self {
447 Self::new(value.seconds(), value.nanos())
448 }
449}
450
451#[cfg(feature = "chrono")]
464#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
465impl TryFrom<chrono::Duration> for Duration {
466 type Error = DurationError;
467
468 fn try_from(value: chrono::Duration) -> Result<Self, Self::Error> {
469 Self::new(value.num_seconds(), value.subsec_nanos())
470 }
471}
472
473#[cfg(feature = "chrono")]
484#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
485impl From<Duration> for chrono::Duration {
486 fn from(value: Duration) -> Self {
487 Self::seconds(value.seconds) + Self::nanoseconds(value.nanos as i64)
488 }
489}
490
491#[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
493impl serde::ser::Serialize for Duration {
494 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
495 where
496 S: serde::ser::Serializer,
497 {
498 let formatted = String::from(*self);
499 formatted.serialize(serializer)
500 }
501}
502
503struct DurationVisitor;
504
505impl serde::de::Visitor<'_> for DurationVisitor {
506 type Value = Duration;
507
508 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
509 formatter.write_str("a string with a duration in Google format ([sign]{seconds}.{nanos}s)")
510 }
511
512 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
513 where
514 E: serde::de::Error,
515 {
516 let d = Duration::try_from(value).map_err(E::custom)?;
517 Ok(d)
518 }
519}
520
521#[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
523impl<'de> serde::de::Deserialize<'de> for Duration {
524 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
525 where
526 D: serde::Deserializer<'de>,
527 {
528 deserializer.deserialize_str(DurationVisitor)
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535 use serde_json::json;
536 use test_case::test_case;
537 type Result = std::result::Result<(), Box<dyn std::error::Error>>;
538
539 #[test]
541 fn zero() -> Result {
542 let proto = Duration {
543 seconds: 0,
544 nanos: 0,
545 };
546 let json = serde_json::to_value(proto)?;
547 let expected = json!(r#"0s"#);
548 assert_eq!(json, expected);
549 let roundtrip = serde_json::from_value::<Duration>(json)?;
550 assert_eq!(proto, roundtrip);
551 Ok(())
552 }
553
554 const SECONDS_IN_DAY: i64 = 24 * 60 * 60;
557 const SECONDS_IN_YEAR: i64 = 365 * SECONDS_IN_DAY + SECONDS_IN_DAY / 4;
560
561 #[test_case(10_000 * SECONDS_IN_YEAR , 0 ; "exactly 10,000 years")]
562 #[test_case(- 10_000 * SECONDS_IN_YEAR , 0 ; "exactly negative 10,000 years")]
563 #[test_case(10_000 * SECONDS_IN_YEAR , 999_999_999 ; "exactly 10,000 years and 999,999,999 nanos"
564 )]
565 #[test_case(- 10_000 * SECONDS_IN_YEAR , -999_999_999 ; "exactly negative 10,000 years and 999,999,999 nanos"
566 )]
567 #[test_case(0, 999_999_999 ; "exactly 999,999,999 nanos")]
568 #[test_case(0 , -999_999_999 ; "exactly negative 999,999,999 nanos")]
569 fn edge_of_range(seconds: i64, nanos: i32) -> Result {
570 let d = Duration::new(seconds, nanos)?;
571 assert_eq!(seconds, d.seconds());
572 assert_eq!(nanos, d.nanos());
573 Ok(())
574 }
575
576 #[test_case(10_000 * SECONDS_IN_YEAR + 1, 0 ; "more seconds than in 10,000 years")]
577 #[test_case(- 10_000 * SECONDS_IN_YEAR - 1, 0 ; "more negative seconds than in -10,000 years")]
578 #[test_case(0, 1_000_000_000 ; "too many positive nanoseconds")]
579 #[test_case(0, -1_000_000_000 ; "too many negative nanoseconds")]
580 fn out_of_range(seconds: i64, nanos: i32) -> Result {
581 let d = Duration::new(seconds, nanos);
582 assert!(matches!(d, Err(Error::OutOfRange)), "{d:?}");
583 Ok(())
584 }
585
586 #[test_case(1 , -1 ; "mismatched sign case 1")]
587 #[test_case(-1 , 1 ; "mismatched sign case 2")]
588 fn mismatched_sign(seconds: i64, nanos: i32) -> Result {
589 let d = Duration::new(seconds, nanos);
590 assert!(matches!(d, Err(Error::MismatchedSigns)), "{d:?}");
591 Ok(())
592 }
593
594 #[test_case(20_000 * SECONDS_IN_YEAR, 0, 10_000 * SECONDS_IN_YEAR, 0 ; "too many positive seconds"
595 )]
596 #[test_case(-20_000 * SECONDS_IN_YEAR, 0, -10_000 * SECONDS_IN_YEAR, 0 ; "too many negative seconds"
597 )]
598 #[test_case(10_000 * SECONDS_IN_YEAR - 1, 1_999_999_999, 10_000 * SECONDS_IN_YEAR, 999_999_999 ; "upper edge of range"
599 )]
600 #[test_case(-10_000 * SECONDS_IN_YEAR + 1, -1_999_999_999, -10_000 * SECONDS_IN_YEAR, -999_999_999 ; "lower edge of range"
601 )]
602 #[test_case(10_000 * SECONDS_IN_YEAR - 1 , 2 * 1_000_000_000_i32, 10_000 * SECONDS_IN_YEAR, 0 ; "nanos push over 10,000 years"
603 )]
604 #[test_case(-10_000 * SECONDS_IN_YEAR + 1, -2 * 1_000_000_000_i32, -10_000 * SECONDS_IN_YEAR, 0 ; "one push under -10,000 years"
605 )]
606 #[test_case(0, 0, 0, 0 ; "all inputs are zero")]
607 #[test_case(1, 0, 1, 0 ; "positive seconds and zero nanos")]
608 #[test_case(1, 200_000, 1, 200_000 ; "positive seconds and nanos")]
609 #[test_case(-1, 0, -1, 0; "negative seconds and zero nanos")]
610 #[test_case(-1, -500_000_000, -1, -500_000_000; "negative seconds and nanos")]
611 #[test_case(2, -400_000_000, 1, 600_000_000; "positive seconds and negative nanos")]
612 #[test_case(-2, 400_000_000, -1, -600_000_000; "negative seconds and positive nanos")]
613 fn clamp(seconds: i64, nanos: i32, want_seconds: i64, want_nanos: i32) -> Result {
614 let got = Duration::clamp(seconds, nanos);
615 let want = Duration {
616 seconds: want_seconds,
617 nanos: want_nanos,
618 };
619 assert_eq!(want, got);
620 Ok(())
621 }
622
623 #[test_case(0, 0, "0s" ; "zero")]
625 #[test_case(0, 2, "0.000000002s" ; "2ns")]
626 #[test_case(0, 200_000_000, "0.2s" ; "200ms")]
627 #[test_case(12, 0, "12s"; "round positive seconds")]
628 #[test_case(12, 123, "12.000000123s"; "positive seconds and nanos")]
629 #[test_case(12, 123_000, "12.000123s"; "positive seconds and micros")]
630 #[test_case(12, 123_000_000, "12.123s"; "positive seconds and millis")]
631 #[test_case(12, 123_456_789, "12.123456789s"; "positive seconds and full nanos")]
632 #[test_case(-12, -0, "-12s"; "round negative seconds")]
633 #[test_case(-12, -123, "-12.000000123s"; "negative seconds and nanos")]
634 #[test_case(-12, -123_000, "-12.000123s"; "negative seconds and micros")]
635 #[test_case(-12, -123_000_000, "-12.123s"; "negative seconds and millis")]
636 #[test_case(-12, -123_456_789, "-12.123456789s"; "negative seconds and full nanos")]
637 #[test_case(-10_000 * SECONDS_IN_YEAR, -999_999_999, "-315576000000.999999999s"; "range edge start"
638 )]
639 #[test_case(10_000 * SECONDS_IN_YEAR, 999_999_999, "315576000000.999999999s"; "range edge end")]
640 fn roundtrip(seconds: i64, nanos: i32, want: &str) -> Result {
641 let input = Duration::new(seconds, nanos)?;
642 let got = serde_json::to_value(input)?
643 .as_str()
644 .map(str::to_string)
645 .ok_or("cannot convert value to string")?;
646 assert_eq!(want, got);
647
648 let rt = serde_json::from_value::<Duration>(serde_json::Value::String(got))?;
649 assert_eq!(input, rt);
650 Ok(())
651 }
652
653 #[test_case("-315576000001s"; "range edge start")]
654 #[test_case("315576000001s"; "range edge end")]
655 fn deserialize_out_of_range(input: &str) -> Result {
656 let value = serde_json::to_value(input)?;
657 let got = serde_json::from_value::<Duration>(value);
658 assert!(got.is_err(), "{got:?}");
659 Ok(())
660 }
661
662 #[test_case(time::Duration::default(), Duration::default() ; "default")]
663 #[test_case(time::Duration::new(0, 0), Duration::new(0, 0).unwrap() ; "zero")]
664 #[test_case(time::Duration::new(10_000 * SECONDS_IN_YEAR , 0), Duration::new(10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly 10,000 years"
665 )]
666 #[test_case(time::Duration::new(-10_000 * SECONDS_IN_YEAR , 0), Duration::new(-10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly negative 10,000 years"
667 )]
668 fn from_time_in_range(value: time::Duration, want: Duration) -> Result {
669 let got = Duration::try_from(value)?;
670 assert_eq!(got, want);
671 Ok(())
672 }
673
674 #[test_case(time::Duration::new(10_001 * SECONDS_IN_YEAR, 0) ; "above the range")]
675 #[test_case(time::Duration::new(-10_001 * SECONDS_IN_YEAR, 0) ; "below the range")]
676 fn from_time_out_of_range(value: time::Duration) {
677 let got = Duration::try_from(value);
678 assert!(matches!(got, Err(DurationError::OutOfRange)), "{got:?}");
679 }
680
681 #[test_case(Duration::default(), time::Duration::default() ; "default")]
682 #[test_case(Duration::new(0, 0).unwrap(), time::Duration::new(0, 0) ; "zero")]
683 #[test_case(Duration::new(10_000 * SECONDS_IN_YEAR , 0).unwrap(), time::Duration::new(10_000 * SECONDS_IN_YEAR, 0) ; "exactly 10,000 years"
684 )]
685 #[test_case(Duration::new(-10_000 * SECONDS_IN_YEAR , 0).unwrap(), time::Duration::new(-10_000 * SECONDS_IN_YEAR, 0) ; "exactly negative 10,000 years"
686 )]
687 fn to_time_in_range(value: Duration, want: time::Duration) -> Result {
688 let got = time::Duration::from(value);
689 assert_eq!(got, want);
690 Ok(())
691 }
692
693 #[test_case("" ; "empty")]
694 #[test_case("1.0" ; "missing final s")]
695 #[test_case("1.2.3.4s" ; "too many periods")]
696 #[test_case("aaas" ; "not a number")]
697 #[test_case("aaaa.0s" ; "seconds are not a number [aaa]")]
698 #[test_case("1a.0s" ; "seconds are not a number [1a]")]
699 #[test_case("1.aaas" ; "nanos are not a number [aaa]")]
700 #[test_case("1.0as" ; "nanos are not a number [0a]")]
701 #[test_case("1.1234567890as" ; "nanos with trailing chars [1234567890a]")]
702 #[test_case("1.s" ; "empty nanos")]
703 #[test_case("--1s" ; "repeated minus sign")]
704 #[test_case("-+1s" ; "minus then plus sign")]
705 #[test_case("+-1s" ; "plus then minus sign")]
706 #[test_case("++1s" ; "repeated plus sign")]
707 #[test_case("--1.5s" ; "repeated minus sign with nanos")]
708 #[test_case("--9223372036854775808s" ; "repeated minus sign with i64 min")]
709 #[test_case("-9223372036854775808s" ; "seconds do not fit in i64")]
710 fn parse_detect_bad_input(input: &str) -> Result {
711 let got = Duration::try_from(input);
712 assert!(got.is_err(), "{got:?}");
713 let err = got.err().unwrap();
714 assert!(
715 matches!(err, DurationError::Deserialize(_)),
716 "unexpected error {err:?}"
717 );
718 Ok(())
719 }
720
721 #[test_case("+1s", 1, 0 ; "plus sign")]
722 #[test_case("+1.5s", 1, 500_000_000 ; "plus sign with nanos")]
723 #[test_case("-0.5s", 0, -500_000_000 ; "minus sign with zero seconds")]
724 fn parse_sign(input: &str, seconds: i64, nanos: i32) -> Result {
725 let got = Duration::try_from(input)?;
726 assert_eq!(got, Duration::new(seconds, nanos)?);
727 Ok(())
728 }
729
730 #[test]
731 fn fractional_seconds_exceed_9_digits() -> Result {
732 let d = Duration::try_from("1.1234567890s")?;
733 assert_eq!(d, Duration::new(1, 123_456_789)?);
734
735 let d = Duration::try_from("1.123456789012s")?;
736 assert_eq!(d, Duration::new(1, 123_456_789)?);
737
738 let d: Duration = serde_json::from_str(r#""1.1234567890s""#)?;
739 assert_eq!(d, Duration::new(1, 123_456_789)?);
740
741 let d: Duration = serde_json::from_str(r#""1.123456789012s""#)?;
742 assert_eq!(d, Duration::new(1, 123_456_789)?);
743
744 let d = Duration::try_from("-1.1234567890s")?;
745 assert_eq!(d, Duration::new(-1, -123_456_789)?);
746
747 let d: Duration = serde_json::from_str(r#""-1.123456789012s""#)?;
748 assert_eq!(d, Duration::new(-1, -123_456_789)?);
749 Ok(())
750 }
751
752 #[test]
753 fn deserialize_unexpected_input_type() -> Result {
754 let got = serde_json::from_value::<Duration>(serde_json::json!({}));
755 assert!(got.is_err(), "{got:?}");
756 let msg = format!("{got:?}");
757 assert!(msg.contains("duration in Google format"), "message={msg}");
758 Ok(())
759 }
760
761 #[test_case(std::time::Duration::new(0, 0), Duration::clamp(0, 0))]
762 #[test_case(
763 std::time::Duration::new(0, 400_000_000),
764 Duration::clamp(0, 400_000_000)
765 )]
766 #[test_case(
767 std::time::Duration::new(1, 400_000_000),
768 Duration::clamp(1, 400_000_000)
769 )]
770 #[test_case(std::time::Duration::new(10_000 * SECONDS_IN_YEAR as u64, 999_999_999), Duration::clamp(10_000 * SECONDS_IN_YEAR, 999_999_999))]
771 fn from_std_time_in_range(input: std::time::Duration, want: Duration) {
772 let got = Duration::try_from(input).unwrap();
773 assert_eq!(got, want);
774 }
775
776 #[test]
777 fn convert_from_string() -> Result {
778 let input = "12.750s".to_string();
779 let a = Duration::try_from(input.as_str())?;
780 let b = Duration::try_from(&input)?;
781 assert_eq!(a, b);
782 Ok(())
783 }
784
785 #[test_case(std::time::Duration::new(i64::MAX as u64, 0))]
786 #[test_case(std::time::Duration::new(i64::MAX as u64 + 10, 0))]
787 fn from_std_time_out_of_range(input: std::time::Duration) {
788 let got = Duration::try_from(input);
789 assert!(got.is_err(), "{got:?}");
790 }
791
792 #[test_case(chrono::Duration::default(), Duration::default() ; "default")]
793 #[test_case(chrono::Duration::new(0, 0).unwrap(), Duration::new(0, 0).unwrap() ; "zero")]
794 #[test_case(chrono::Duration::new(10_000 * SECONDS_IN_YEAR, 0).unwrap(), Duration::new(10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly 10,000 years"
795 )]
796 #[test_case(chrono::Duration::new(-10_000 * SECONDS_IN_YEAR, 0).unwrap(), Duration::new(-10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly negative 10,000 years"
797 )]
798 fn from_chrono_time_in_range(value: chrono::Duration, want: Duration) -> Result {
799 let got = Duration::try_from(value)?;
800 assert_eq!(got, want);
801 Ok(())
802 }
803
804 #[test_case(Duration::default(), chrono::Duration::default() ; "default")]
805 #[test_case(Duration::new(0, 0).unwrap(), chrono::Duration::new(0, 0).unwrap() ; "zero")]
806 #[test_case(Duration::new(0, 500_000).unwrap(), chrono::Duration::new(0, 500_000).unwrap() ; "500us")]
807 #[test_case(Duration::new(1, 400_000_000).unwrap(), chrono::Duration::new(1, 400_000_000).unwrap() ; "1.4s")]
808 #[test_case(Duration::new(0, -400_000_000).unwrap(), chrono::Duration::new(-1, 600_000_000).unwrap() ; "minus 0.4s")]
809 #[test_case(Duration::new(-1, -400_000_000).unwrap(), chrono::Duration::new(-2, 600_000_000).unwrap() ; "minus 1.4s")]
810 #[test_case(Duration::new(10_000 * SECONDS_IN_YEAR , 0).unwrap(), chrono::Duration::new(10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly 10,000 years"
811 )]
812 #[test_case(Duration::new(-10_000 * SECONDS_IN_YEAR , 0).unwrap(), chrono::Duration::new(-10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly negative 10,000 years"
813 )]
814 fn to_chrono_time_in_range(value: Duration, want: chrono::Duration) -> Result {
815 let got = chrono::Duration::from(value);
816 assert_eq!(got, want);
817 Ok(())
818 }
819
820 #[test_case(chrono::Duration::new(10_001 * SECONDS_IN_YEAR, 0).unwrap() ; "above the range")]
821 #[test_case(chrono::Duration::new(-10_001 * SECONDS_IN_YEAR, 0).unwrap() ; "below the range")]
822 fn from_chrono_time_out_of_range(value: chrono::Duration) {
823 let got = Duration::try_from(value);
824 assert!(matches!(got, Err(DurationError::OutOfRange)), "{got:?}");
825 }
826}