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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#![no_std]
#![cfg_attr(feature = "freeze", feature(freeze))]

#[cfg(feature = "freeze")]
use core::marker::Freeze;
use core::{
    fmt,
    hash::Hash,
    panic::{RefUnwindSafe, UnwindSafe},
};

/// A Zero-sized type with the specified alignment.
///
/// To facilitate deriving traits on types containing this type, this type
/// implements most relevant traits, including [`Default`], [`Ord`], [`Copy`],
/// [`Send`], [`Sync`], [`Unpin`], etc.
///
/// With the `bytemuck` optional feature enabled, this type implements the
#[cfg_attr(feature = "bytemuck", doc = "[`bytemuck::Pod`]")]
#[cfg_attr(
    not(feature = "bytemuck"),
    doc = "[`bytemuck::Pod`](https://docs.rs/bytemuck/latest/bytemuck/trait.Pod.html)"
)]
/// trait.
///
/// With the `freeze` optional feature enabled, this type implements the
/// unstable [`core::marker::Freeze`] trait.
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct AlignedZst<const ALIGNMENT: usize>
where
    Alignment<ALIGNMENT>: SupportedAlignment,
{
    inner: <Alignment<ALIGNMENT> as SupportedAlignment>::AlignedZst,
}

impl<const ALIGNMENT: usize> fmt::Debug for AlignedZst<ALIGNMENT>
where
    Alignment<ALIGNMENT>: SupportedAlignment,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AlignedZst<{}> {{ .. }}", ALIGNMENT)
    }
}

// Safety: This is an inhabited ZST.
#[cfg(feature = "bytemuck")]
unsafe impl<const ALIGNMENT: usize> bytemuck::Zeroable for AlignedZst<ALIGNMENT> where
    Alignment<ALIGNMENT>: SupportedAlignment
{
}

// Safety: This is an inhabited ZST.
#[cfg(feature = "bytemuck")]
unsafe impl<const ALIGNMENT: usize> bytemuck::Pod for AlignedZst<ALIGNMENT> where
    Alignment<ALIGNMENT>: SupportedAlignment
{
}

mod sealed {
    pub trait Sealed {}
}

impl<const N: usize> sealed::Sealed for Alignment<N> {}

/// Specifies the alignment of [`AlignedZst`] as a type.
pub struct Alignment<const N: usize>;

/// Statically guarantees that an alignment is supported
///
/// This trait is *sealed*: the list of implementors below is total. Users to
/// not have the ability to mark additional `Alignment<N>` values as supported.
/// Only alignments supported by rustc/LLVM are constructable, i.e. powers of
/// two from 1 to `2^29`.
pub unsafe trait SupportedAlignment: sealed::Sealed {
    cfg_if::cfg_if! {
        if #[cfg(feature = "freeze")] {
            /// Safety: This must be an inhabited ZST with the specified alignment.
            #[doc(hidden)]
            type AlignedZst: Sized + Default + Copy + Ord + Hash + Send + Sync + Unpin + UnwindSafe + RefUnwindSafe + Freeze + 'static;
        } else {
            /// Safety: This must be an inhabited ZST with the specified alignment.
            #[doc(hidden)]
            type AlignedZst: Sized + Default + Copy + Ord + Hash + Send + Sync + Unpin + UnwindSafe + RefUnwindSafe + 'static;
        }
    }
}

macro_rules! make_zsts {
    ( $($typename:ident = $alignment:literal;)* ) => { $(
        /// Helper type used only as a field in [`AlignedZst`].
        ///
        #[doc = concat!("Is a ZST with alignment ", stringify!($alignment), ".")]
        #[doc(hidden)]
        #[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[repr(align($alignment))]
        pub struct $typename;

        unsafe impl SupportedAlignment for Alignment<$alignment> {
            type AlignedZst = $typename;
        }
     )* };
}

make_zsts! {
    Align1 = 1;
    Align2 = 2;
    Align4 = 4;
    Align8 = 8;
    Align16 = 16;
    Align32 = 32;
    Align64 = 64;
    Align128 = 128;
    Align256 = 256;
    Align512 = 512;
    Align1024 = 1024;
    Align2048 = 2048;
    Align4096 = 4096;
    Align8192 = 8192;
    Align16384 = 16384;
    Align32768 = 32768;
    Align65536 = 65536;
    Align131072 = 131072;
    Align262144 = 262144;
    Align524288 = 524288;
    Align1048576 = 1048576;
    Align2097152 = 2097152;
    Align4194304 = 4194304;
    Align8388608 = 8388608;
    Align16777216 = 16777216;
    Align33554432 = 33554432;
    Align67108864 = 67108864;
    Align134217728 = 134217728;
    Align268435456 = 268435456;
    Align536870912 = 536870912;
}

#[cfg(test)]
mod tests {
    extern crate std;

    use crate::{AlignedZst, Alignment, SupportedAlignment};

    #[test]
    fn it_works() {
        #[derive(Default, Clone, Copy)]
        struct AlignedThing<const N: usize, T>
        where
            Alignment<N>: SupportedAlignment,
        {
            _aligned: AlignedZst<N>,
            value: T,
        }

        assert_eq!(core::mem::align_of::<AlignedThing<64, u8>>(), 64);
        assert_eq!(
            core::mem::align_of::<AlignedThing<4, u64>>(),
            core::cmp::max(4, core::mem::align_of::<u64>())
        );
        assert_eq!(
            core::mem::align_of::<AlignedThing<536870912, u8>>(),
            536870912
        );

        let x: [AlignedThing<64, u8>; 2] =
            [AlignedThing { value: 42, _aligned: Default::default() }; 2];
        assert_eq!(
            (&x[1].value as *const _ as usize)
                - (&x[0].value as *const _ as usize),
            64
        );
    }
}