human_bandwidth/
option.rs

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