use core::fmt;
use crate::{
input::TimeZoneInput,
time_zone::{FormatTimeZone, FormatTimeZoneWithFallback, TimeZoneFormatter},
DateTimeError,
};
use writeable::Writeable;
#[derive(Debug, Copy, Clone)]
pub struct FormattedTimeZone<'l, T>
where
T: TimeZoneInput,
{
pub(crate) time_zone_format: &'l TimeZoneFormatter,
pub(crate) time_zone: &'l T,
}
impl<'l, T> Writeable for FormattedTimeZone<'l, T>
where
T: TimeZoneInput,
{
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
let mut sink = writeable::adapters::CoreWriteAsPartsWrite(sink);
let r = match self.write_no_fallback(&mut sink) {
Ok(fmt_result) => Ok(fmt_result?),
Err(_) => self
.time_zone_format
.fallback_unit
.format_with_last_resort_fallback(
&mut sink,
self.time_zone,
&self.time_zone_format.data_payloads,
)?,
};
debug_assert!(r.is_ok(), "{r:?}");
Ok(())
}
}
impl<'l, T> fmt::Display for FormattedTimeZone<'l, T>
where
T: TimeZoneInput,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.write_to(f)
}
}
impl<'l, T> FormattedTimeZone<'l, T>
where
T: TimeZoneInput,
{
pub fn write_no_fallback<W>(&self, mut w: &mut W) -> Result<fmt::Result, DateTimeError>
where
W: core::fmt::Write + ?Sized,
{
for unit in self.time_zone_format.format_units.iter() {
match unit.format(
&mut writeable::adapters::CoreWriteAsPartsWrite(&mut w),
self.time_zone,
&self.time_zone_format.data_payloads,
) {
Ok(r) => return Ok(r),
Err(DateTimeError::UnsupportedOptions) => continue,
Err(e) => return Err(e),
}
}
Err(DateTimeError::UnsupportedOptions)
}
}