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