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.
10pub trait Alignment:
11    sealed::Sealed + fmt::Debug + Default + Copy + Send + Sync + Unpin + 'static
12{
13    /// Alignment in bytes
14    const ALIGN: usize;
15}
16
17/// Alignment that is at least as strict as `A`, such that anything aligned to `Self` is also
18/// aligned to `A`
19#[diagnostic::on_unimplemented(message = "Alignment `{Self}` doesn't guarantee alignment `{A}`")]
20pub trait AtLeast<A>: Alignment
21where
22    A: Alignment,
23{
24}
25
26macro_rules! define_alignments {
27    ($($name:ident = $align:literal),+ $(,)?) => {
28        $(
29            #[doc = concat!("Alignment of ", stringify!($align), " bytes")]
30            #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
31            pub struct $name;
32
33            impl sealed::Sealed for $name {}
34
35            impl Alignment for $name {
36                const ALIGN: usize = $align;
37            }
38        )+
39    };
40}
41
42define_alignments!(
43    Align1 = 1,
44    Align2 = 2,
45    Align4 = 4,
46    Align8 = 8,
47    Align16 = 16,
48    Align32 = 32,
49    Align64 = 64,
50    Align128 = 128,
51    Align256 = 256,
52    Align512 = 512,
53    Align1024 = 1024,
54    Align2048 = 2048,
55    Align4096 = 4096,
56);
57
58/// Implements `AtLeast` for every alignment and every alignment that is not stricter than it,
59/// alignments must be listed from the strictest one
60macro_rules! impl_at_least {
61    () => {};
62    ($strictest:ident $(, $rest:ident)*) => {
63        impl AtLeast<$strictest> for $strictest {}
64        $(
65            impl AtLeast<$rest> for $strictest {}
66        )*
67        impl_at_least!($($rest),*);
68    };
69}
70
71impl_at_least!(
72    Align4096, Align2048, Align1024, Align512, Align256, Align128, Align64, Align32, Align16,
73    Align8, Align4, Align2, Align1
74);