Skip to content

Commit

Permalink
feat: to from hex string for Hash
Browse files Browse the repository at this point in the history
  • Loading branch information
grumbach committed Mar 2, 2023
1 parent 1c9d701 commit f20e23c
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// permissions and limitations relating to use of the SAFE Network Software.

use std::fmt;
use std::str::FromStr;

mod amount_secrets;
mod blst;
Expand Down Expand Up @@ -63,6 +64,34 @@ impl Hash {
pub fn hash(input: &[u8]) -> Self {
Self::from(sha3_256(input))
}

/// Deserializes a `Hash` represented as a hex string to a `Hash`.
#[cfg(feature = "serde")]
pub fn from_hex(hex: &str) -> Result<Self, Error> {
let mut bytes =
hex::decode(hex).map_err(|e| Error::HexDeserializationFailed(e.to_string()))?;
bytes.reverse();
let h: Hash = bincode::deserialize(&bytes)
.map_err(|e| Error::HexDeserializationFailed(e.to_string()))?;
Ok(h)
}

/// Serialize this `Hash` instance to a hex string.
#[cfg(feature = "serde")]
pub fn to_hex(&self) -> Result<String, Error> {
let mut serialized =
bincode::serialize(&self).map_err(|e| Error::HexSerializationFailed(e.to_string()))?;
serialized.reverse();
Ok(hex::encode(serialized))
}
}

impl FromStr for Hash {
type Err = Error;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Hash::from_hex(s)
}
}

impl From<[u8; 32]> for Hash {
Expand Down

0 comments on commit f20e23c

Please sign in to comment.