Debian Codegraph @

third_party/rust/time/src/serde/iso8601.rs

raw
1 //! Use the well-known [ISO 8601 format] when serializing and deserializing an [`OffsetDateTime`].
2 //!
3 //! Use this module in combination with serde's [`#[with]`][with] attribute.
4 //!
5 //! [ISO 8601 format]: https://www.iso.org/iso-8601-date-and-time-format.html
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::iso8601::{Config, EncodedConfig};
21 use crate::format_description::well_known::Iso8601;
22 use crate::OffsetDateTime;
23
24 /// The configuration of ISO 8601 used for serde implementations.
25 pub(crate) const SERDE_CONFIG: EncodedConfig =
26 Config::DEFAULT.set_year_is_six_digits(true).encode();
27
28 /// Serialize an [`OffsetDateTime`] using the well-known ISO 8601 format.
29 #[cfg(feature = "formatting")]
30 pub fn serialize<S: Serializer>(
31 datetime: &OffsetDateTime,
32 serializer: S,
33 ) -> Result<S::Ok, S::Error> {
34 datetime
35 .format(&Iso8601::<SERDE_CONFIG>)
36 .map_err(S::Error::custom)?
37 .serialize(serializer)
38 }
39
40 /// Deserialize an [`OffsetDateTime`] from its ISO 8601 representation.
41 #[cfg(feature = "parsing")]
42 pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {
43 deserializer.deserialize_str(Visitor::<Iso8601<SERDE_CONFIG>>(PhantomData))
44 }
45
46 /// Use the well-known ISO 8601 format when serializing and deserializing an
47 /// [`Option<OffsetDateTime>`].
48 ///
49 /// Use this module in combination with serde's [`#[with]`][with] attribute.
50 ///
51 /// [ISO 8601 format]: https://www.iso.org/iso-8601-date-and-time-format.html
52 /// [with]: https://serde.rs/field-attrs.html#with
53 pub mod option {
54 #[allow(clippy::wildcard_imports)]
55 use super::*;
56
57 /// Serialize an [`Option<OffsetDateTime>`] using the well-known ISO 8601 format.
58 #[cfg(feature = "formatting")]
59 pub fn serialize<S: Serializer>(
60 option: &Option<OffsetDateTime>,
61 serializer: S,
62 ) -> Result<S::Ok, S::Error> {
63 option
64 .map(|odt| odt.format(&Iso8601::<SERDE_CONFIG>))
65 .transpose()
66 .map_err(S::Error::custom)?
67 .serialize(serializer)
68 }
69
70 /// Deserialize an [`Option<OffsetDateTime>`] from its ISO 8601 representation.
71 #[cfg(feature = "parsing")]
72 pub fn deserialize<'a, D: Deserializer<'a>>(
73 deserializer: D,
74 ) -> Result<Option<OffsetDateTime>, D::Error> {
75 deserializer.deserialize_option(Visitor::<Option<Iso8601<SERDE_CONFIG>>>(PhantomData))
76 }
77 }