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
use std::alloc::Layout;
use std::mem::ManuallyDrop;
use std::ptr::NonNull;

/// Extension methods for `Box<T>`
pub trait BoxExt: Sized {
    /// The type that the `Box<T>` stores
    type T: ?Sized;

    /// drops the value inside the box and returns the allocation
    /// in the form of an `UninitBox`
    fn drop_box(bx: Self) -> UninitBox;

    /// takes the value inside the box and returns it as well as the
    /// allocation in the form of an `UninitBox`
    fn take_box(bx: Self) -> (UninitBox, Self::T)
    where
        Self::T: Sized;
}

impl<T: ?Sized> BoxExt for Box<T> {
    type T = T;

    fn drop_box(bx: Self) -> UninitBox {
        unsafe {
            let layout = Layout::for_value::<T>(&bx);
            let ptr = NonNull::new_unchecked(Box::into_raw(bx));

            ptr.as_ptr().drop_in_place();

            UninitBox {
                ptr: ptr.cast(),
                layout,
            }
        }
    }

    fn take_box(bx: Self) -> (UninitBox, Self::T)
    where
        Self::T: Sized,
    {
        unsafe {
            let ptr = NonNull::new_unchecked(Box::into_raw(bx));

            let value = ptr.as_ptr().read();

            (
                UninitBox {
                    ptr: ptr.cast(),
                    layout: Layout::new::<T>(),
                },
                value,
            )
        }
    }
}

/// An uninitialized piece of memory
pub struct UninitBox {
    ptr: NonNull<u8>,
    layout: Layout,
}

impl UninitBox {
    /// The layout of the allocation
    #[inline]
    pub fn layout(&self) -> Layout {
        self.layout
    }

    /// create a new allocation that can fit the given type
    #[inline]
    pub fn new<T>() -> Self {
        Self::from_layout(Layout::new::<T>())
    }

    /// Create a new allocation that can fit the given layout
    #[inline]
    pub fn from_layout(layout: Layout) -> Self {
        if layout.size() == 0 {
            UninitBox {
                layout,
                ptr: unsafe { NonNull::new_unchecked(layout.align() as *mut u8) },
            }
        } else {
            let ptr = unsafe { std::alloc::alloc(layout) };

            if ptr.is_null() {
                std::alloc::handle_alloc_error(layout)
            } else {
                unsafe {
                    UninitBox {
                        ptr: NonNull::new_unchecked(ptr),
                        layout,
                    }
                }
            }
        }
    }

    /// Initialize the box with the given value,
    ///
    /// # Panic
    ///
    /// if `std::alloc::Layout::new::<T>() != self.layout()` then
    /// this function will panic
    #[inline]
    pub fn init<T>(self, value: T) -> Box<T> {
        assert_eq!(
            self.layout,
            Layout::new::<T>(),
            "Layout of UninitBox is incompatible with `T`"
        );

        let bx = ManuallyDrop::new(self);

        let ptr = bx.ptr.cast::<T>().as_ptr();

        unsafe {
            ptr.write(value);

            Box::from_raw(ptr)
        }
    }

    /// Initialize the box with the given value,
    ///
    /// # Panic
    ///
    /// if `std::alloc::Layout::new::<T>() != self.layout()` then
    /// this function will panic
    #[inline]
    pub fn init_with<T, F: FnOnce() -> T>(self, value: F) -> Box<T> {
        assert_eq!(
            self.layout,
            Layout::new::<T>(),
            "Layout of UninitBox is incompatible with `T`"
        );

        let bx = ManuallyDrop::new(self);

        let ptr = bx.ptr.cast::<T>().as_ptr();

        unsafe {
            ptr.write(value());

            Box::from_raw(ptr)
        }
    }

    /// Get the pointer from the `UninitBox`
    ///
    /// This pointer is not valid to write to
    #[inline]
    pub fn as_ptr(&self) -> *const () {
        self.ptr.as_ptr() as *const ()
    }

    /// Get the pointer from the `UninitBox`
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut () {
        self.ptr.as_ptr() as *mut ()
    }
}

impl Drop for UninitBox {
    fn drop(&mut self) {
        unsafe { std::alloc::dealloc(self.ptr.as_ptr(), self.layout) }
    }
}