tokio_dbus/alignment.rs
1use crate::ty;
2
3/// The alignment of a D-Bus type, as a runtime value.
4///
5/// D-Bus values are padded to the alignment of their type, which for the static
6/// writers in this crate is derived from a [`ty::Marker`]. Code which works with
7/// types that are only known at runtime needs to pass it explicitly instead.
8///
9/// # Examples
10///
11/// ```
12/// use tokio_dbus::{ty, Alignment};
13///
14/// assert_eq!(Alignment::of::<u8>(), Alignment::BYTE);
15/// assert_eq!(Alignment::of::<ty::Str>(), Alignment::U32);
16/// assert_eq!(Alignment::of::<(u8, u8)>(), Alignment::U64);
17/// ```
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19#[non_exhaustive]
20pub enum Alignment {
21 /// Alignment of one byte, used by `y`, `g` and `v`.
22 BYTE,
23 /// Alignment of two bytes, used by `n` and `q`.
24 U16,
25 /// Alignment of four bytes, used by `b`, `i`, `u`, `h`, `s`, `o` and by the
26 /// length prefix of an array.
27 U32,
28 /// Alignment of eight bytes, used by `x`, `t`, `d`, structs and dict
29 /// entries.
30 U64,
31}
32
33impl Alignment {
34 /// The alignment of the type described by the [`ty::Marker`] `T`.
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use tokio_dbus::{ty, Alignment};
40 ///
41 /// assert_eq!(Alignment::of::<u64>(), Alignment::U64);
42 /// assert_eq!(Alignment::of::<ty::Variant>(), Alignment::BYTE);
43 /// ```
44 pub const fn of<T>() -> Self
45 where
46 T: ty::Aligned,
47 {
48 match align_of::<T::Alignment>() {
49 1 => Alignment::BYTE,
50 2 => Alignment::U16,
51 4 => Alignment::U32,
52 _ => Alignment::U64,
53 }
54 }
55
56 /// The alignment as a number of bytes, which is always a power of two.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// use tokio_dbus::Alignment;
62 ///
63 /// assert_eq!(Alignment::BYTE.in_bytes(), 1);
64 /// assert_eq!(Alignment::U64.in_bytes(), 8);
65 /// ```
66 pub const fn in_bytes(self) -> usize {
67 match self {
68 Alignment::BYTE => 1,
69 Alignment::U16 => 2,
70 Alignment::U32 => 4,
71 Alignment::U64 => 8,
72 }
73 }
74}