pub use paste::paste;
#[macro_export]
macro_rules! bytes_to_type {
($type:ty) => {
$crate::paste! {
pub fn [<bytes_to_$type>](bytes: &[u8]) -> anyhow::Result<Vec<$type>> {
if bytes.len() % std::mem::size_of::<$type>() != 0 {
return Err(anyhow::anyhow!(
"Bytes length is not a multiple of {}",
std::mem::size_of::<$type>()
));
}
Ok(unsafe {
std::slice::from_raw_parts(
bytes.as_ptr() as *const $type,
bytes.len() / std::mem::size_of::<$type>(),
)
}
.to_vec())
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
bytes_to_type!(u32);
let bytes = vec![1, 2, 3, 4];
let result = bytes_to_u32(bytes.as_slice()).unwrap();
assert_eq!(result, vec![67305985]);
}
#[test]
fn it_returns_error_if_bytes_length_is_not_a_multiple_of_type_size() {
bytes_to_type!(u32);
let bytes = vec![1, 2, 3];
let result = bytes_to_u32(bytes.as_slice());
assert!(result.is_err());
}
}