wasm/core/
little_endian.rs

1//! This module contains the definition and implementation of [`LittleEndianBytes`], a trait to
2//! convert values (such as integers or floats) to bytes in little endian byter order
3
4/// This macro implements the [`LittleEndianBytes`] trait for a provided list of types.
5///
6/// # Assumptions
7///
8/// Each type for which this macro is executed must provide a `from_le_bytes` and `to_le_bytes`
9/// function.
10macro_rules! impl_LittleEndianBytes{
11        [$($type:ty),+] => {
12
13            $(impl LittleEndianBytes<{ ::core::mem::size_of::<$type>() }> for $type {
14                fn from_le_bytes(bytes: [u8; ::core::mem::size_of::<$type>()]) -> Self {
15                    Self::from_le_bytes(bytes)
16                }
17
18                fn to_le_bytes(self) -> [u8; ::core::mem::size_of::<$type>()] {
19                    self.to_le_bytes()
20                }
21            })+
22        }
23    }
24
25/// Convert from and to the little endian byte representation of a value
26///
27/// `N` denotes the number of bytes required for the little endian representation
28pub trait LittleEndianBytes<const N: usize> {
29    /// Convert from a byte array to Self
30    fn from_le_bytes(bytes: [u8; N]) -> Self;
31
32    /// Convert from self to a byte array
33    fn to_le_bytes(self) -> [u8; N];
34}
35
36// implements the [`LittleEndianBytes`]
37impl_LittleEndianBytes![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64];