use crate::{Duration, Error, Instant};
use ::jiff::{SignedDuration, Timestamp};
impl TryFrom<Timestamp> for Instant {
type Error = Error;
fn try_from(timestamp: Timestamp) -> Result<Self, Error> {
Self::from_unix_nanoseconds(timestamp.as_nanosecond()).ok_or_else(|| {
Error::data(format!(
"The timestamp {timestamp} is outside the years 0001 to 9999"
))
})
}
}
impl TryFrom<Instant> for Timestamp {
type Error = Error;
fn try_from(instant: Instant) -> Result<Self, Error> {
Self::new(instant.unix_seconds(), instant.nanoseconds() as i32).map_err(|error| {
Error::data(format!(
"The instant {instant} is outside the range of a jiff timestamp: {error}"
))
})
}
}
impl TryFrom<SignedDuration> for Duration {
type Error = Error;
fn try_from(duration: SignedDuration) -> Result<Self, Error> {
i64::try_from(duration.as_nanos())
.map(Self::from_nanoseconds)
.map_err(|_| {
Error::data(format!(
"The duration {duration:?} is outside the SOML range of about 292 years"
))
})
}
}
impl From<Duration> for SignedDuration {
fn from(duration: Duration) -> Self {
Self::from_nanos(duration.nanoseconds())
}
}
serde_with_module! {
timestamp, ::jiff::Timestamp, crate::Instant
}
serde_with_module! {
signed_duration, ::jiff::SignedDuration, crate::Duration
}