snix_castore/
digests.rs

1use bytes::Bytes;
2use data_encoding::BASE64;
3use std::str::FromStr;
4use thiserror::Error;
5
6#[derive(Clone, Copy, 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    // constructs a [B3Digest] from a &[u8].
57    // Returns an error if the digest has the wrong length.
58    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 std::fmt::Display for B3Digest {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.write_str("blake3-").unwrap();
98        BASE64.encode_write(&self.0, f)
99    }
100}
101
102impl std::fmt::Debug 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 FromStr for B3Digest {
110    type Err = Error;
111
112    fn from_str(s: &str) -> Result<Self, Self::Err> {
113        if !s.starts_with("blake3-") {
114            return Err(Error::InvalidHashType);
115        }
116        let encoded = &s[7..];
117        let decoded = BASE64
118            .decode(encoded.as_bytes())
119            .map_err(|_| Error::InvalidDigestLen(s.len()))?;
120        decoded.as_slice().try_into()
121    }
122}