humantime_serde/option.rs
1//! Convenience module to allow serialization via `humantime_serde` for `Option`
2//!
3//! # Example
4//!
5//! ```
6//! use serde::{Serialize, Deserialize};
7//! use std::time::{Duration, SystemTime};
8//!
9//! #[derive(Serialize, Deserialize)]
10//! struct Foo {
11//! #[serde(with = "humantime_serde::option")]
12//! timeout: Option<Duration>,
13//! #[serde(default)]
14//! #[serde(with = "humantime_serde::option")]
15//! time: Option<SystemTime>,
16//! }
17//! ```
18
19use super::Serde;
20use serde::{Deserialize, Deserializer, Serialize, Serializer};
21
22/// Serializes an `Option<Duration>` or `Option<SystemTime>`
23///
24/// This function can be used with `serde_derive`'s `with` and
25/// `deserialize_with` annotations.
26pub fn serialize<T, S>(d: &Option<T>, s: S) -> Result<S::Ok, S::Error>
27where
28 for<'a> Serde<&'a T>: Serialize,
29 S: Serializer,
30{
31 let nested: Option<Serde<&T>> = d.as_ref().map(Into::into);
32 nested.serialize(s)
33}
34
35/// Deserialize an `Option<Duration>` or `Option<SystemTime>`
36///
37/// This function can be used with `serde_derive`'s `with` and
38/// `deserialize_with` annotations.
39pub fn deserialize<'a, T, D>(d: D) -> Result<Option<T>, D::Error>
40where
41 Serde<T>: Deserialize<'a>,
42 D: Deserializer<'a>,
43{
44 let got: Option<Serde<T>> = Deserialize::deserialize(d)?;
45 Ok(got.map(Serde::into_inner))
46}