byteserde/utils/numerics/
be_bytes.rs1pub trait ToBeBytes<const N: usize> {
2 fn to_bytes(&self) -> [u8; N];
3}
4
5macro_rules! impl_ToBeBytes {
14 ($name:ty, $len:expr) => {
15 impl $crate::utils::numerics::be_bytes::ToBeBytes<$len> for $name {
16 #[inline]
17 fn to_bytes(&self) -> [u8; $len] {
18 self.to_be_bytes()
19 }
20 }
21 };
22}
23const USIZE: usize = std::mem::size_of::<usize>();
24impl_ToBeBytes!(u16, 2);
25impl_ToBeBytes!(i16, 2);
26impl_ToBeBytes!(u32, 4);
27impl_ToBeBytes!(i32, 4);
28impl_ToBeBytes!(u64, 8);
29impl_ToBeBytes!(i64, 8);
30impl_ToBeBytes!(u128, 16);
31impl_ToBeBytes!(i128, 16);
32impl_ToBeBytes!(f32, 4);
33impl_ToBeBytes!(f64, 8);
34impl_ToBeBytes!(usize, USIZE);
35impl_ToBeBytes!(isize, USIZE);
36pub trait FromBeBytes<const N: usize, T> {
39 fn from_bytes(v: [u8; N]) -> T;
40 fn from_bytes_ref(v: &[u8; N]) -> T;
41}
42
43macro_rules! impl_FromBeBytes {
52 ($name:ty, $len:expr) => {
53 impl $crate::utils::numerics::be_bytes::FromBeBytes<$len, $name> for $name {
54 #[inline]
55 fn from_bytes(v: [u8; $len]) -> $name {
56 <$name>::from_be_bytes(v)
57 }
58 #[inline]
59 fn from_bytes_ref(v: &[u8; $len]) -> $name {
60 <$name>::from_be_bytes(*v)
61 }
62 }
63 };
64}
65
66impl_FromBeBytes!(u16, 2);
67impl_FromBeBytes!(i16, 2);
68impl_FromBeBytes!(u32, 4);
69impl_FromBeBytes!(i32, 4);
70impl_FromBeBytes!(u64, 8);
71impl_FromBeBytes!(i64, 8);
72impl_FromBeBytes!(u128, 16);
73impl_FromBeBytes!(i128, 16);
74impl_FromBeBytes!(f32, 4);
75impl_FromBeBytes!(f64, 8);
76impl_FromBeBytes!(usize, USIZE);
77impl_FromBeBytes!(isize, USIZE);
78#[cfg(test)]
80mod tests {
81 use super::*;
82 use crate::unittest::setup;
83 use log::info;
84
85 #[test]
86 fn test_u16() {
87 setup::log::configure();
88 let inp = 0xAA00_u16;
89 let byt = inp.to_bytes();
90 let out = u16::from_bytes(byt);
91 info! {"inp: {inp}"}
92 info!("inp: {inp}, inp:x {inp:#06x}, inp:b {inp:016b}");
93 info!("out: {out}, out:x {out:#06x}, inp:b {out:016b}");
94 info!("byt:x 0x{byt0:02x}{byt1:02x}, out:b {byt0:08b}{byt1:08b}", byt0 = byt[0], byt1 = byt[1]);
95 assert_eq!(byt, [0xAA_u8, 0x00_u8]);
96 assert_eq!(inp, out);
97 }
98}