| 1 |
//! Use the well-known [RFC2822 format] when serializing and deserializing an [`OffsetDateTime`]. |
| 2 |
//! |
| 3 |
//! Use this module in combination with serde's [`#[with]`][with] attribute. |
| 4 |
//! |
| 5 |
//! [RFC2822 format]: https://tools.ietf.org/html/rfc2822#section-3.3 |
| 6 |
//! [with]: https://serde.rs/field-attrs.html#with |
| 7 |
|
| 8 |
#[cfg(feature = "parsing")] |
| 9 |
use core::marker::PhantomData; |
| 10 |
|
| 11 |
#[cfg(feature = "formatting")] |
| 12 |
use serde::ser::Error as _; |
| 13 |
#[cfg(feature = "parsing")] |
| 14 |
use serde::Deserializer; |
| 15 |
#[cfg(feature = "formatting")] |
| 16 |
use serde::{Serialize, Serializer}; |
| 17 |
|
| 18 |
#[cfg(feature = "parsing")] |
| 19 |
use super::Visitor; |
| 20 |
use crate::format_description::well_known::Rfc2822; |
| 21 |
use crate::OffsetDateTime; |
| 22 |
|
| 23 |
/// Serialize an [`OffsetDateTime`] using the well-known RFC2822 format. |
| 24 |
#[cfg(feature = "formatting")] |
| 25 |
pub fn serialize<S: Serializer>( |
| 26 |
datetime: &OffsetDateTime, |
| 27 |
serializer: S, |
| 28 |
) -> Result<S::Ok, S::Error> { |
| 29 |
datetime |
| 30 |
.format(&Rfc2822) |
| 31 |
.map_err(S::Error::custom)? |
| 32 |
.serialize(serializer) |
| 33 |
} |
| 34 |
|
| 35 |
/// Deserialize an [`OffsetDateTime`] from its RFC2822 representation. |
| 36 |
#[cfg(feature = "parsing")] |
| 37 |
pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> { |
| 38 |
deserializer.deserialize_str(Visitor::<Rfc2822>(PhantomData)) |
| 39 |
} |
| 40 |
|
| 41 |
/// Use the well-known [RFC2822 format] when serializing and deserializing an |
| 42 |
/// [`Option<OffsetDateTime>`]. |
| 43 |
/// |
| 44 |
/// Use this module in combination with serde's [`#[with]`][with] attribute. |
| 45 |
/// |
| 46 |
/// [RFC2822 format]: https://tools.ietf.org/html/rfc2822#section-3.3 |
| 47 |
/// [with]: https://serde.rs/field-attrs.html#with |
| 48 |
pub mod option { |
| 49 |
#[allow(clippy::wildcard_imports)] |
| 50 |
use super::*; |
| 51 |
|
| 52 |
/// Serialize an [`Option<OffsetDateTime>`] using the well-known RFC2822 format. |
| 53 |
#[cfg(feature = "formatting")] |
| 54 |
pub fn serialize<S: Serializer>( |
| 55 |
option: &Option<OffsetDateTime>, |
| 56 |
serializer: S, |
| 57 |
) -> Result<S::Ok, S::Error> { |
| 58 |
option |
| 59 |
.map(|odt| odt.format(&Rfc2822)) |
| 60 |
.transpose() |
| 61 |
.map_err(S::Error::custom)? |
| 62 |
.serialize(serializer) |
| 63 |
} |
| 64 |
|
| 65 |
/// Deserialize an [`Option<OffsetDateTime>`] from its RFC2822 representation. |
| 66 |
#[cfg(feature = "parsing")] |
| 67 |
pub fn deserialize<'a, D: Deserializer<'a>>( |
| 68 |
deserializer: D, |
| 69 |
) -> Result<Option<OffsetDateTime>, D::Error> { |
| 70 |
deserializer.deserialize_option(Visitor::<Option<Rfc2822>>(PhantomData)) |
| 71 |
} |
| 72 |
} |