collections/
byte_array.rs1use core::fmt::{self, Display, Formatter};
23
24#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
26pub struct FromSliceError {
27 pub expected: usize,
29 pub actual: usize,
31}
32
33impl Display for FromSliceError {
34 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
35 write!(
36 f,
37 "the provided slice length {} doesn't match array size {}",
38 self.actual, self.expected
39 )
40 }
41}
42
43impl core::error::Error for FromSliceError {}
44
45pub trait ByteArray<const LEN: usize>: Sized {
47 fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self;
49
50 fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError>;
54
55 fn from_slice_checked(slice: impl AsRef<[u8]>) -> Self {
58 Self::from_slice(slice).expect("slice length not matching type requirements")
59 }
60
61 fn to_byte_array(&self) -> [u8; LEN];
63}
64
65impl<const LEN: usize> ByteArray<LEN> for [u8; LEN] {
66 #[inline]
67 fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self {
68 val.into()
69 }
70
71 #[inline]
72 fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError> {
73 let slice = slice.as_ref();
74 Self::try_from(slice).map_err(|_| FromSliceError {
75 expected: LEN,
76 actual: slice.len(),
77 })
78 }
79
80 #[inline]
81 fn to_byte_array(&self) -> [u8; LEN] {
82 *self
83 }
84}
85
86#[cfg(test)]
87mod test {
88 use super::*;
89
90 #[test]
91 fn raw_array_implements_byte_array() {
92 let arr = <[u8; 4]>::from_byte_array([1, 2, 3, 4]);
93 assert_eq!(arr.to_byte_array(), [1, 2, 3, 4]);
94 assert_eq!(<[u8; 4]>::from_slice([1, 2, 3, 4]), Ok(arr));
95 assert_eq!(<[u8; 4]>::from_slice_checked([1, 2, 3, 4]), arr);
96 assert_eq!(
97 <[u8; 4]>::from_slice([1, 2, 3]),
98 Err(FromSliceError {
99 expected: 4,
100 actual: 3,
101 })
102 );
103 }
104
105 #[test]
106 #[should_panic(expected = "slice length not matching type requirements")]
107 fn from_slice_checked_panics_on_mismatch() {
108 let _ = <[u8; 4]>::from_slice_checked([1, 2]);
109 }
110}