use thiserror::Error;
use crate::hex::{Hex, hex_encode};
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum HashNewtypeError {
#[error("invalid hex length: expected {expected}, got {got}")]
Length {
expected: usize,
got: usize,
},
#[error("invalid hex digit at byte {index}")]
Digit {
index: usize,
},
}
crate::impl_error_kind! {
HashNewtypeError {
{ Length { .. } } => "length",
{ Digit { .. } } => "digit",
}
}
pub fn parse_hex_32_strict(s: &str) -> Result<[u8; 32], HashNewtypeError> {
if s.len() != 64 {
return Err(HashNewtypeError::Length {
expected: 64,
got: s.len(),
});
}
decode_pairs(s)
}
pub fn parse_hex_32_padded(s: &str) -> Result<[u8; 32], HashNewtypeError> {
if s.is_empty() || s.len() > 64 {
return Err(HashNewtypeError::Length {
expected: 64,
got: s.len(),
});
}
let mut padded = String::with_capacity(64);
for _ in 0..(64 - s.len()) {
padded.push('0');
}
padded.push_str(s);
decode_pairs(&padded)
}
fn decode_pairs(s: &str) -> Result<[u8; 32], HashNewtypeError> {
debug_assert_eq!(s.len(), 64);
let mut bytes = [0u8; 32];
for (i, byte) in bytes.iter_mut().enumerate() {
let pair = &s[i * 2..i * 2 + 2];
*byte = u8::from_str_radix(pair, 16).map_err(|_| HashNewtypeError::Digit { index: i })?;
}
Ok(bytes)
}
#[must_use]
pub fn hex_prefix(bytes: &[u8; 32], n: usize) -> String {
hex_encode(&bytes[..n.min(32)])
}
#[must_use]
pub fn hex_full(bytes: &[u8; 32]) -> String {
bytes.to_hex()
}
#[macro_export]
macro_rules! define_hash_newtype {
(
$(#[$attr:meta])*
$name:ident
) => {
$crate::define_hash_newtype! {
$(#[$attr])*
$name { display = full, from_hex = strict }
}
};
(
$(#[$attr:meta])*
$name:ident { $($body:tt)* }
) => {
#[derive(
::core::clone::Clone,
::core::fmt::Debug,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash,
::core::cmp::PartialOrd,
::core::cmp::Ord,
::serde::Serialize,
::serde::Deserialize,
)]
$(#[$attr])*
pub struct $name(pub [u8; 32]);
impl $name {
#[must_use]
pub fn new(bytes: [u8; 32]) -> Self {
Self(bytes)
}
#[must_use]
pub fn from_bytes(bytes: &[u8]) -> Self {
Self(*::blake3::hash(bytes).as_bytes())
}
#[must_use]
pub fn to_hex(&self) -> String {
$crate::hex::hex_encode(&self.0)
}
$crate::__hash_newtype_from_hex!($($body)*);
}
$crate::__hash_newtype_display!($name, $($body)*);
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! __hash_newtype_from_hex {
(from_hex = padded $($rest:tt)*) => {
$crate::__hash_newtype_from_hex_padded!();
};
($_other:ident = $_val:tt , from_hex = padded $($rest:tt)*) => {
$crate::__hash_newtype_from_hex_padded!();
};
($_other:ident = $_val:tt ( $($_v:tt)* ) , from_hex = padded $($rest:tt)*) => {
$crate::__hash_newtype_from_hex_padded!();
};
($($_rest:tt)*) => {
$crate::__hash_newtype_from_hex_strict!();
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! __hash_newtype_from_hex_strict {
() => {
pub fn from_hex(
s: &str,
) -> ::core::result::Result<Self, $crate::hash_newtype::HashNewtypeError> {
$crate::hash_newtype::parse_hex_32_strict(s).map(Self)
}
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! __hash_newtype_from_hex_padded {
() => {
pub fn from_hex(
s: &str,
) -> ::core::result::Result<Self, $crate::hash_newtype::HashNewtypeError> {
$crate::hash_newtype::parse_hex_32_padded(s).map(Self)
}
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! __hash_newtype_display {
($name:ident, display = prefix($n:literal) $($rest:tt)*) => {
impl ::core::fmt::Display for $name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str(&$crate::hash_newtype::hex_prefix(&self.0, $n))
}
}
};
($name:ident, $_k:ident = $_v:tt , display = prefix($n:literal) $($rest:tt)*) => {
impl ::core::fmt::Display for $name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str(&$crate::hash_newtype::hex_prefix(&self.0, $n))
}
}
};
($name:ident, $($_rest:tt)*) => {
impl ::core::fmt::Display for $name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str(&$crate::hash_newtype::hex_full(&self.0))
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
define_hash_newtype! {
SampleHash
}
define_hash_newtype! {
#[derive(Copy)]
SampleId { display = full, from_hex = strict }
}
define_hash_newtype! {
#[derive(Copy, Default)]
#[serde(transparent)]
SampleNode { display = prefix(6), from_hex = padded }
}
#[test]
fn new_and_from_bytes_distinct() {
let raw = SampleHash::new([0xab; 32]);
let hashed = SampleHash::from_bytes(b"payload");
assert_eq!(raw.0, [0xab; 32]);
assert_ne!(raw, hashed);
assert_eq!(hashed.0, *blake3::hash(b"payload").as_bytes());
}
#[test]
fn to_hex_is_64_lowercase() {
let h = SampleHash::new([0xab; 32]);
let hex = h.to_hex();
assert_eq!(hex.len(), 64);
assert!(
hex.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
);
assert_eq!(hex, "ab".repeat(32));
}
#[test]
fn display_full_matches_to_hex() {
let h = SampleHash::new([0xcd; 32]);
assert_eq!(h.to_string(), h.to_hex());
assert_eq!(h.to_string(), "cd".repeat(32));
}
#[test]
fn from_hex_strict_round_trips() {
let h = SampleHash::new([0x12; 32]);
let hex = h.to_hex();
let back = SampleHash::from_hex(&hex).unwrap();
assert_eq!(h, back);
}
#[test]
fn from_hex_strict_rejects_short_and_nonhex() {
assert!(matches!(
SampleHash::from_hex("ab"),
Err(HashNewtypeError::Length {
expected: 64,
got: 2
})
));
let bad = "zz".to_string() + &"00".repeat(31);
assert!(matches!(
SampleHash::from_hex(&bad),
Err(HashNewtypeError::Digit { index: 0 })
));
}
#[test]
fn copy_id_is_copy_and_carries_full_surface() {
let a = SampleId::new([1u8; 32]);
let b = a; assert_eq!(a, b);
let hashed = SampleId::from_bytes(b"id");
assert_eq!(hashed.0, *blake3::hash(b"id").as_bytes());
let hex = a.to_hex();
assert_eq!(hex, "01".repeat(32));
assert_eq!(SampleId::from_hex(&hex).unwrap(), a);
}
#[test]
fn transparent_node_serde_is_bare_array_and_display_is_prefix() {
let n = SampleNode::new([0xab; 32]);
let json = serde_json::to_string(&n).unwrap();
let back: SampleNode = serde_json::from_str(&json).unwrap();
assert_eq!(n, back);
assert_eq!(n.to_string(), "abababababab");
assert_eq!(SampleNode::default(), SampleNode::new([0u8; 32]));
let hashed = SampleNode::from_bytes(b"node");
assert_eq!(hashed.0, *blake3::hash(b"node").as_bytes());
}
#[test]
fn padded_from_hex_round_trips_shorthand() {
let n = SampleNode::from_hex("ab").unwrap();
let mut expected = [0u8; 32];
expected[31] = 0xab;
assert_eq!(n, SampleNode::new(expected));
assert_eq!(n.to_hex().len(), 64);
}
#[test]
fn padded_from_hex_rejects_empty_and_overlong() {
assert!(matches!(
SampleNode::from_hex(""),
Err(HashNewtypeError::Length { .. })
));
let over = "a".repeat(65);
assert!(matches!(
SampleNode::from_hex(&over),
Err(HashNewtypeError::Length {
expected: 64,
got: 65
})
));
}
#[test]
fn hash_newtype_error_kind_tags() {
assert_eq!(
(HashNewtypeError::Length {
expected: 64,
got: 2
})
.kind(),
"length"
);
assert_eq!((HashNewtypeError::Digit { index: 0 }).kind(), "digit");
}
}