snix_castore/
digests.rs

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// TODO: allow converting these errors to crate::Error
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    // constructs a [B3Digest] from a &[u8].
58    // Returns an error if the digest has the wrong length.
59    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 Clone for B3Digest {
97    fn clone(&self) -> Self {
98        Self(self.0.to_owned())
99    }
100}
101
102impl std::fmt::Display for B3Digest {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.write_str("blake3-").unwrap();
105        BASE64.encode_write(&self.0, f)
106    }
107}
108
109impl std::fmt::Debug for B3Digest {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.write_str("blake3-").unwrap();
112        BASE64.encode_write(&self.0, f)
113    }
114}
115
116impl FromStr for B3Digest {
117    type Err = Error;
118
119    fn from_str(s: &str) -> Result<Self, Self::Err> {
120        if !s.starts_with("blake3-") {
121            return Err(Error::InvalidHashType);
122        }
123        let encoded = &s[7..];
124        let decoded = BASE64
125            .decode(encoded.as_bytes())
126            .map_err(|_| Error::InvalidDigestLen(s.len()))?;
127        decoded.as_slice().try_into()
128    }
129}