Skip to content

Commit

Permalink
Add From impls for Days, Months and std::time::Duration
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Sep 14, 2023
1 parent 0cf7b5e commit 1458553
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/calendar_duration.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use core::fmt;
use core::num::NonZeroU32;
use core::time::Duration;

use crate::{expect, try_opt};
use crate::{Days, Months};

/// ISO 8601 duration type.
///
Expand Down Expand Up @@ -268,9 +270,31 @@ impl CalendarDuration {
}
}

impl From<Days> for CalendarDuration {
fn from(value: Days) -> Self {
let days = u32::try_from(value.0).expect("value of `Days` out of range");
Self::new().days(days)
}
}

impl From<Months> for CalendarDuration {
fn from(value: Months) -> Self {
Self::new().months(value.0)
}
}

impl From<Duration> for CalendarDuration {
fn from(value: Duration) -> Self {
let seconds = u32::try_from(value.as_secs()).expect("value of `Duration` out of range");
Self::new().seconds(seconds).nanos(value.subsec_nanos()).unwrap()
}
}

#[cfg(test)]
mod tests {
use super::CalendarDuration;
use crate::{Days, Months};
use std::time::Duration;

#[test]
fn test_basic_functionality() {
Expand Down Expand Up @@ -301,6 +325,28 @@ mod tests {
assert!(CalendarDuration::new().is_zero());
}

#[test]
fn test_from_impls() {
assert_eq!(CalendarDuration::new().days(5), Days::new(5).into());
assert_eq!(CalendarDuration::new().months(5), Months::new(5).into());
assert_eq!(
CalendarDuration::new().seconds(7).nanos(8).unwrap(),
Duration::new(7, 8).into()
);
}

#[test]
#[should_panic]
fn test_from_extreme_days_panics() {
let _ = CalendarDuration::from(Days::new(1 << 32));
}

#[test]
#[should_panic]
fn test_from_extreme_duration_panics() {
let _ = CalendarDuration::from(Duration::new(1 << 32, 0));
}

#[test]
fn test_display_format() {
assert_eq!(
Expand Down

0 comments on commit 1458553

Please sign in to comment.