use crate::hex::{from_hex, to_hex, Hex, HexError};
use thiserror::Error;
#[derive(Debug, Error, PartialEq)]
pub enum ByteArrayError {
#[error("Could not create a ByteArray when converting from a different format: {0}")]
ConversionError(String),
#[error("The input data was the incorrect length to perform the desired conversion")]
IncorrectLength,
}
#[allow(clippy::ptr_arg)]
pub trait ByteArray: Sized {
fn to_vec(&self) -> Vec<u8> {
self.as_bytes().to_vec()
}
fn from_vec(v: &Vec<u8>) -> Result<Self, ByteArrayError> {
Self::from_bytes(v.as_slice())
}
fn from_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError>;
fn as_bytes(&self) -> &[u8];
}
impl ByteArray for Vec<u8> {
fn to_vec(&self) -> Vec<u8> {
self.clone()
}
fn from_vec(v: &Vec<u8>) -> Result<Self, ByteArrayError> {
Ok(v.clone())
}
fn from_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError> {
Ok(bytes.to_vec())
}
fn as_bytes(&self) -> &[u8] {
Vec::as_slice(self)
}
}
impl ByteArray for [u8; 32] {
fn from_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError> {
if bytes.len() != 32 {
return Err(ByteArrayError::IncorrectLength);
}
let mut a = [0u8; 32];
a.copy_from_slice(bytes);
Ok(a)
}
fn as_bytes(&self) -> &[u8] {
self
}
}
impl<T: ByteArray> Hex for T {
fn from_hex(hex: &str) -> Result<Self, HexError> {
let v = from_hex(hex)?;
Self::from_vec(&v).map_err(|_| HexError::HexConversionError)
}
fn to_hex(&self) -> String {
to_hex(&self.to_vec())
}
}