1use bytes::Bytes;
2use data_encoding::BASE64;
3use std::str::FromStr;
4use thiserror::Error;
5
6#[derive(PartialEq, Eq, Hash)]
7#[repr(transparent)]
8pub struct B3Digest([u8; Self::LENGTH]);
9
10impl B3Digest {
11 pub const LENGTH: usize = blake3::OUT_LEN;
12}
13
14#[derive(Error, Debug, PartialEq)]
15pub enum Error {
16 #[error("invalid digest length: {0}")]
17 InvalidDigestLen(usize),
18 #[error("invalid hash type: expected a 'blake3-' prefixed digest")]
19 InvalidHashType,
20}
21
22impl AsRef<[u8; B3Digest::LENGTH]> for B3Digest {
23 fn as_ref(&self) -> &[u8; Self::LENGTH] {
24 &self.0
25 }
26}
27
28impl std::ops::Deref for B3Digest {
29 type Target = [u8; Self::LENGTH];
30
31 fn deref(&self) -> &Self::Target {
32 &self.0
33 }
34}
35
36impl From<B3Digest> for bytes::Bytes {
37 fn from(val: B3Digest) -> Self {
38 Bytes::copy_from_slice(&val.0)
39 }
40}
41
42impl From<blake3::Hash> for B3Digest {
43 fn from(value: blake3::Hash) -> Self {
44 Self(*value.as_bytes())
45 }
46}
47impl From<digest::Output<blake3::Hasher>> for B3Digest {
48 fn from(value: digest::Output<blake3::Hasher>) -> Self {
49 Self(value.into())
50 }
51}
52
53impl TryFrom<&[u8]> for B3Digest {
54 type Error = Error;
55
56 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
59 Ok(Self(
60 value
61 .try_into()
62 .map_err(|_e| Error::InvalidDigestLen(value.len()))?,
63 ))
64 }
65}
66
67impl TryFrom<bytes::Bytes> for B3Digest {
68 type Error = Error;
69
70 fn try_from(value: bytes::Bytes) -> Result<Self, Self::Error> {
71 value[..].try_into()
72 }
73}
74
75impl TryFrom<Vec<u8>> for B3Digest {
76 type Error = Error;
77
78 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
79 value[..].try_into()
80 }
81}
82
83impl From<&[u8; B3Digest::LENGTH]> for B3Digest {
84 fn from(value: &[u8; B3Digest::LENGTH]) -> Self {
85 Self(*value)
86 }
87}
88
89impl From<B3Digest> for [u8; B3Digest::LENGTH] {
90 fn from(value: B3Digest) -> Self {
91 value.0
92 }
93}
94
95impl Clone for B3Digest {
96 fn clone(&self) -> Self {
97 Self(self.0.to_owned())
98 }
99}
100
101impl std::fmt::Display for B3Digest {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.write_str("blake3-").unwrap();
104 BASE64.encode_write(&self.0, f)
105 }
106}
107
108impl std::fmt::Debug for B3Digest {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.write_str("blake3-").unwrap();
111 BASE64.encode_write(&self.0, f)
112 }
113}
114
115impl FromStr for B3Digest {
116 type Err = Error;
117
118 fn from_str(s: &str) -> Result<Self, Self::Err> {
119 if !s.starts_with("blake3-") {
120 return Err(Error::InvalidHashType);
121 }
122 let encoded = &s[7..];
123 let decoded = BASE64
124 .decode(encoded.as_bytes())
125 .map_err(|_| Error::InvalidDigestLen(s.len()))?;
126 decoded.as_slice().try_into()
127 }
128}