use thiserror::Error;
const MAX_EMBEDDED_INPUT_CHARS: usize = 72;
#[non_exhaustive]
#[derive(Error, Debug, Clone)]
pub enum DataHashError {
#[error("Invalid hex input for DataHash (got '{input}')")]
InvalidHex {
input: String,
},
#[error("Invalid bytes input for DataHash (got '{input}')")]
InvalidBytes {
input: String,
},
}
impl DataHashError {
pub fn input(&self) -> &str {
match self {
Self::InvalidHex { input } => input,
Self::InvalidBytes { input } => input,
}
}
pub(crate) fn invalid_hex(input: &str) -> Self {
Self::InvalidHex {
input: Self::truncate_for_display(input),
}
}
pub(crate) fn invalid_bytes_str(input: &str) -> Self {
Self::InvalidBytes {
input: Self::truncate_for_display(input),
}
}
pub(crate) fn invalid_bytes_slice(bytes: &[u8]) -> Self {
Self::InvalidBytes {
input: Self::truncate_for_display(&Self::format_bytes(bytes)),
}
}
fn truncate_for_display(input: &str) -> String {
if input.len() <= MAX_EMBEDDED_INPUT_CHARS {
return input.to_owned();
}
let end = input.floor_char_boundary(MAX_EMBEDDED_INPUT_CHARS);
let mut truncated = input[..end].to_owned();
truncated.push_str("...");
truncated
}
fn format_bytes(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
}