Bladeren bron

Improve conversion

Cesar Rodas 1 jaar geleden
bovenliggende
commit
3e6a8755ad
2 gewijzigde bestanden met toevoegingen van 22 en 7 verwijderingen
  1. 8 0
      crates/types/src/types/addr.rs
  2. 14 7
      crates/types/src/types/id.rs

+ 8 - 0
crates/types/src/types/addr.rs

@@ -4,6 +4,8 @@
 //!
 //!
 //! It can also parse the bech32 version of the public key if provided (used by
 //! It can also parse the bech32 version of the public key if provided (used by
 //! clients mostly)
 //! clients mostly)
+use std::hash::Hash;
+
 use bech32::{self, FromBase32, ToBase32, Variant};
 use bech32::{self, FromBase32, ToBase32, Variant};
 use serde::{
 use serde::{
     de::{self, Deserialize, Deserializer},
     de::{self, Deserialize, Deserializer},
@@ -66,6 +68,12 @@ pub struct Addr {
     pub hrp: Option<HumanReadablePart>,
     pub hrp: Option<HumanReadablePart>,
 }
 }
 
 
+impl Hash for Addr {
+    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+        self.bytes.hash(state)
+    }
+}
+
 impl Addr {
 impl Addr {
     /// Instantiates a new Addr from a hex string with an optional human
     /// Instantiates a new Addr from a hex string with an optional human
     /// readable part
     /// readable part

+ 14 - 7
crates/types/src/types/id.rs

@@ -9,7 +9,7 @@ use std::ops::Deref;
 /// Event Id
 /// Event Id
 ///
 ///
 /// Event Id are raw 32 bytes and 64-character length hex encoded to JSON
 /// Event Id are raw 32 bytes and 64-character length hex encoded to JSON
-#[derive(Debug, Clone, Eq, PartialEq)]
+#[derive(Debug, Clone, Hash, Eq, PartialEq)]
 pub struct Id(pub [u8; 32]);
 pub struct Id(pub [u8; 32]);
 
 
 impl Deref for Id {
 impl Deref for Id {
@@ -25,18 +25,25 @@ impl ToString for Id {
     }
     }
 }
 }
 
 
+impl TryFrom<String> for Id {
+    type Error = String;
+    fn try_from(value: String) -> Result<Self, Self::Error> {
+        Ok(Self(
+            hex::decode(&value)
+                .map_err(|e| e.to_string())?
+                .try_into()
+                .map_err(|_| "Invalid length for Id".to_string())?,
+        ))
+    }
+}
+
 impl<'de> Deserialize<'de> for Id {
 impl<'de> Deserialize<'de> for Id {
     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
     where
     where
         D: Deserializer<'de>,
         D: Deserializer<'de>,
     {
     {
         let s = <String>::deserialize(deserializer)?;
         let s = <String>::deserialize(deserializer)?;
-        let id: [u8; 32] = hex::decode(&s)
-            .map_err(|e| de::Error::custom(e.to_string()))?
-            .try_into()
-            .map_err(|_| de::Error::custom("Invalid length for Id"))?;
-
-        Ok(Self(id))
+        s.try_into().map_err(|e| de::Error::custom(e))
     }
     }
 }
 }