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
use crate::aligned_alloc;

use alloc::alloc::{alloc, dealloc, Layout};
use core::fmt::{self, Debug};
use core::marker::PhantomData;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::{drop_in_place, NonNull};

/// Aligned heap allocation
pub struct AlignedBox<T: ?Sized> {
    inner: NonNull<T>,
    align: usize,
    _marker: PhantomData<T>,
}

unsafe impl<T: ?Sized + Send> Send for AlignedBox<T> {}
unsafe impl<T: ?Sized + Sync> Sync for AlignedBox<T> {}

#[cfg(feature = "std")]
mod std_impl {
    use super::AlignedBox;

    use std::panic::{RefUnwindSafe, UnwindSafe};

    impl<T: ?Sized + UnwindSafe> UnwindSafe for AlignedBox<T> {}
    impl<T: ?Sized + RefUnwindSafe> RefUnwindSafe for AlignedBox<T> {}
}

impl<T> AlignedBox<T> {
    /// Allocates memory on the heap with specified alignment and then places x into it.
    ///
    /// This doesn't actually allocate if T is zero-sized.
    pub fn new(x: T, align: usize) -> Self {
        let size = mem::size_of::<T>();
        let align = mem::align_of::<T>().max(align);

        let inner = if size == 0 {
            NonNull::dangling()
        } else {
            unsafe {
                let ptr = aligned_alloc(alloc, size, align).cast::<T>();
                ptr.write(x);
                NonNull::new_unchecked(ptr)
            }
        };

        Self {
            align,
            inner,
            _marker: PhantomData,
        }
    }
}

impl<T: ?Sized> AlignedBox<T> {
    /// Consumes the box, returning a raw pointer and alignment.
    pub fn into_raw(this: Self) -> (*mut T, usize) {
        let ans = (this.inner.as_ptr(), this.align);
        mem::forget(this);
        ans
    }

    /// Constructs a aligned box from a raw pointer and alignment
    /// # Safety
    /// + `ptr` must be non-null and well aligned for `align`
    /// + `ptr` must be allocated with the global allocator
    pub unsafe fn from_raw(ptr: *mut T, align: usize) -> Self {
        Self {
            inner: NonNull::new_unchecked(ptr),
            align,
            _marker: PhantomData,
        }
    }

    /// Returns the alignment of the box
    pub fn alignment(this: &Self) -> usize {
        this.align
    }
}

impl<T: ?Sized> Drop for AlignedBox<T> {
    fn drop(&mut self) {
        unsafe {
            let size = mem::size_of_val(self.inner.as_ref());
            if size == 0 {
                return;
            }
            let ptr = self.inner.as_ptr();
            drop_in_place(ptr);

            let layout = Layout::from_size_align_unchecked(size, self.align);
            dealloc(ptr.cast(), layout)
        }
    }
}

impl<T: ?Sized> Deref for AlignedBox<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.inner.as_ptr() }
    }
}

impl<T: ?Sized> DerefMut for AlignedBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.inner.as_ptr() }
    }
}

impl<T: ?Sized + Debug> Debug for AlignedBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        T::fmt(self, f)
    }
}