1use crate::hex::HexString;
2use crate::{impl_deserialize, impl_serialize, impl_st, u256, AlgebraicType};
3use core::fmt;
4use sha3::{Digest, Keccak256};
5
6pub const HASH_SIZE: usize = 32;
7
8#[derive(Eq, PartialEq, PartialOrd, Ord, Clone, Copy, Hash)]
9#[cfg_attr(any(test, feature = "proptest"), derive(proptest_derive::Arbitrary))]
10pub struct Hash {
11 pub data: [u8; HASH_SIZE],
12}
13
14impl_st!([] Hash, AlgebraicType::U256);
15impl_serialize!([] Hash, (self, ser) => u256::from_le_bytes(self.data).serialize(ser));
16impl_deserialize!([] Hash, de => Ok(Self { data: <_>::deserialize(de).map(u256::to_le_bytes)? }));
17
18#[cfg(feature = "metrics_impls")]
19impl spacetimedb_metrics::typed_prometheus::AsPrometheusLabel for Hash {
20 fn as_prometheus_str(&self) -> impl AsRef<str> + '_ {
21 self.to_hex()
22 }
23}
24
25impl Hash {
26 pub const ZERO: Self = Self::from_byte_array([0; HASH_SIZE]);
27
28 pub const fn from_byte_array(data: [u8; HASH_SIZE]) -> Self {
29 Self { data }
30 }
31
32 pub fn from_u256(val: u256) -> Self {
33 Self::from_byte_array(val.to_le_bytes())
34 }
35
36 pub fn to_u256(self) -> u256 {
37 u256::from_le_bytes(self.data)
38 }
39
40 pub fn to_hex(&self) -> HexString<32> {
41 crate::hex::encode(&self.data)
42 }
43
44 pub fn abbreviate(&self) -> &[u8; 16] {
45 self.data[..16].try_into().unwrap()
46 }
47
48 pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Self, hex::FromHexError> {
49 hex::FromHex::from_hex(hex)
50 }
51}
52
53pub fn hash_bytes(bytes: impl AsRef<[u8]>) -> Hash {
54 Hash::from_byte_array(Keccak256::digest(bytes).into())
55}
56
57impl fmt::Display for Hash {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.pad(&self.to_hex())
60 }
61}
62
63impl fmt::Debug for Hash {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.debug_tuple("Hash").field(&format_args!("{self}")).finish()
66 }
67}
68
69impl hex::FromHex for Hash {
70 type Error = hex::FromHexError;
71
72 fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
73 let data = hex::FromHex::from_hex(hex)?;
74 Ok(Hash { data })
75 }
76}
77
78#[cfg(feature = "serde")]
79impl serde::Serialize for Hash {
80 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
81 crate::ser::serde::serialize_to(self, serializer)
82 }
83}
84#[cfg(feature = "serde")]
85impl<'de> serde::Deserialize<'de> for Hash {
86 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
87 crate::de::serde::deserialize_from(deserializer)
88 }
89}