Skip to content
This repository has been archived by the owner on Jun 3, 2020. It is now read-only.

Commit

Permalink
tendermint-rs: Impl FromStr, Deserialize, and Serialize for Hash
Browse files Browse the repository at this point in the history
Support for serializing and deserializing hash values from hex strings
  • Loading branch information
tony-iqlusion committed Apr 15, 2019
1 parent 934f7d8 commit 58e41e9
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion tendermint-rs/src/hash.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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, Error> {
Self::from_hex_upper(HashAlgorithm::Sha256, s)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Hash {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::from_str(&String::deserialize(deserializer)?)
.map_err(|e| D::Error::custom(format!("{}", e)))?)
}
}

#[cfg(feature = "serde")]
impl Serialize for Hash {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.to_string().serialize(serializer)
}
}

0 comments on commit 58e41e9

Please sign in to comment.