1use std::fmt;
4use std::io;
5use std::str::FromStr;
6
7use crate::cbor::{self, FromCbor, ToCbor, Value};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct ChangeId(Hash);
12
13impl ChangeId {
14 #[must_use]
16 pub const fn hash(&self) -> &Hash {
17 &self.0
18 }
19
20 #[must_use]
22 pub const fn from_hash(hash: Hash) -> Self {
23 Self(hash)
24 }
25}
26
27impl fmt::Display for ChangeId {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 self.0.fmt(f)
30 }
31}
32
33impl FromStr for ChangeId {
34 type Err = <Hash as std::str::FromStr>::Err;
35
36 fn from_str(text: &str) -> Result<Self, Self::Err> {
37 text.parse().map(Self)
38 }
39}
40
41impl ToCbor for ChangeId {
42 fn to_cbor(&self) -> Value {
43 self.0.to_cbor()
44 }
45}
46
47impl FromCbor for ChangeId {
48 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
49 Hash::from_cbor(value).map(Self)
50 }
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
55#[non_exhaustive]
56pub enum HashAlgorithm {
57 Blake3,
59}
60
61impl HashAlgorithm {
62 #[must_use]
64 pub const fn name(self) -> &'static str {
65 match self {
66 Self::Blake3 => "blake3",
67 }
68 }
69
70 const fn multihash_code(self) -> u64 {
72 match self {
73 Self::Blake3 => 0x1e,
74 }
75 }
76
77 const fn digest_len(self) -> usize {
79 match self {
80 Self::Blake3 => 32,
81 }
82 }
83
84 fn from_name(name: &str) -> Option<Self> {
85 (name == Self::Blake3.name()).then_some(Self::Blake3)
86 }
87
88 fn from_multihash_code(code: u64) -> Option<Self> {
89 (code == Self::Blake3.multihash_code()).then_some(Self::Blake3)
90 }
91}
92
93const MAX_DIGEST_LEN: usize = 64;
95
96#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
101pub struct Hash {
102 algorithm: HashAlgorithm,
103 digest: [u8; MAX_DIGEST_LEN],
106}
107
108impl Hash {
109 #[must_use]
111 pub fn of(data: &[u8]) -> Self {
112 Self::from_blake3(&blake3::hash(data))
113 }
114
115 #[must_use]
117 pub fn algorithm(&self) -> HashAlgorithm {
118 self.algorithm
119 }
120
121 #[must_use]
123 pub fn digest(&self) -> &[u8] {
124 &self.digest[..self.algorithm.digest_len()]
125 }
126
127 #[must_use]
130 pub fn to_multihash(&self) -> Vec<u8> {
131 let digest = self.digest();
132 let mut out = Vec::with_capacity(2 + digest.len());
133 write_varint(&mut out, self.algorithm.multihash_code());
134 write_varint(&mut out, digest.len() as u64);
135 out.extend_from_slice(digest);
136 out
137 }
138
139 pub fn from_multihash(bytes: &[u8]) -> Result<Self, ParseHashError> {
146 let mut rest = bytes;
147 let code = read_varint(&mut rest)?;
148 let len = read_varint(&mut rest)?;
149 let algorithm =
150 HashAlgorithm::from_multihash_code(code).ok_or(ParseHashError::UnknownAlgorithm)?;
151 if usize::try_from(len).ok() != Some(algorithm.digest_len()) {
152 return Err(ParseHashError::WrongLength);
153 }
154 if rest.len() != algorithm.digest_len() {
155 return Err(ParseHashError::Malformed);
156 }
157 Ok(Self::new(algorithm, rest))
158 }
159
160 fn from_blake3(hash: &blake3::Hash) -> Self {
161 Self::new(HashAlgorithm::Blake3, hash.as_bytes())
162 }
163
164 fn new(algorithm: HashAlgorithm, digest: &[u8]) -> Self {
166 debug_assert_eq!(digest.len(), algorithm.digest_len());
167 let mut padded = [0; MAX_DIGEST_LEN];
168 padded[..digest.len()].copy_from_slice(digest);
169 Self {
170 algorithm,
171 digest: padded,
172 }
173 }
174}
175
176impl fmt::Display for Hash {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 write!(f, "{}:", self.algorithm.name())?;
179 self.digest()
180 .iter()
181 .try_for_each(|byte| write!(f, "{byte:02x}"))
182 }
183}
184
185impl fmt::Debug for Hash {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(f, "Hash({self})")
188 }
189}
190
191impl FromStr for Hash {
192 type Err = ParseHashError;
193
194 fn from_str(text: &str) -> Result<Self, Self::Err> {
197 let (name, hex) = text.split_once(':').ok_or(ParseHashError::Malformed)?;
198 let algorithm = HashAlgorithm::from_name(name).ok_or(ParseHashError::UnknownAlgorithm)?;
199 if hex.len() != 2 * algorithm.digest_len() {
200 return Err(ParseHashError::WrongLength);
201 }
202 let mut digest = [0; MAX_DIGEST_LEN];
203 for (byte, pair) in digest.iter_mut().zip(hex.as_bytes().chunks(2)) {
204 *byte = (hex_digit(pair[0])? << 4) | hex_digit(pair[1])?;
205 }
206 Ok(Self { algorithm, digest })
207 }
208}
209
210impl ToCbor for Hash {
211 fn to_cbor(&self) -> Value {
212 Value::Bytes(self.to_multihash())
213 }
214}
215
216impl FromCbor for Hash {
217 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
218 match value {
219 Value::Bytes(bytes) => {
220 Self::from_multihash(bytes).map_err(|_| cbor::Error::Expected("a multihash"))
221 }
222 _ => Err(cbor::Error::Expected("a multihash")),
223 }
224 }
225}
226
227#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
229#[non_exhaustive]
230pub enum ParseHashError {
231 #[error("unknown hash algorithm")]
233 UnknownAlgorithm,
234 #[error("digest has the wrong length for its algorithm")]
236 WrongLength,
237 #[error("not a hash in the expected form")]
239 Malformed,
240}
241
242#[derive(Clone, Debug, Default)]
244pub struct Hasher(blake3::Hasher);
245
246impl Hasher {
247 #[must_use]
249 pub fn new() -> Self {
250 Self::default()
251 }
252
253 pub fn update(&mut self, data: &[u8]) -> &mut Self {
255 self.0.update(data);
256 self
257 }
258
259 #[must_use]
261 pub fn finalize(&self) -> Hash {
262 Hash::from_blake3(&self.0.finalize())
263 }
264}
265
266impl io::Write for Hasher {
267 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
268 self.update(data);
269 Ok(data.len())
270 }
271
272 fn flush(&mut self) -> io::Result<()> {
273 Ok(())
274 }
275}
276
277fn hex_digit(digit: u8) -> Result<u8, ParseHashError> {
278 match digit {
279 b'0'..=b'9' => Ok(digit - b'0'),
280 b'a'..=b'f' => Ok(digit - b'a' + 10),
281 _ => Err(ParseHashError::Malformed),
282 }
283}
284
285fn write_varint(out: &mut Vec<u8>, mut value: u64) {
288 loop {
289 let low = u8::try_from(value & 0x7f).expect("seven bits");
290 value >>= 7;
291 if value == 0 {
292 out.push(low);
293 return;
294 }
295 out.push(low | 0x80);
296 }
297}
298
299fn read_varint(bytes: &mut &[u8]) -> Result<u64, ParseHashError> {
302 let mut value = 0u64;
303 for (index, &byte) in bytes.iter().enumerate().take(9) {
304 value |= u64::from(byte & 0x7f) << (7 * index);
305 if byte & 0x80 == 0 {
306 if byte == 0 && index > 0 {
307 return Err(ParseHashError::Malformed);
308 }
309 *bytes = &bytes[index + 1..];
310 return Ok(value);
311 }
312 }
313 Err(ParseHashError::Malformed)
314}