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