cardano_sdk/chain/
hash.rs1use std::fmt;
2
3macro_rules! special_hash {
4 ($name:ident, $size:literal) => {
5 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
6 pub struct $name(pub [u8; $size]);
7
8 impl fmt::Debug for $name {
9 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10 write!(f, "{}", hex::encode(self.0))
11 }
12 }
13
14 impl fmt::Display for $name {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 write!(f, "{}", hex::encode(self.0))
17 }
18 }
19
20 impl $name {
21 pub fn from_hex(s: &str) -> Option<Self> {
22 if s.len() == $size * 2 {
23 match hex::decode(s) {
24 Ok(v) => {
25 let mut out = [0; $size];
26 out.copy_from_slice(&v);
27 Some($name(out))
28 }
29 Err(_) => None,
30 }
31 } else {
32 None
33 }
34 }
35
36 pub fn from_slice(s: &[u8]) -> Option<Self> {
37 if s.len() == $size {
38 let mut out = [0; $size];
39 out.copy_from_slice(&s);
40 Some($name(out))
41 } else {
42 None
43 }
44 }
45
46 pub fn from_bytes(s: [u8; $size]) -> Self {
47 Self(s)
48 }
49 }
50
51 impl ::cbored::Decode for $name {
52 fn decode<'a>(
53 reader: &mut ::cbored::Reader<'a>,
54 ) -> Result<Self, ::cbored::DecodeError> {
55 Ok(Self(reader.decode().map_err(|e| e.push::<Self>())?))
56 }
57 }
58
59 impl ::cbored::Encode for $name {
60 fn encode(&self, writer: &mut ::cbored::Writer) {
61 writer.encode(&self.0)
62 }
63 }
64 };
65}
66
67special_hash!(ByronHash, 32);
68special_hash!(HeaderHash, 32);
69special_hash!(TxHash, 32);
70special_hash!(VRFKeyHash, 32);
71special_hash!(Ed25519KeyHash, 28);
72special_hash!(ScriptHash, 28);
73special_hash!(PoolMetadataHash, 32);
74special_hash!(GenesisDelegateHash, 28);
75special_hash!(GenesisHash, 28);
76special_hash!(ScriptDataHash, 32);
77special_hash!(MetadataHash, 32);