#[cfg(feature = "parsing")]
use core::marker::PhantomData;
#[cfg(feature = "formatting")]
use serde::ser::Error as _;
#[cfg(feature = "parsing")]
use serde::Deserializer;
#[cfg(feature = "formatting")]
use serde::{Serialize, Serializer};
#[cfg(feature = "parsing")]
use super::Visitor;
use crate::format_description::well_known::iso8601::{Config, EncodedConfig};
use crate::format_description::well_known::Iso8601;
use crate::OffsetDateTime;
pub(crate) const SERDE_CONFIG: EncodedConfig =
Config::DEFAULT.set_year_is_six_digits(true).encode();
#[cfg(feature = "formatting")]
pub fn serialize<S: Serializer>(
datetime: &OffsetDateTime,
serializer: S,
) -> Result<S::Ok, S::Error> {
datetime
.format(&Iso8601::<SERDE_CONFIG>)
.map_err(S::Error::custom)?
.serialize(serializer)
}
#[cfg(feature = "parsing")]
pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {
deserializer.deserialize_str(Visitor::<Iso8601<SERDE_CONFIG>>(PhantomData))
}
pub mod option {
#[allow(clippy::wildcard_imports)]
use super::*;
#[cfg(feature = "formatting")]
pub fn serialize<S: Serializer>(
option: &Option<OffsetDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error> {
option
.map(|odt| odt.format(&Iso8601::<SERDE_CONFIG>))
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
#[cfg(feature = "parsing")]
pub fn deserialize<'a, D: Deserializer<'a>>(
deserializer: D,
) -> Result<Option<OffsetDateTime>, D::Error> {
deserializer.deserialize_option(Visitor::<Option<Iso8601<SERDE_CONFIG>>>(PhantomData))
}
}