Debian Codegraph @

debian/missing-sources/time/src/serde/timestamp/mod.rs

raw
1 //! Treat an [`OffsetDateTime`] as a [Unix timestamp] for the purposes of serde.
2 //!
3 //! Use this module in combination with serde's [`#[with]`][with] attribute.
4 //!
5 //! When deserializing, the offset is assumed to be UTC.
6 //!
7 //! [Unix timestamp]: https://en.wikipedia.org/wiki/Unix_time
8 //! [with]: https://serde.rs/field-attrs.html#with
9
10 pub mod microseconds;
11 pub mod milliseconds;
12 pub mod milliseconds_i64;
13 pub mod nanoseconds;
14
15 use serde_core::{Deserialize, Deserializer, Serialize, Serializer};
16
17 use crate::OffsetDateTime;
18 use crate::error::ComponentRange;
19
20 /// Serialize an `OffsetDateTime` as its Unix timestamp
21 #[inline]
22 pub fn serialize<S>(datetime: &OffsetDateTime, serializer: S) -> Result<S::Ok, S::Error>
23 where
24 S: Serializer,
25 {
26 datetime.unix_timestamp().serialize(serializer)
27 }
28
29 /// Deserialize an `OffsetDateTime` from its Unix timestamp
30 #[inline]
31 pub fn deserialize<'a, D>(deserializer: D) -> Result<OffsetDateTime, D::Error>
32 where
33 D: Deserializer<'a>,
34 {
35 OffsetDateTime::from_unix_timestamp(<_>::deserialize(deserializer)?)
36 .map_err(ComponentRange::into_de_error)
37 }
38
39 /// Treat an `Option<OffsetDateTime>` as a [Unix timestamp] for the purposes of
40 /// serde.
41 ///
42 /// Use this module in combination with serde's [`#[with]`][with] attribute.
43 ///
44 /// Note: Due to [serde-rs/serde#2878], you will need to apply `#[serde(default)]` if you want a
45 /// missing field to deserialize as `None`.
46 ///
47 /// When deserializing, the offset is assumed to be UTC.
48 ///
49 /// [Unix timestamp]: https://en.wikipedia.org/wiki/Unix_time
50 /// [with]: https://serde.rs/field-attrs.html#with
51 /// [serde-rs/serde#2878]: https://github.com/serde-rs/serde/issues/2878
52 pub mod option {
53 use super::*;
54
55 /// Serialize an `Option<OffsetDateTime>` as its Unix timestamp
56 #[inline]
57 pub fn serialize<S>(option: &Option<OffsetDateTime>, serializer: S) -> Result<S::Ok, S::Error>
58 where
59 S: Serializer,
60 {
61 option
62 .map(OffsetDateTime::unix_timestamp)
63 .serialize(serializer)
64 }
65
66 /// Deserialize an `Option<OffsetDateTime>` from its Unix timestamp
67 #[inline]
68 pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<OffsetDateTime>, D::Error>
69 where
70 D: Deserializer<'a>,
71 {
72 Option::deserialize(deserializer)?
73 .map(OffsetDateTime::from_unix_timestamp)
74 .transpose()
75 .map_err(ComponentRange::into_de_error)
76 }
77 }