leaf_protocol_types/
digest.rs1use std::str::FromStr;
4
5use iroh_base::hash::Hash;
6
7#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct Digest(pub Hash);
10impl Default for Digest {
11 fn default() -> Self {
12 Self(Hash::from_bytes([0; 32]))
13 }
14}
15impl From<Digest> for Hash {
16 fn from(val: Digest) -> Self {
17 val.0
18 }
19}
20impl Digest {
21 pub fn new(bytes: &[u8]) -> Self {
22 Self(Hash::new(bytes))
23 }
24 pub fn from_bytes(bytes: [u8; 32]) -> Self {
25 Self(Hash::from_bytes(bytes))
26 }
27}
28impl std::fmt::Debug for Digest {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.debug_tuple("Digest")
31 .field(&format_args!("{}", self.0))
32 .finish()
33 }
34}
35impl FromStr for Digest {
36 type Err = <Hash as FromStr>::Err;
37 fn from_str(s: &str) -> Result<Self, Self::Err> {
38 Ok(Self(FromStr::from_str(s)?))
39 }
40}
41impl std::fmt::Display for Digest {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 self.0.fmt(f)
44 }
45}
46impl From<Hash> for Digest {
47 fn from(value: Hash) -> Self {
48 Self(value)
49 }
50}
51impl borsh::BorshSerialize for Digest {
52 fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
53 <[u8; 32] as borsh::BorshSerialize>::serialize(self.0.as_bytes(), writer)
54 }
55}
56impl borsh::BorshDeserialize for Digest {
57 fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
58 let bytes = <[u8; 32] as borsh::BorshDeserialize>::deserialize_reader(reader)?;
59 Ok(Digest(Hash::from_bytes(bytes)))
60 }
61}
62impl std::ops::Deref for Digest {
63 type Target = Hash;
64 fn deref(&self) -> &Self::Target {
65 &self.0
66 }
67}
68impl std::ops::DerefMut for Digest {
69 fn deref_mut(&mut self) -> &mut Self::Target {
70 &mut self.0
71 }
72}