use std::convert::TryInto;
use std::mem::size_of;
pub trait FixedInt: Sized + Copy {
type Bytes: AsRef<[u8]>;
const ENCODED_SIZE: usize = size_of::<Self>();
fn encode_fixed(self, dst: &mut [u8]) -> Option<()>;
fn encode_fixed_light(self) -> Self::Bytes;
fn decode_fixed(src: &[u8]) -> Option<Self>;
fn encode_fixed_vec(self) -> Vec<u8> {
self.encode_fixed_light().as_ref().to_vec()
}
fn switch_endianness(self) -> Self;
}
macro_rules! impl_fixedint {
($t:ty) => {
impl FixedInt for $t {
type Bytes = [u8; size_of::<$t>()];
fn encode_fixed(self, dst: &mut [u8]) -> Option<()> {
if dst.len() == size_of::<Self>() {
dst.clone_from_slice(&self.to_le_bytes());
Some(())
} else {
None
}
}
fn encode_fixed_light(self) -> Self::Bytes {
self.to_le_bytes()
}
fn decode_fixed(src: &[u8]) -> Option<Self> {
if src.len() == size_of::<Self>() {
Some(Self::from_le_bytes(src.try_into().unwrap()))
} else {
None
}
}
fn switch_endianness(self) -> Self {
Self::from_le_bytes(self.to_be_bytes())
}
}
};
}
impl_fixedint!(usize);
impl_fixedint!(u64);
impl_fixedint!(u32);
impl_fixedint!(u16);
impl_fixedint!(u8);
impl_fixedint!(isize);
impl_fixedint!(i64);
impl_fixedint!(i32);
impl_fixedint!(i16);
impl_fixedint!(i8);