From 6193c9d9742d1d19a45a0ee1c383858201304912 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 7 Mar 2022 12:36:09 +0000 Subject: [PATCH] humantime_serde_option: New module in tor-basic-utils This will be used to allow our config *builder* structs to be Deserialize. --- Cargo.lock | 2 ++ crates/tor-basic-utils/Cargo.toml | 6 +++++ .../src/humantime_serde_option.rs | 24 +++++++++++++++++++ crates/tor-basic-utils/src/lib.rs | 3 +++ 4 files changed, 35 insertions(+) create mode 100644 crates/tor-basic-utils/src/humantime_serde_option.rs diff --git a/Cargo.lock b/Cargo.lock index 2d6fc8ffa..f69166f3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3098,6 +3098,8 @@ name = "tor-basic-utils" version = "0.1.0" dependencies = [ "educe", + "humantime-serde", + "serde", ] [[package]] diff --git a/crates/tor-basic-utils/Cargo.toml b/crates/tor-basic-utils/Cargo.toml index e9ec80611..ce445b123 100644 --- a/crates/tor-basic-utils/Cargo.toml +++ b/crates/tor-basic-utils/Cargo.toml @@ -11,6 +11,12 @@ categories = ["rust-patterns"] # We must put *something* here and this will do repository = "https://gitlab.torproject.org/tpo/core/arti.git/" [dependencies] +serde = { version = "1.0.103", features = ["derive"], optional = true } +humantime-serde-crate = { package = "humantime-serde", version = "1", optional = true } + +[features] +default = ["humantime-serde"] +humantime-serde = ["humantime-serde-crate", "serde"] [dev-dependencies] educe = "0.4.6" diff --git a/crates/tor-basic-utils/src/humantime_serde_option.rs b/crates/tor-basic-utils/src/humantime_serde_option.rs new file mode 100644 index 000000000..c2f4ef8f3 --- /dev/null +++ b/crates/tor-basic-utils/src/humantime_serde_option.rs @@ -0,0 +1,24 @@ +//! Module to adaopt `humantime_serde` to `Option` + +use humantime_serde_crate::Serde as HtSerde; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// Serializes an `Option` or `Option` via the humantime crate. +pub fn serialize(d: &Option, s: S) -> Result +where + for<'a> HtSerde<&'a T>: Serialize, + S: Serializer, +{ + let nested: Option> = d.as_ref().map(Into::into); + nested.serialize(s) +} + +/// Deserialize an `Option` or `Option` via the humantime crate. +pub fn deserialize<'a, T, D>(d: D) -> Result, D::Error> +where + HtSerde: Deserialize<'a>, + D: Deserializer<'a>, +{ + let got: Option> = Deserialize::deserialize(d)?; + Ok(got.map(HtSerde::into_inner)) +} diff --git a/crates/tor-basic-utils/src/lib.rs b/crates/tor-basic-utils/src/lib.rs index 811cb6866..fc09b6210 100644 --- a/crates/tor-basic-utils/src/lib.rs +++ b/crates/tor-basic-utils/src/lib.rs @@ -41,6 +41,9 @@ use std::fmt; +#[cfg(feature = "humantime-serde")] +pub mod humantime_serde_option; + // ---------------------------------------------------------------------- /// Function with the signature of `Debug::fmt` that just prints `".."`