tokio_dbus/
frame.rs

1use crate::proto::Endianness;
2use crate::Signature;
3
4pub(crate) mod sealed {
5    pub trait Sealed {}
6}
7
8/// A verbatim frame that can be stored and loaded from a buffer.
9///
10/// This is implemented for primitives `Copy` types such as `u32`.
11///
12/// # Safety
13///
14/// This asserts that the implementor is `repr(C)`, and can inhabit any bit
15/// pattern.
16///
17/// Any type implementing `Frame` must have an alignment of at most `8`.
18pub unsafe trait Frame: self::sealed::Sealed {
19    /// The signature of the frame.
20    #[doc(hidden)]
21    const SIGNATURE: &'static Signature;
22
23    /// Adjust the endianness of the frame.
24    #[doc(hidden)]
25    fn adjust(&mut self, endianness: Endianness);
26}
27
28impl self::sealed::Sealed for u8 {}
29
30unsafe impl Frame for u8 {
31    const SIGNATURE: &'static Signature = Signature::BYTE;
32
33    #[inline]
34    fn adjust(&mut self, _: Endianness) {}
35}
36
37impl_traits_for_frame!(u8);
38
39impl self::sealed::Sealed for f64 {}
40
41unsafe impl Frame for f64 {
42    const SIGNATURE: &'static Signature = Signature::DOUBLE;
43
44    #[inline]
45    fn adjust(&mut self, endianness: Endianness) {
46        if endianness != Endianness::NATIVE {
47            *self = f64::from_bits(u64::swap_bytes(self.to_bits()));
48        }
49    }
50}
51
52impl_traits_for_frame!(f64);
53
54macro_rules! impl_number {
55    ($($ty:ty, $signature:ident),* $(,)?) => {
56        $(
57            impl self::sealed::Sealed for $ty {}
58
59            unsafe impl Frame for $ty {
60                const SIGNATURE: &'static Signature = Signature::$signature;
61
62                #[inline]
63                fn adjust(&mut self, endianness: Endianness) {
64                    if endianness != Endianness::NATIVE {
65                        *self = <$ty>::swap_bytes(*self);
66                    }
67                }
68            }
69
70            impl_traits_for_frame!($ty);
71        )*
72    }
73}
74
75impl_number!(i16, INT16, i32, INT32, i64, INT64);
76impl_number!(u16, UINT16, u32, UINT32, u64, UINT64);