wasm/execution/
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
4use super::value::{F32, F64};
5
6/// This macro implements the [`LittleEndianBytes`] trait for a provided list of types.
7///
8/// # Assumptions
9///
10/// Each type for which this macro is executed must provide a `from_le_bytes` and `to_le_bytes`
11/// function.
12macro_rules! impl_LittleEndianBytes{
13        [$($type:ty),+] => {
14
15            $(impl LittleEndianBytes<{ ::core::mem::size_of::<$type>() }> for $type {
16                fn from_le_bytes(bytes: [u8; ::core::mem::size_of::<$type>()]) -> Self {
17                    Self::from_le_bytes(bytes)
18                }
19
20                fn to_le_bytes(self) -> [u8; ::core::mem::size_of::<$type>()] {
21                    self.to_le_bytes()
22                }
23            })+
24        }
25    }
26
27/// Convert from and to the little endian byte representation of a value
28///
29/// `N` denotes the number of bytes required for the little endian representation
30pub trait LittleEndianBytes<const N: usize> {
31    /// Convert from a byte array to Self
32    fn from_le_bytes(bytes: [u8; N]) -> Self;
33
34    /// Convert from self to a byte array
35    fn to_le_bytes(self) -> [u8; N];
36}
37
38// implements the [`LittleEndianBytes`]
39impl_LittleEndianBytes![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128];
40
41impl LittleEndianBytes<4> for F32 {
42    fn from_le_bytes(bytes: [u8; 4]) -> Self {
43        F32(f32::from_le_bytes(bytes))
44    }
45
46    fn to_le_bytes(self) -> [u8; 4] {
47        self.0.to_le_bytes()
48    }
49}
50
51impl LittleEndianBytes<8> for F64 {
52    fn from_le_bytes(bytes: [u8; 8]) -> Self {
53        F64(f64::from_le_bytes(bytes))
54    }
55
56    fn to_le_bytes(self) -> [u8; 8] {
57        self.0.to_le_bytes()
58    }
59}