flatty_base/utils/
alloc.rs

1use alloc::alloc::{alloc, dealloc, Layout};
2use core::{
3    ops::{Deref, DerefMut},
4    slice,
5};
6
7pub struct AlignedBytes {
8    data: *mut u8,
9    layout: Layout,
10}
11
12impl AlignedBytes {
13    pub fn new(size: usize, align: usize) -> Self {
14        let layout = Layout::from_size_align(size, align).unwrap();
15        let data = unsafe { alloc(layout) };
16        assert!(!data.is_null());
17        Self { data, layout }
18    }
19    pub fn from_slice(src: &[u8], align: usize) -> Self {
20        let mut this = Self::new(src.len(), align);
21        this.copy_from_slice(src);
22        this
23    }
24    pub fn layout(&self) -> Layout {
25        self.layout
26    }
27}
28
29impl Drop for AlignedBytes {
30    fn drop(&mut self) {
31        unsafe { dealloc(self.data, self.layout) };
32    }
33}
34
35impl Deref for AlignedBytes {
36    type Target = [u8];
37    fn deref(&self) -> &[u8] {
38        unsafe { slice::from_raw_parts(self.data, self.layout.size()) }
39    }
40}
41
42impl DerefMut for AlignedBytes {
43    fn deref_mut(&mut self) -> &mut [u8] {
44        unsafe { slice::from_raw_parts_mut(self.data, self.layout.size()) }
45    }
46}
47
48unsafe impl Send for AlignedBytes {}
49unsafe impl Sync for AlignedBytes {}