use alloc::string::String;
use faster_hex::CheckCase;
#[derive(Debug)]
pub(crate) enum Error {
Length,
Character,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Length => f.write_str("invalid hex length"),
Self::Character => f.write_str("invalid hex character"),
}
}
}
impl core::error::Error for Error {}
pub(crate) fn decode_caller<const N: usize>(input: &str) -> Result<[u8; N], Error> {
decode::<N>(input, CheckCase::None)
}
pub(crate) fn decode_wire<const N: usize>(input: &str) -> Result<[u8; N], Error> {
decode::<N>(input, CheckCase::Lower)
}
fn decode<const N: usize>(input: &str, case: CheckCase) -> Result<[u8; N], Error> {
faster_hex::hex_decode_array_with_case::<N>(input.as_bytes(), case).map_err(|error| match error
{
faster_hex::Error::InvalidChar { .. } => Error::Character,
_ => Error::Length,
})
}
pub(crate) fn encode(bytes: &[u8]) -> String {
faster_hex::hex_string(bytes)
}
pub(crate) fn encode_slice<'a>(bytes: &[u8], buf: &'a mut [u8]) -> &'a str {
match faster_hex::hex_encode(bytes, buf) {
Ok(encoded) => encoded,
Err(_) => "",
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, reason = "tests fail by panicking")]
use super::*;
#[test]
fn decode_caller_accepts_mixed_case() {
assert_eq!(
decode_caller::<4>("00ffAAbb").unwrap(),
[0x00, 0xff, 0xaa, 0xbb]
);
}
#[test]
fn decode_wire_rejects_uppercase() {
assert!(decode_wire::<4>("00FF").is_err());
}
#[test]
fn decode_rejects_odd_length() {
assert!(decode_caller::<4>("012").is_err());
}
#[test]
fn decode_rejects_wrong_length() {
assert!(decode_wire::<4>("00ffaa").is_err());
}
#[test]
fn encode_is_lowercase() {
assert_eq!(encode(&[0xde, 0xad]), "dead");
}
}