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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! A newtype with alignment of at least `A` bytes
//!
//! # Examples
//!
//! ```
//! use std::mem;
//!
//! use aligned::{Aligned, A2, A4, A16};
//!
//! // Array aligned to a 2 byte boundary
//! static X: Aligned<A2, [u8; 3]> = Aligned([0; 3]);
//!
//! // Array aligned to a 4 byte boundary
//! static Y: Aligned<A4, [u8; 3]> = Aligned([0; 3]);
//!
//! // Unaligned array
//! static Z: [u8; 3] = [0; 3];
//!
//! // You can allocate the aligned arrays on the stack too
//! let w: Aligned<A16, _> = Aligned([0u8; 3]);
//!
//! assert_eq!(mem::align_of_val(&X), 2);
//! assert_eq!(mem::align_of_val(&Y), 4);
//! assert_eq!(mem::align_of_val(&Z), 1);
//! assert_eq!(mem::align_of_val(&w), 16);
//! ```

#![deny(missing_docs)]
#![deny(warnings)]
#![cfg_attr(not(test), no_std)]

use core::{
    borrow::{Borrow, BorrowMut},
    cmp::Ordering,
    fmt::{Debug, Display},
    hash::{Hash, Hasher},
    ops,
};

use as_slice::{AsMutSlice, AsSlice};

/// A marker trait for an alignment value.
pub trait Alignment: Copy + sealed::Sealed {}

impl Alignment for A1 {}
impl Alignment for A2 {}
impl Alignment for A4 {}
impl Alignment for A8 {}
impl Alignment for A16 {}
impl Alignment for A32 {}
impl Alignment for A64 {}

mod sealed {
    pub trait Sealed {}

    impl Sealed for super::A1 {}
    impl Sealed for super::A2 {}
    impl Sealed for super::A4 {}
    impl Sealed for super::A8 {}
    impl Sealed for super::A16 {}
    impl Sealed for super::A32 {}
    impl Sealed for super::A64 {}
}

/// 1-byte alignment
#[derive(Clone, Copy)]
#[repr(align(1))]
pub struct A1;

/// 2-byte alignment
#[derive(Clone, Copy)]
#[repr(align(2))]
pub struct A2;

/// 4-byte alignment
#[derive(Clone, Copy)]
#[repr(align(4))]
pub struct A4;

/// 8-byte alignment
#[derive(Clone, Copy)]
#[repr(align(8))]
pub struct A8;

/// 16-byte alignment
#[derive(Clone, Copy)]
#[repr(align(16))]
pub struct A16;

/// 32-byte alignment
#[derive(Clone, Copy)]
#[repr(align(32))]
pub struct A32;

/// 64-byte alignment
#[derive(Clone, Copy)]
#[repr(align(64))]
pub struct A64;

/// A newtype with alignment of at least `A` bytes
#[repr(C)]
pub struct Aligned<A, T>
where
    T: ?Sized,
{
    _alignment: [A; 0],
    value: T,
}

/// Changes the alignment of `value` to be at least `A` bytes
#[allow(non_snake_case)]
pub const fn Aligned<A, T>(value: T) -> Aligned<A, T> {
    Aligned {
        _alignment: [],
        value,
    }
}

impl<A, T> ops::Deref for Aligned<A, T>
where
    A: Alignment,
    T: ?Sized,
{
    type Target = T;

    fn deref(&self) -> &T {
        &self.value
    }
}

impl<A, T> ops::DerefMut for Aligned<A, T>
where
    A: Alignment,
    T: ?Sized,
{
    fn deref_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

impl<A, T> ops::Index<ops::RangeTo<usize>> for Aligned<A, [T]>
where
    A: Alignment,
{
    type Output = Aligned<A, [T]>;

    fn index(&self, range: ops::RangeTo<usize>) -> &Aligned<A, [T]> {
        unsafe { &*(&self.value[range] as *const [T] as *const Aligned<A, [T]>) }
    }
}

impl<A, T> AsSlice for Aligned<A, T>
where
    A: Alignment,
    T: AsSlice,
{
    type Element = T::Element;

    fn as_slice(&self) -> &[T::Element] {
        T::as_slice(&**self)
    }
}

impl<A, T> AsMutSlice for Aligned<A, T>
where
    A: Alignment,
    T: AsMutSlice,
{
    fn as_mut_slice(&mut self) -> &mut [T::Element] {
        T::as_mut_slice(&mut **self)
    }
}

impl<A, T> Borrow<T> for Aligned<A, T>
where
    A: Alignment,
{
    fn borrow(&self) -> &T {
        &self.value
    }
}

impl<A, T> BorrowMut<T> for Aligned<A, T>
where
    A: Alignment,
{
    fn borrow_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

impl<A, T> Borrow<[<Aligned<A, T> as AsSlice>::Element]> for Aligned<A, T>
where
    A: Alignment,
    Aligned<A, T>: AsSlice,
{
    fn borrow(&self) -> &[<Aligned<A, T> as AsSlice>::Element] {
        self.as_slice()
    }
}

impl<A, T> BorrowMut<[<Aligned<A, T> as AsSlice>::Element]> for Aligned<A, T>
where
    A: Alignment,
    Aligned<A, T>: AsMutSlice,
{
    fn borrow_mut(&mut self) -> &mut [<Aligned<A, T> as AsSlice>::Element] {
        self.as_mut_slice()
    }
}

impl<A, T> Clone for Aligned<A, T>
where
    A: Alignment,
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            _alignment: [],
            value: self.value.clone(),
        }
    }
}

impl<A, T> Copy for Aligned<A, T>
where
    A: Alignment,
    T: Copy,
{
}

impl<A, T> Default for Aligned<A, T>
where
    A: Alignment,
    T: Default,
{
    fn default() -> Self {
        Self {
            _alignment: [],
            value: Default::default(),
        }
    }
}

impl<A, T> Debug for Aligned<A, T>
where
    A: Alignment,
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.value.fmt(f)
    }
}

impl<A, T> Display for Aligned<A, T>
where
    A: Alignment,
    T: Display,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.value.fmt(f)
    }
}

impl<A, T> PartialEq for Aligned<A, T>
where
    A: Alignment,
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<A, T> Eq for Aligned<A, T>
where
    A: Alignment,
    T: Eq,
{
}

impl<A, T> Hash for Aligned<A, T>
where
    A: Alignment,
    T: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value.hash(state);
    }
}

impl<A, T> Ord for Aligned<A, T>
where
    A: Alignment,
    T: Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        self.value.cmp(&other.value)
    }
}

impl<A, T> PartialOrd for Aligned<A, T>
where
    A: Alignment,
    T: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.value.partial_cmp(&other.value)
    }
}

#[test]
fn sanity() {
    use core::mem;

    let a: Aligned<A1, _> = Aligned([0u8; 3]);
    let x: Aligned<A2, _> = Aligned([0u8; 3]);
    let y: Aligned<A4, _> = Aligned([0u8; 3]);
    let z: Aligned<A8, _> = Aligned([0u8; 3]);
    let w: Aligned<A16, _> = Aligned([0u8; 3]);

    // check alignment
    assert_eq!(mem::align_of_val(&a), 1);
    assert_eq!(mem::align_of_val(&x), 2);
    assert_eq!(mem::align_of_val(&y), 4);
    assert_eq!(mem::align_of_val(&z), 8);
    assert_eq!(mem::align_of_val(&w), 16);

    assert!(a.as_ptr() as usize % 1 == 0);
    assert!(x.as_ptr() as usize % 2 == 0);
    assert!(y.as_ptr() as usize % 4 == 0);
    assert!(z.as_ptr() as usize % 8 == 0);
    assert!(w.as_ptr() as usize % 16 == 0);

    // test `deref`
    assert_eq!(a.len(), 3);
    assert_eq!(x.len(), 3);
    assert_eq!(y.len(), 3);
    assert_eq!(z.len(), 3);
    assert_eq!(w.len(), 3);

    // alignment should be preserved after slicing
    let a: &Aligned<_, [_]> = &a;
    let x: &Aligned<_, [_]> = &x;
    let y: &Aligned<_, [_]> = &y;
    let z: &Aligned<_, [_]> = &z;
    let w: &Aligned<_, [_]> = &w;

    let a: &Aligned<_, _> = &a[..2];
    let x: &Aligned<_, _> = &x[..2];
    let y: &Aligned<_, _> = &y[..2];
    let z: &Aligned<_, _> = &z[..2];
    let w: &Aligned<_, _> = &w[..2];

    assert!(a.as_ptr() as usize % 1 == 0);
    assert!(x.as_ptr() as usize % 2 == 0);
    assert!(y.as_ptr() as usize % 4 == 0);
    assert!(z.as_ptr() as usize % 8 == 0);
    assert!(w.as_ptr() as usize % 16 == 0);

    // alignment should be preserved after boxing
    let a: Box<Aligned<A1, [u8]>> = Box::new(Aligned([0u8; 3]));
    let x: Box<Aligned<A2, [u8]>> = Box::new(Aligned([0u8; 3]));
    let y: Box<Aligned<A4, [u8]>> = Box::new(Aligned([0u8; 3]));
    let z: Box<Aligned<A8, [u8]>> = Box::new(Aligned([0u8; 3]));
    let w: Box<Aligned<A16, [u8]>> = Box::new(Aligned([0u8; 3]));

    assert_eq!(mem::align_of_val(&*a), 1);
    assert_eq!(mem::align_of_val(&*x), 2);
    assert_eq!(mem::align_of_val(&*y), 4);
    assert_eq!(mem::align_of_val(&*z), 8);
    assert_eq!(mem::align_of_val(&*w), 16);

    // test coercions
    let x: Aligned<A2, _> = Aligned([0u8; 3]);
    let y: &Aligned<A2, [u8]> = &x;
    let _: &[u8] = y;
}