use core::fmt::{self, Display, Formatter};
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct FromSliceError {
pub expected: usize,
pub actual: usize,
}
impl Display for FromSliceError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"the provided slice length {} doesn't match array size {}",
self.actual, self.expected
)
}
}
impl core::error::Error for FromSliceError {}
pub trait ByteArray<const LEN: usize>: Sized {
fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self;
fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError>;
fn from_slice_checked(slice: impl AsRef<[u8]>) -> Self {
Self::from_slice(slice).expect("slice length not matching type requirements")
}
fn to_byte_array(&self) -> [u8; LEN];
}
impl<const LEN: usize> ByteArray<LEN> for [u8; LEN] {
#[inline]
fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self {
val.into()
}
#[inline]
fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError> {
let slice = slice.as_ref();
Self::try_from(slice).map_err(|_| FromSliceError {
expected: LEN,
actual: slice.len(),
})
}
#[inline]
fn to_byte_array(&self) -> [u8; LEN] {
*self
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn raw_array_implements_byte_array() {
let arr = <[u8; 4]>::from_byte_array([1, 2, 3, 4]);
assert_eq!(arr.to_byte_array(), [1, 2, 3, 4]);
assert_eq!(<[u8; 4]>::from_slice([1, 2, 3, 4]), Ok(arr));
assert_eq!(<[u8; 4]>::from_slice_checked([1, 2, 3, 4]), arr);
assert_eq!(
<[u8; 4]>::from_slice([1, 2, 3]),
Err(FromSliceError {
expected: 4,
actual: 3,
})
);
}
#[test]
#[should_panic(expected = "slice length not matching type requirements")]
fn from_slice_checked_panics_on_mismatch() {
let _ = <[u8; 4]>::from_slice_checked([1, 2]);
}
}