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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#![no_std]
#![feature(allocator_api)]
#![feature(ptr_internals)]
#![feature(try_reserve)]
#![feature(dropck_eyepatch)]
#![feature(rustc_private)]

extern crate alloc;
use alloc::alloc::handle_alloc_error;
use alloc::alloc::{Global, Layout};
use alloc::boxed::Box;
use core::alloc::Alloc;
use core::mem;
use core::ptr::{NonNull, Unique};

pub struct RealBox<T, A: Alloc = Global> {
    ptr: Unique<T>,
    a: A,
}

impl<T, A: Alloc> RealBox<T, A> {
    /// Gets a raw pointer to the start of the allocation. Note that this is
    /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
    /// be careful.
    pub fn ptr(&self) -> *mut T {
        self.ptr.as_ptr()
    }

    /// Returns a shared reference to the allocator backing this RawVec.
    pub fn alloc(&self) -> &A {
        &self.a
    }

    /// Returns a mutable reference to the allocator backing this RawVec.
    pub fn alloc_mut(&mut self) -> &mut A {
        &mut self.a
    }

    fn current_layout(&self) -> Option<Layout> {
        unsafe {
            let align = mem::align_of::<T>();
            let size = mem::size_of::<T>();
            Some(Layout::from_size_align_unchecked(size, align))
        }
    }
}

impl<T, A: Alloc> RealBox<T, A> {
    pub unsafe fn dealloc_buffer(&mut self) {
        let elem_size = mem::size_of::<T>();
        if elem_size != 0 {
            if let Some(layout) = self.current_layout() {
                self.a.dealloc(NonNull::from(self.ptr).cast(), layout);
            }
        }
    }
}

unsafe impl<#[may_dangle] T, A: Alloc> Drop for RealBox<T, A> {
    fn drop(&mut self) {
        unsafe {
            self.dealloc_buffer();
        }
    }
}

impl<T, A: Alloc> RealBox<T, A> {
    pub(crate) fn new_in(a: A) -> Self {
        RealBox::allocate_in(true, a)
    }

    fn allocate_in(zeroed: bool, mut a: A) -> Self {
        let elem_size = mem::size_of::<T>();

        // handles ZSTs and `cap = 0` alike
        let ptr = if elem_size == 0 {
            NonNull::<T>::dangling()
        } else {
            let align = mem::align_of::<T>();
            let layout = Layout::from_size_align(elem_size, align).unwrap();
            let result = if zeroed {
                unsafe { a.alloc_zeroed(layout) }
            } else {
                unsafe { a.alloc(layout) }
            };
            match result {
                Ok(ptr) => ptr.cast(),
                Err(_) => handle_alloc_error(layout),
            }
        };

        RealBox { ptr: ptr.into(), a }
    }
}

impl<T> RealBox<T, Global> {
    pub fn new() -> Self {
        Self::new_in(Global)
    }

    /// Converts the entire buffer into `Box<T>`.
    pub unsafe fn into_box(self) -> Box<T> {
        let output: Box<T> = Box::from_raw(self.ptr());
        mem::forget(self);
        output
    }
}

impl<T> RealBox<T, Global> {
    pub fn heap_init<F>(initialize: F) -> Box<T>
    where
        F: Fn(&mut T),
    {
        unsafe {
            let mut t = Self::new_in(Global).into_box();
            initialize(t.as_mut());
            t
        }
    }
}

impl<T, A: Alloc> RealBox<T, A> {
    pub fn new_with_allocator(a: A) -> Self {
        Self::new_in(a)
    }
}

impl<T, A: Alloc> RealBox<T, A> {
    pub unsafe fn from_raw_parts(ptr: *mut T, a: A) -> Self {
        RealBox {
            ptr: Unique::new_unchecked(ptr),
            a,
        }
    }
}

impl<T> RealBox<T, Global> {
    pub fn from_box(mut slice: Box<[T]>) -> Self {
        unsafe {
            let result = RealBox::from_raw_parts(slice.as_mut_ptr(), Global);
            mem::forget(slice);
            result
        }
    }
}

#[cfg(test)]
mod test {
    use crate::*;

    #[test]
    fn test_naive_i32() {
        let t = RealBox::<i32>::new();
        assert_ne!(t.ptr.as_ptr(), core::ptr::null_mut());
    }

    extern crate std;
    use std::alloc::System;

    #[test]
    fn test_alloc_with_system() {
        let t = RealBox::<i32, System>::new_with_allocator(System);
        assert_ne!(t.ptr.as_ptr(), core::ptr::null_mut());
    }

    //#[test]
    //#[should_panic] // This should OOM and cargo test cannot unwind it!
    //fn test_big() {
    //    use std::boxed::Box;
    //    let _ = Box::new([[0;1000];1000]);
    //}

    #[test]
    fn test_pure_big() {
        let t = RealBox::<[[i32; 100]; 1000]>::new();
        assert_ne!(t.ptr.as_ptr(), core::ptr::null_mut());
    }

    struct DummyStruct;
    #[test]
    fn test_zero() {
        use core::ptr::NonNull;
        let t = RealBox::<DummyStruct>::new();
        assert_eq!(t.ptr.as_ptr(), NonNull::<_>::dangling().as_ptr());
    }

    #[test]
    fn test_drop() {
        let t = RealBox::<[[i32; 10000]; 1000]>::new();
        let ptr = t.ptr.as_ptr();
        drop(t);
        let t = RealBox::<[[i32; 10000]; 1000]>::new();
        assert_eq!(ptr, t.ptr.as_ptr());
    }

    #[test]
    fn test_heap_init() {
        extern crate libc;
        use core::ffi::c_void;

        #[derive(Debug)]
        struct Obj {
            x: u32,
            y: f64,
            a: [u8; 4],
        }

        let stack_obj = Obj {
            x: 12,
            y: 0.9,
            a: [0xff, 0xfe, 0xfd, 0xfc],
        };

        let heap_obj = RealBox::<Obj>::heap_init(|mut t| {
            t.x = 12;
            t.y = 0.9;
            t.a = [0xff, 0xfe, 0xfd, 0xfc]
        });

        let size = mem::size_of::<Obj>();

        unsafe {
            assert_eq!(
                libc::memcmp(
                    &stack_obj as *const Obj as *const c_void,
                    Box::into_raw(heap_obj) as *const c_void,
                    size
                ),
                0
            );
        }
    }
}