time/serde/
rfc2822.rs

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")]
9use core::marker::PhantomData;
10
11#[cfg(feature = "formatting")]
12use serde::ser::Error as _;
13#[cfg(feature = "parsing")]
14use serde::Deserializer;
15#[cfg(feature = "formatting")]
16use serde::{Serialize, Serializer};
17
18#[cfg(feature = "parsing")]
19use super::Visitor;
20use crate::format_description::well_known::Rfc2822;
21use crate::OffsetDateTime;
22
23/// Serialize an [`OffsetDateTime`] using the well-known RFC2822 format.
24#[cfg(feature = "formatting")]
25pub 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")]
37pub 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
48pub mod option {
49    use super::*;
50
51    /// Serialize an [`Option<OffsetDateTime>`] using the well-known RFC2822 format.
52    #[cfg(feature = "formatting")]
53    pub fn serialize<S: Serializer>(
54        option: &Option<OffsetDateTime>,
55        serializer: S,
56    ) -> Result<S::Ok, S::Error> {
57        option
58            .map(|odt| odt.format(&Rfc2822))
59            .transpose()
60            .map_err(S::Error::custom)?
61            .serialize(serializer)
62    }
63
64    /// Deserialize an [`Option<OffsetDateTime>`] from its RFC2822 representation.
65    #[cfg(feature = "parsing")]
66    pub fn deserialize<'a, D: Deserializer<'a>>(
67        deserializer: D,
68    ) -> Result<Option<OffsetDateTime>, D::Error> {
69        deserializer.deserialize_option(Visitor::<Option<Rfc2822>>(PhantomData))
70    }
71}