bee_block/payload/milestone/
merkle.rs

1// Copyright 2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::Error;
5
6/// A Merkle root of a list of hashes.
7#[derive(Clone, Copy, Eq, PartialEq, packable::Packable, derive_more::From, derive_more::AsRef)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub struct MerkleRoot([u8; Self::LENGTH]);
10
11impl MerkleRoot {
12    /// Length of a merkle root.
13    pub const LENGTH: usize = 32;
14
15    /// Creates a new [`MerkleRoot`].
16    pub fn new(bytes: [u8; Self::LENGTH]) -> Self {
17        Self::from(bytes)
18    }
19
20    /// Creates a null [`MerkleRoot`].
21    pub fn null() -> Self {
22        Self::from([0u8; Self::LENGTH])
23    }
24}
25
26impl core::ops::Deref for MerkleRoot {
27    type Target = [u8; Self::LENGTH];
28
29    fn deref(&self) -> &Self::Target {
30        &self.0
31    }
32}
33
34impl core::fmt::Display for MerkleRoot {
35    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
36        write!(f, "{}", prefix_hex::encode(self.0))
37    }
38}
39
40impl core::fmt::Debug for MerkleRoot {
41    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
42        write!(f, "MerkleRoot({})", self)
43    }
44}
45
46impl core::str::FromStr for MerkleRoot {
47    type Err = Error;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        Ok(Self::from(
51            prefix_hex::decode::<[u8; Self::LENGTH]>(s).map_err(Error::HexError)?,
52        ))
53    }
54}