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 4200 : pub unsafe fn new_unchecked(buf: &'a mut [u8; N]) -> Self {
16 4200 : let _align = ConstAlign::<A>;
17 4200 : assert_eq!(buf.as_ptr().align_offset(_align.align()), 0);
18 4200 : AlignedSlice { buf, _align }
19 4200 : }
20 : }
21 :
22 : impl<'a, const N: usize, A: Alignment> Deref for AlignedSlice<'a, N, A> {
23 : type Target = [u8; N];
24 :
25 1079041 : fn deref(&self) -> &Self::Target {
26 1079041 : self.buf
27 1079041 : }
28 : }
29 :
30 : impl<'a, const N: usize, A: Alignment> DerefMut for AlignedSlice<'a, N, A> {
31 48036 : fn deref_mut(&mut self) -> &mut Self::Target {
32 48036 : self.buf
33 48036 : }
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 : }
|