alloy_primitives/
sealed.rs

1use crate::B256;
2
3/// A consensus hashable item, with its memoized hash.
4///
5/// We do not implement any specific hashing algorithm here. Instead types
6/// implement the [`Sealable`] trait to provide define their own hash.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub struct Sealed<T> {
10    /// The inner item
11    inner: T,
12    /// Its hash.
13    seal: B256,
14}
15
16impl<T> core::ops::Deref for Sealed<T> {
17    type Target = T;
18
19    fn deref(&self) -> &Self::Target {
20        self.inner()
21    }
22}
23
24impl<T> Sealed<T> {
25    /// Instantiate without performing the hash. This should be used carefully.
26    pub const fn new_unchecked(inner: T, seal: B256) -> Self {
27        Self { inner, seal }
28    }
29
30    /// Decompose into parts.
31    #[allow(clippy::missing_const_for_fn)] // false positive
32    pub fn into_parts(self) -> (T, B256) {
33        (self.inner, self.seal)
34    }
35
36    /// Decompose into parts. Alias for [`Self::into_parts`].
37    #[allow(clippy::missing_const_for_fn)] // false positive
38    pub fn split(self) -> (T, B256) {
39        self.into_parts()
40    }
41
42    /// Get the inner item.
43    #[inline(always)]
44    pub const fn inner(&self) -> &T {
45        &self.inner
46    }
47
48    /// Get the hash.
49    #[inline(always)]
50    pub const fn seal(&self) -> B256 {
51        self.seal
52    }
53
54    /// Unseal the inner item, discarding the hash.
55    #[inline(always)]
56    #[allow(clippy::missing_const_for_fn)] // false positive
57    pub fn into_inner(self) -> T {
58        self.inner
59    }
60
61    /// Unseal the inner item, discarding the hash. Alias for
62    /// [`Self::into_inner`].
63    #[inline(always)]
64    #[allow(clippy::missing_const_for_fn)] // false positive
65    pub fn unseal(self) -> T {
66        self.into_inner()
67    }
68}
69
70/// Sealeable objects.
71pub trait Sealable: Sized {
72    /// Calculate the seal hash, this may be slow.
73    fn hash_slow(&self) -> B256;
74
75    /// Seal the object by calculating the hash. This may be slow.
76    fn seal_slow(self) -> Sealed<Self> {
77        let seal = self.hash_slow();
78        Sealed::new_unchecked(self, seal)
79    }
80
81    /// Instantiate an unchecked seal. This should be used with caution.
82    fn seal_unchecked(self, seal: B256) -> Sealed<Self> {
83        Sealed::new_unchecked(self, seal)
84    }
85}