Line data Source code
1 : use std::ops::{Deref, DerefMut};
2 :
3 : use super::alignment::{Alignment, ConstAlign};
4 :
5 : /// Newtype for an aligned slice.
6 : pub struct AlignedSlice<'a, const N: usize, A: Alignment> {
7 : /// underlying byte slice
8 : buf: &'a mut [u8; N],
9 : /// alignment marker
10 : _align: A,
11 : }
12 :
13 : impl<'a, const N: usize, const A: usize> AlignedSlice<'a, N, ConstAlign<A>> {
14 : /// Create a new aligned slice from a mutable byte slice. The input must already satisify the alignment.
15 4400 : pub unsafe fn new_unchecked(buf: &'a mut [u8; N]) -> Self {
16 4400 : let _align = ConstAlign::<A>;
17 4400 : assert_eq!(buf.as_ptr().align_offset(_align.align()), 0);
18 4400 : AlignedSlice { buf, _align }
19 4400 : }
20 : }
21 :
22 : impl<'a, const N: usize, A: Alignment> Deref for AlignedSlice<'a, N, A> {
23 : type Target = [u8; N];
24 :
25 1015964 : fn deref(&self) -> &Self::Target {
26 1015964 : self.buf
27 1015964 : }
28 : }
29 :
30 : impl<'a, const N: usize, A: Alignment> DerefMut for AlignedSlice<'a, N, A> {
31 48078 : fn deref_mut(&mut self) -> &mut Self::Target {
32 48078 : self.buf
33 48078 : }
34 : }
35 :
36 : impl<'a, const N: usize, A: Alignment> AsRef<[u8; N]> for AlignedSlice<'a, N, A> {
37 0 : fn as_ref(&self) -> &[u8; N] {
38 0 : self.buf
39 0 : }
40 : }
|