Skip to main content

ab_aligned_buffer/
alignment.rs

1//! Alignment of buffers
2
3use crate::sealed;
4use core::fmt;
5
6/// Alignment in bytes, a power of two from 1 to 4096.
7///
8/// Used as a type parameter of buffers for the alignment of their contents, and as a value for the
9/// alignment of allocations.
10#[diagnostic::on_unimplemented(
11    message = "`{Self}` is not a supported alignment",
12    note = "Supported alignments are powers of two from 1 to 4096"
13)]
14pub trait Alignment:
15    sealed::Sealed + fmt::Debug + Default + Copy + Send + Sync + Unpin + 'static
16{
17    /// Alignment in bytes
18    const ALIGN: u32;
19}
20
21/// Alignment of `ALIGN` bytes, only powers of two from 1 to 4096 implement [`Alignment`]
22#[derive(Default, Copy, Clone, Eq, PartialEq)]
23pub struct Align<const ALIGN: u32>;
24
25impl<const ALIGN: u32> fmt::Debug for Align<ALIGN> {
26    #[inline]
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "Align<{ALIGN}>")
29    }
30}
31
32/// Alignment that is at least as strict as `A`, such that anything aligned to `Self` is also
33/// aligned to `A`
34#[diagnostic::on_unimplemented(message = "Alignment `{Self}` doesn't guarantee alignment `{A}`")]
35pub trait AtLeast<A>: Alignment
36where
37    A: Alignment,
38{
39}
40
41macro_rules! define_alignments {
42    ($($name:ident = $align:literal),+ $(,)?) => {
43        $(
44            #[doc = concat!("Alignment of ", stringify!($align), " bytes")]
45            pub type $name = Align<$align>;
46
47            impl sealed::Sealed for $name {}
48
49            impl Alignment for $name {
50                const ALIGN: u32 = $align;
51            }
52        )+
53    };
54}
55
56define_alignments!(
57    Align1 = 1,
58    Align2 = 2,
59    Align4 = 4,
60    Align8 = 8,
61    Align16 = 16,
62    Align32 = 32,
63    Align64 = 64,
64    Align128 = 128,
65    Align256 = 256,
66    Align512 = 512,
67    Align1024 = 1024,
68    Align2048 = 2048,
69    Align4096 = 4096,
70);
71
72/// Every alignment is at least 1 byte, which generic code can rely on with just an `Alignment`
73/// bound
74impl<A> AtLeast<Align1> for A where A: Alignment {}
75
76/// Implements `AtLeast` for every alignment and every alignment that is not stricter than it,
77/// alignments must be listed from the strictest one, `Align1` is covered by the implementation
78/// above
79macro_rules! impl_at_least {
80    () => {};
81    ($strictest:ident $(, $rest:ident)*) => {
82        impl AtLeast<$strictest> for $strictest {}
83        $(
84            impl AtLeast<$rest> for $strictest {}
85        )*
86        impl_at_least!($($rest),*);
87    };
88}
89
90impl_at_least!(
91    Align4096, Align2048, Align1024, Align512, Align256, Align128, Align64, Align32, Align16,
92    Align8, Align4, Align2
93);