//! Treat an [`OffsetDateTime`] as a [Unix timestamp] for the purposes of serde. //! //! Use this module in combination with serde's [`#[with]`][with] attribute. //! //! When deserializing, the offset is assumed to be UTC. //! //! [Unix timestamp]: https://en.wikipedia.org/wiki/Unix_time //! [with]: https://serde.rs/field-attrs.html#with use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use crate::OffsetDateTime; /// Serialize an `OffsetDateTime` as its Unix timestamp pub fn serialize( datetime: &OffsetDateTime, serializer: S, ) -> Result { datetime.unix_timestamp().serialize(serializer) } /// Deserialize an `OffsetDateTime` from its Unix timestamp pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result { OffsetDateTime::from_unix_timestamp(<_>::deserialize(deserializer)?) .map_err(|err| de::Error::invalid_value(de::Unexpected::Signed(err.value), &err)) } /// Treat an `Option` as a [Unix timestamp] for the purposes of /// serde. /// /// Use this module in combination with serde's [`#[with]`][with] attribute. /// /// When deserializing, the offset is assumed to be UTC. /// /// [Unix timestamp]: https://en.wikipedia.org/wiki/Unix_time /// [with]: https://serde.rs/field-attrs.html#with pub mod option { #[allow(clippy::wildcard_imports)] use super::*; /// Serialize an `Option` as its Unix timestamp pub fn serialize( option: &Option, serializer: S, ) -> Result { option .map(OffsetDateTime::unix_timestamp) .serialize(serializer) } /// Deserialize an `Option` from its Unix timestamp pub fn deserialize<'a, D: Deserializer<'a>>( deserializer: D, ) -> Result, D::Error> { Option::deserialize(deserializer)? .map(OffsetDateTime::from_unix_timestamp) .transpose() .map_err(|err| de::Error::invalid_value(de::Unexpected::Signed(err.value), &err)) } }