63 lines
2.1 KiB
Rust
63 lines
2.1 KiB
Rust
//! Use the well-known [RFC2822 format] when serializing and deserializing an [`OffsetDateTime`].
|
|
//!
|
|
//! Use this module in combination with serde's [`#[with]`][with] attribute.
|
|
//!
|
|
//! [RFC2822 format]: https://tools.ietf.org/html/rfc2822#section-3.3
|
|
//! [with]: https://serde.rs/field-attrs.html#with
|
|
|
|
use core::marker::PhantomData;
|
|
|
|
use serde::ser::Error as _;
|
|
use serde::{Deserializer, Serialize, Serializer};
|
|
|
|
use super::Visitor;
|
|
use crate::format_description::well_known::Rfc2822;
|
|
use crate::OffsetDateTime;
|
|
|
|
/// Serialize an [`OffsetDateTime`] using the well-known RFC2822 format.
|
|
pub fn serialize<S: Serializer>(
|
|
datetime: &OffsetDateTime,
|
|
serializer: S,
|
|
) -> Result<S::Ok, S::Error> {
|
|
datetime
|
|
.format(&Rfc2822)
|
|
.map_err(S::Error::custom)?
|
|
.serialize(serializer)
|
|
}
|
|
|
|
/// Deserialize an [`OffsetDateTime`] from its RFC2822 representation.
|
|
pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {
|
|
deserializer.deserialize_any(Visitor::<Rfc2822>(PhantomData))
|
|
}
|
|
|
|
/// Use the well-known [RFC2822 format] when serializing and deserializing an
|
|
/// [`Option<OffsetDateTime>`].
|
|
///
|
|
/// Use this module in combination with serde's [`#[with]`][with] attribute.
|
|
///
|
|
/// [RFC2822 format]: https://tools.ietf.org/html/rfc2822#section-3.3
|
|
/// [with]: https://serde.rs/field-attrs.html#with
|
|
pub mod option {
|
|
#[allow(clippy::wildcard_imports)]
|
|
use super::*;
|
|
|
|
/// Serialize an [`Option<OffsetDateTime>`] using the well-known RFC2822 format.
|
|
pub fn serialize<S: Serializer>(
|
|
option: &Option<OffsetDateTime>,
|
|
serializer: S,
|
|
) -> Result<S::Ok, S::Error> {
|
|
option
|
|
.map(|odt| odt.format(&Rfc2822))
|
|
.transpose()
|
|
.map_err(S::Error::custom)?
|
|
.serialize(serializer)
|
|
}
|
|
|
|
/// Deserialize an [`Option<OffsetDateTime>`] from its RFC2822 representation.
|
|
pub fn deserialize<'a, D: Deserializer<'a>>(
|
|
deserializer: D,
|
|
) -> Result<Option<OffsetDateTime>, D::Error> {
|
|
deserializer.deserialize_option(Visitor::<Option<Rfc2822>>(PhantomData))
|
|
}
|
|
}
|