From 84d0859ddb41ef2b54328ea48e617b5bbf7cc6e8 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 9 Dec 2020 10:19:17 +0100 Subject: [PATCH] document forward_de/serialize_to_display/from_str Signed-off-by: Wolfgang Bumiller --- proxmox/src/serde_macros.rs | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/proxmox/src/serde_macros.rs b/proxmox/src/serde_macros.rs index 79cd2f8a..bcf763a8 100644 --- a/proxmox/src/serde_macros.rs +++ b/proxmox/src/serde_macros.rs @@ -1,3 +1,25 @@ +/// Given a type which implements [`FromStr`](std::str::FromStr), derive +/// [`Deserialize`](serde::Deserialize) by using the [`from_str`](std::str::FromStr::from_str()) +/// method. +/// +/// ``` +/// # use std::str::FromStr; +/// # use anyhow::bail; +/// # use proxmox::forward_deserialize_to_from_str; +/// struct AsciiAlnum(String); +/// +/// impl FromStr for AsciiAlnum { +/// type Err = anyhow::Error; +/// fn from_str(s: &str) -> Result { +/// if s.as_bytes().iter().any(|&b| !b.is_ascii_alphanumeric()) { +/// bail!("invalid non-ascii-alphanumeric characters in string"); +/// } +/// Ok(Self(s.to_string())) +/// } +/// } +/// +/// forward_deserialize_to_from_str!(AsciiAlnum); +/// ``` #[macro_export] macro_rules! forward_deserialize_to_from_str { ($typename:ty) => { @@ -29,6 +51,24 @@ macro_rules! forward_deserialize_to_from_str { }; } +/// Given a type which implements [`Display`], derive [`Serialize`](serde::Serialize) by using the +/// [`Display`] trait. +/// +/// ``` +/// # use std::fmt; +/// # use proxmox::forward_serialize_to_display; +/// struct DoubleAngleBracketed(String); +/// +/// impl fmt::Display for DoubleAngleBracketed { +/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +/// write!(f, "<<{}>>", self.0) +/// } +/// } +/// +/// forward_serialize_to_display!(DoubleAngleBracketed); +/// ``` +/// +/// [`Display`]: std::fmt::Display #[macro_export] macro_rules! forward_serialize_to_display { ($typename:ty) => {