use crate::error::{Error, Result};
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
pub fn encode_hex(bytes: &[u8]) -> String {
hex::encode(bytes)
}
pub fn decode_hex(hex_str: &str) -> Result<Vec<u8>> {
let hex_str = hex_str.strip_prefix("0x").unwrap_or(hex_str);
hex::decode(hex_str).map_err(|e| Error::ParseError(e.to_string()))
}
pub fn bytes_to_u128(bytes: &[u8]) -> Result<u128> {
if bytes.len() != 16 {
return Err(Error::InvalidLength {
expected: 16,
actual: bytes.len(),
});
}
let mut array = [0u8; 16];
array.copy_from_slice(bytes);
Ok(u128::from_be_bytes(array))
}
pub fn u128_to_bytes(value: u128) -> [u8; 16] {
value.to_be_bytes()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode_hex() {
assert_eq!(encode_hex(&[]), "");
assert_eq!(encode_hex(&[0x00]), "00");
assert_eq!(encode_hex(&[0xff]), "ff");
assert_eq!(encode_hex(&[0xde, 0xad, 0xbe, 0xef]), "deadbeef");
}
#[test]
fn test_decode_hex() {
assert_eq!(decode_hex("").unwrap(), vec![]);
assert_eq!(decode_hex("00").unwrap(), vec![0x00]);
assert_eq!(decode_hex("ff").unwrap(), vec![0xff]);
assert_eq!(decode_hex("deadbeef").unwrap(), vec![0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_decode_hex_with_prefix() {
assert_eq!(decode_hex("0x").unwrap(), vec![]);
assert_eq!(decode_hex("0xdeadbeef").unwrap(), vec![0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_decode_hex_invalid() {
assert!(decode_hex("gg").is_err());
assert!(decode_hex("0").is_err()); }
#[test]
fn test_bytes_to_u128() {
let bytes = [0u8; 16];
assert_eq!(bytes_to_u128(&bytes).unwrap(), 0);
let bytes = [0xff; 16];
assert_eq!(bytes_to_u128(&bytes).unwrap(), u128::MAX);
}
#[test]
fn test_bytes_to_u128_wrong_length() {
assert!(bytes_to_u128(&[0u8; 15]).is_err());
assert!(bytes_to_u128(&[0u8; 17]).is_err());
}
#[test]
fn test_u128_to_bytes_roundtrip() {
for value in [0u128, 1, u128::MAX, 12345678901234567890] {
let bytes = u128_to_bytes(value);
let recovered = bytes_to_u128(&bytes).unwrap();
assert_eq!(value, recovered);
}
}
}