1use crate::{Error, Result};
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6
7pub(crate) fn decode_hex<const N: usize>(what: &'static str, s: &str) -> Result<[u8; N]> {
8 let raw = hex::decode(s).map_err(|_| Error::InvalidKey(format!("{what} is not hex")))?;
9 raw.try_into().map_err(|_| Error::InvalidKey(format!("{what} must be {N} bytes")))
10}
11
12#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub struct Hash32(pub [u8; 32]);
15
16impl Hash32 {
17 pub fn of(data: &[u8]) -> Self {
19 Self(*blake3::hash(data).as_bytes())
20 }
21
22 pub fn to_hex(&self) -> String {
24 hex::encode(self.0)
25 }
26
27 pub fn from_hex(s: &str) -> Result<Self> {
29 Ok(Self(decode_hex("hash", s)?))
30 }
31}
32
33impl From<blake3::Hash> for Hash32 {
34 fn from(h: blake3::Hash) -> Self {
35 Self(*h.as_bytes())
36 }
37}
38
39impl fmt::Display for Hash32 {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.write_str(&self.to_hex())
42 }
43}
44
45impl fmt::Debug for Hash32 {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 write!(f, "Hash32({})", self.to_hex())
48 }
49}
50
51impl Serialize for Hash32 {
52 fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
53 s.serialize_str(&self.to_hex())
54 }
55}
56
57impl<'de> Deserialize<'de> for Hash32 {
58 fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
59 let s = String::deserialize(d)?;
60 Self::from_hex(&s).map_err(serde::de::Error::custom)
61 }
62}