1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crate::{protocol::Endianness, Signature};

/// A verbatim frame that can be stored and loaded from a buffer.
///
/// This is implemented for primitives `Copy` types such as `u32`.
///
/// # Safety
///
/// This asserts that the implementor is `repr(C)`, and can inhabit any bit
/// pattern.
///
/// Any type implementing `Frame` must have an alignment of at most `8`.
pub unsafe trait Frame {
    /// The signature of the frame.
    const SIGNATURE: &'static Signature;

    /// Adjust the endianness of the frame.
    fn adjust(&mut self, endianness: Endianness);
}

unsafe impl Frame for u8 {
    const SIGNATURE: &'static Signature = Signature::BYTE;

    #[inline]
    fn adjust(&mut self, _: Endianness) {}
}

unsafe impl Frame for f64 {
    const SIGNATURE: &'static Signature = Signature::DOUBLE;

    #[inline]
    fn adjust(&mut self, endianness: Endianness) {
        if endianness != Endianness::NATIVE {
            *self = f64::from_bits(u64::swap_bytes(self.to_bits()));
        }
    }
}

macro_rules! impl_number {
    ($($ty:ty, $signature:ident),* $(,)?) => {
        $(
            unsafe impl Frame for $ty {
                const SIGNATURE: &'static Signature = Signature::$signature;

                #[inline]
                fn adjust(&mut self, endianness: Endianness) {
                    if endianness != Endianness::NATIVE {
                        *self = <$ty>::swap_bytes(*self);
                    }
                }
            }
        )*
    }
}

impl_number!(i16, INT16, i32, INT32, i64, INT64);
impl_number!(u16, UINT16, u32, UINT32, u64, UINT64);