fixed_byterepr/
lib.rs

1#![doc = include_str!("../README.md")]
2#![feature(generic_const_exprs)]
3#![allow(incomplete_features)]
4#![no_std]
5
6pub trait FromBytes {
7    const N: usize;
8
9    fn from_be_bytes(bytes: [u8; Self::N]) -> Self;
10    fn from_le_bytes(bytes: [u8; Self::N]) -> Self;
11    fn from_ne_bytes(bytes: [u8; Self::N]) -> Self;
12}
13
14pub trait ToBytes {
15    const N: usize;
16
17    fn to_be_bytes(self) -> [u8; Self::N];
18    fn to_le_bytes(self) -> [u8; Self::N];
19    fn to_ne_bytes(self) -> [u8; Self::N];
20}
21
22#[macro_export]
23macro_rules! delegate_from_bytes {
24    ($($ty:ident)+) => ($(
25        impl $crate::FromBytes for $ty {
26            const N: usize = ::core::mem::size_of::<$ty>();
27
28            fn from_be_bytes(bytes: [u8; ::core::mem::size_of::<$ty>()]) -> Self {
29                Self::from_be_bytes(bytes)
30            }
31
32            fn from_le_bytes(bytes: [u8; ::core::mem::size_of::<$ty>()]) -> Self {
33                Self::from_le_bytes(bytes)
34            }
35
36            fn from_ne_bytes(bytes: [u8; ::core::mem::size_of::<$ty>()]) -> Self {
37                Self::from_ne_bytes(bytes)
38            }
39        }
40    )+)
41}
42
43#[macro_export]
44macro_rules! delegate_to_bytes {
45    ($($ty:ident)+) => ($(
46        impl $crate::ToBytes for $ty {
47            const N: usize = ::core::mem::size_of::<$ty>();
48
49            fn to_be_bytes(self) -> [u8; ::core::mem::size_of::<$ty>()] {
50                self.to_be_bytes()
51            }
52
53            fn to_le_bytes(self) -> [u8; ::core::mem::size_of::<$ty>()] {
54                self.to_le_bytes()
55            }
56
57            fn to_ne_bytes(self) -> [u8; ::core::mem::size_of::<$ty>()] {
58                self.to_ne_bytes()
59            }
60        }
61    )+)
62}
63
64delegate_from_bytes! { u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize f32 f64 }
65delegate_to_bytes! { u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize f32 f64 }