use jiff::civil::DateTime;
use jiff::tz::TimeZone;
use jiff::{SignedDuration, Timestamp, ToSpan};
use super::{DateError, Instants, SearchDate};
const NANO_DIGITS: usize = 9;
impl SearchDate {
pub fn instants(&self, zone: &TimeZone) -> Result<Instants, DateError> {
let range = self.range();
let from = range.low.instant(zone).ok_or(DateError::Unrepresentable)?;
let until = range.high.and_then(|high| high.instant(zone));
Ok(Instants { from, until })
}
pub fn approximate(&self, zone: &TimeZone, now: Timestamp) -> Result<Instants, DateError> {
let exact = self.instants(zone)?;
let gap = if now < exact.from {
exact.from.duration_since(now)
} else {
match exact.until {
Some(until) if now >= until => now.duration_since(until),
_ => SignedDuration::ZERO,
}
};
let margin = gap / 10;
let from = exact.from.checked_sub(margin).unwrap_or(Timestamp::MIN);
let until = exact.until.and_then(|until| until.checked_add(margin).ok());
Ok(Instants { from, until })
}
fn instant(&self, zone: &TimeZone) -> Option<Timestamp> {
let (seconds, nanos, round_up) =
match self.time.as_ref().and_then(|clock| clock.second.as_ref()) {
None => (0, 0, false),
Some(second) => {
let digits = second.fraction.as_deref().unwrap_or("");
let (kept, rest) = digits.split_at_checked(NANO_DIGITS).unwrap_or((digits, ""));
let nanos: i32 = format!("{kept:0<NANO_DIGITS$}").parse().ok()?;
(second.whole, nanos, rest.bytes().any(|byte| byte != b'0'))
}
};
let (hour, minute) = self
.time
.as_ref()
.map_or((0, 0), |clock| (clock.hour, clock.minute));
let civil = DateTime::new(
self.year,
self.month.unwrap_or(1),
self.day.unwrap_or(1),
hour,
minute,
seconds,
nanos,
)
.ok()?;
let civil = if round_up {
civil.checked_add(1.nanosecond()).ok()?
} else {
civil
};
let instant = match self.offset() {
Some(offset) => jiff::tz::Offset::from_seconds(offset.seconds())
.ok()?
.to_timestamp(civil)
.ok()?,
None => civil.to_zoned(zone.clone()).ok()?.timestamp(),
};
Some(instant)
}
}