From 58e41e9f33898339dadbbdc9acd67eb8c244bbbc Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Mon, 15 Apr 2019 09:27:46 -0700 Subject: [PATCH] tendermint-rs: Impl FromStr, Deserialize, and Serialize for Hash Support for serializing and deserializing hash values from hex strings --- tendermint-rs/src/hash.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/tendermint-rs/src/hash.rs b/tendermint-rs/src/hash.rs index 8bebfe2..37fc178 100644 --- a/tendermint-rs/src/hash.rs +++ b/tendermint-rs/src/hash.rs @@ -1,7 +1,12 @@ //! Hash functions and their outputs use crate::{algorithm::HashAlgorithm, error::Error}; -use std::fmt::{self, Display}; +#[cfg(feature = "serde")] +use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; +use std::{ + fmt::{self, Display}, + str::FromStr, +}; use subtle_encoding::{Encoding, Hex}; /// Output size for the SHA-256 hash function @@ -65,3 +70,26 @@ impl Display for Hash { write!(f, "{}", hex) } } + +impl FromStr for Hash { + type Err = Error; + + fn from_str(s: &str) -> Result { + Self::from_hex_upper(HashAlgorithm::Sha256, s) + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for Hash { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::from_str(&String::deserialize(deserializer)?) + .map_err(|e| D::Error::custom(format!("{}", e)))?) + } +} + +#[cfg(feature = "serde")] +impl Serialize for Hash { + fn serialize(&self, serializer: S) -> Result { + self.to_string().serialize(serializer) + } +}