use serde::{Deserialize, Deserializer};
use crate::{Error, LocalTime, Location, Network, Timestamp};
const YEARS_1_TO_9999: std::ops::Range<i64> = -62_135_596_800..253_402_300_800;
pub(crate) struct WireTime(pub(crate) Timestamp);
impl<'de> Deserialize<'de> for WireTime {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
let time: jiff::Timestamp = text.trim().parse().map_err(serde::de::Error::custom)?;
let time = Timestamp {
unix_seconds: time.as_second(),
};
if !YEARS_1_TO_9999.contains(&time.unix_seconds) {
return Err(serde::de::Error::custom("time outside the years 1 to 9999"));
}
Ok(Self(time))
}
}
impl Timestamp {
pub(crate) fn to_jiff(self) -> Result<jiff::Timestamp, Error> {
jiff::Timestamp::from_second(self.unix_seconds)
.ok()
.filter(|_| YEARS_1_TO_9999.contains(&self.unix_seconds))
.ok_or_else(|| Error::InvalidQuery {
message: "the time is outside the years 1 to 9999".to_owned(),
})
}
}
#[cfg(any(feature = "uniffi", feature = "unstable-wasm"))]
impl LocalTime {
pub(crate) fn iso_8601(self) -> String {
let offset = self.utc_offset_seconds.unsigned_abs();
let seconds = match offset % 60 {
0 => String::new(),
seconds => format!(":{seconds:02}"),
};
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}{seconds}",
self.year,
self.month,
self.day,
self.hour,
self.minute,
self.second,
if self.utc_offset_seconds < 0 {
'-'
} else {
'+'
},
offset / 3600,
offset / 60 % 60,
)
}
}
impl Location {
#[must_use]
pub fn local_time(&self, time: Timestamp) -> Option<LocalTime> {
let zone = jiff::tz::TimeZone::get(self.timezone.as_deref()?).ok()?;
if zone.is_unknown() {
return None;
}
let local = time.to_jiff().ok()?.to_zoned_datetime(zone);
let year = u16::try_from(local.year()).ok().filter(|year| *year >= 1)?;
Some(LocalTime {
year,
month: u8::try_from(local.month()).ok()?,
day: u8::try_from(local.day()).ok()?,
hour: u8::try_from(local.hour()).ok()?,
minute: u8::try_from(local.minute()).ok()?,
second: u8::try_from(local.second()).ok()?,
utc_offset_seconds: local.offset().seconds(),
})
}
}
impl Network {
pub(crate) fn zone(&self) -> Result<jiff::tz::TimeZone, Error> {
let zone = self
.timezone
.as_deref()
.ok_or_else(|| Error::InvalidNetwork {
message: "local times need the network's time zone".to_owned(),
})?;
jiff::tz::TimeZone::get(zone).map_err(|error| Error::InvalidNetwork {
message: error.to_string(),
})
}
pub(crate) fn local(&self, time: Timestamp) -> Result<jiff::ZonedDateTime, Error> {
let local = time.to_jiff()?.to_zoned_datetime(self.zone()?);
if !(1..=9999).contains(&local.year()) {
return Err(Error::InvalidQuery {
message: "the time is outside the years 1 to 9999".to_owned(),
});
}
Ok(local)
}
}