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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use alloc::vec::Vec;
use crate::canon::{Canon, CanonError, EncodeToVec};
use crate::store::{Sink, Source, Store};
const VERSION: u8 = 0;
pub const HASH_BYTES: usize = 32;
pub type IdHash = [u8; 32];
#[derive(Hash, PartialEq, Eq, Default, Clone, Copy, PartialOrd, Ord)]
pub struct Id {
version: u8,
len: u32,
hash: IdHash,
}
impl core::fmt::Debug for Id {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Id(")?;
for byte in self.hash {
write!(f, "{:02x}", byte)?;
}
write!(f, ", {})", self.len)
}
}
impl Id {
pub fn new<T>(t: &T) -> Self
where
T: Canon,
{
let bytes = t.encode_to_vec();
let len = bytes.len();
let hash = Store::put(&bytes);
Id {
version: VERSION,
len: (len as u32),
hash,
}
}
pub fn raw(hash: [u8; 32], len: u32) -> Self {
Id {
version: VERSION,
len: (len as u32),
hash,
}
}
pub fn hash(&self) -> IdHash {
self.hash
}
pub const fn size(&self) -> usize {
self.len as usize
}
pub fn reify<T>(&self) -> Result<T, CanonError>
where
T: Canon,
{
let len = self.size();
let mut buf = Vec::new();
buf.resize_with(len, || 0);
Store::get(&self.hash(), &mut buf)?;
let mut source = Source::new(&buf);
T::decode(&mut source)
}
pub fn take_bytes(&self) -> Result<Option<Vec<u8>>, CanonError> {
Ok(Some(Store::take_bytes(self)?))
}
}
impl Canon for Id {
fn encode(&self, sink: &mut Sink) {
self.version.encode(sink);
self.len.encode(sink);
sink.copy_bytes(&self.hash());
}
fn decode(source: &mut Source) -> Result<Self, CanonError> {
let version = u8::decode(source)?;
if version != 0 {
return Err(CanonError::InvalidEncoding);
}
let len = u32::decode(source)?;
let mut hash = [0u8; HASH_BYTES];
hash[..].copy_from_slice(source.read_bytes(HASH_BYTES));
Ok(Id { version, len, hash })
}
fn encoded_len(&self) -> usize {
1 + self.len.encoded_len() + HASH_BYTES
}
}
#[cfg(not(target_arch = "wasm32"))]
mod impl_arbitrary {
use super::*;
use arbitrary::{Arbitrary, Result, Unstructured};
impl<'a> Arbitrary<'a> for Id {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
let mut bytevec = Vec::arbitrary(u)?;
if bool::arbitrary(u)? {
let junk = Store::hash(&bytevec[..]);
bytevec.extend_from_slice(&junk);
}
Ok(Id::new(&bytevec))
}
}
}