graven/
le.rs

1/// Fixed-size little-endian value. `read_le`/`write_le` require a slice of exactly `SIZE` bytes.
2pub trait Le: Copy + Default {
3    const SIZE: usize;
4    fn read_le(b: &[u8]) -> Self;
5    fn write_le(self, out: &mut [u8]);
6}
7
8macro_rules! impl_le {
9    ($($t:ty),*) => {$(
10        impl Le for $t {
11            const SIZE: usize = core::mem::size_of::<$t>();
12            #[inline(always)]
13            fn read_le(b: &[u8]) -> Self {
14                let mut a = [0u8; core::mem::size_of::<$t>()];
15                a.copy_from_slice(b);
16                <$t>::from_le_bytes(a)
17            }
18            #[inline(always)]
19            fn write_le(self, out: &mut [u8]) {
20                out.copy_from_slice(&self.to_le_bytes());
21            }
22        }
23    )*};
24}
25
26impl_le!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64);
27
28/// 1 byte (`[bool]` elements, `bool` inside a struct). Spec §5.3 / §6.3: the writer writes
29/// `00` or `01`; the reader reads `00` as false and any other value as true.
30///
31/// Not used for a `bool` **table field**: that one has no slot, only 2 bits (presence +
32/// value, spec §4.4), written with `TableW::set_bool` / `FixedW::set_bool` and read with
33/// [`TableRef::bool`](crate::TableRef::bool). This 1-byte form is only for struct fields
34/// and `[bool]` elements.
35impl Le for bool {
36    const SIZE: usize = 1;
37    #[inline(always)]
38    fn read_le(b: &[u8]) -> Self {
39        b[0] != 0
40    }
41    #[inline(always)]
42    fn write_le(self, out: &mut [u8]) {
43        out[0] = self as u8;
44    }
45}