Debian Codegraph @

third_party/rust/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 nanoseconds;
13
14 use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
15
16 use crate::OffsetDateTime;
17
18 /// Serialize an `OffsetDateTime` as its Unix timestamp
19 pub fn serialize<S: Serializer>(
20 datetime: &OffsetDateTime,
21 serializer: S,
22 ) -> Result<S::Ok, S::Error> {
23 datetime.unix_timestamp().serialize(serializer)
24 }
25
26 /// Deserialize an `OffsetDateTime` from its Unix timestamp
27 pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {
28 OffsetDateTime::from_unix_timestamp(<_>::deserialize(deserializer)?)
29 .map_err(|err| de::Error::invalid_value(de::Unexpected::Signed(err.value), &err))
30 }
31
32 /// Treat an `Option<OffsetDateTime>` as a [Unix timestamp] for the purposes of
33 /// serde.
34 ///
35 /// Use this module in combination with serde's [`#[with]`][with] attribute.
36 ///
37 /// When deserializing, the offset is assumed to be UTC.
38 ///
39 /// [Unix timestamp]: https://en.wikipedia.org/wiki/Unix_time
40 /// [with]: https://serde.rs/field-attrs.html#with
41 pub mod option {
42 #[allow(clippy::wildcard_imports)]
43 use super::*;
44
45 /// Serialize an `Option<OffsetDateTime>` as its Unix timestamp
46 pub fn serialize<S: Serializer>(
47 option: &Option<OffsetDateTime>,
48 serializer: S,
49 ) -> Result<S::Ok, S::Error> {
50 option
51 .map(OffsetDateTime::unix_timestamp)
52 .serialize(serializer)
53 }
54
55 /// Deserialize an `Option<OffsetDateTime>` from its Unix timestamp
56 pub fn deserialize<'a, D: Deserializer<'a>>(
57 deserializer: D,
58 ) -> Result<Option<OffsetDateTime>, D::Error> {
59 Option::deserialize(deserializer)?
60 .map(OffsetDateTime::from_unix_timestamp)
61 .transpose()
62 .map_err(|err| de::Error::invalid_value(de::Unexpected::Signed(err.value), &err))
63 }
64 }