| 1 | |
| 2 |
|
| 3 | |
| 4 |
|
| 5 | use super::{AllocError, Flags};
|
| 6 | use alloc::boxed::Box;
|
| 7 | use core::{mem::MaybeUninit, ptr, result::Result};
|
| 8 |
|
| 9 | |
| 10 | pub trait BoxExt<T>: Sized {
|
| 11 | |
| 12 | |
| 13 | |
| 14 | fn new(x: T, flags: Flags) -> Result<Self, AllocError>;
|
| 15 |
|
| 16 | |
| 17 | |
| 18 | |
| 19 | fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError>;
|
| 20 |
|
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | fn drop_contents(this: Self) -> Box<MaybeUninit<T>>;
|
| 38 | }
|
| 39 |
|
| 40 | impl<T> BoxExt<T> for Box<T> {
|
| 41 | fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
|
| 42 | let mut b = <Self as BoxExt<_>>::new_uninit(flags)?;
|
| 43 | b.write(x);
|
| 44 | |
| 45 | Ok(unsafe { b.assume_init() })
|
| 46 | }
|
| 47 |
|
| 48 | #[cfg(any(test, testlib))]
|
| 49 | fn new_uninit(_flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError> {
|
| 50 | Ok(Box::new_uninit())
|
| 51 | }
|
| 52 |
|
| 53 | #[cfg(not(any(test, testlib)))]
|
| 54 | fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError> {
|
| 55 | let ptr = if core::mem::size_of::<MaybeUninit<T>>() == 0 {
|
| 56 | core::ptr::NonNull::<_>::dangling().as_ptr()
|
| 57 | } else {
|
| 58 | let layout = core::alloc::Layout::new::<MaybeUninit<T>>();
|
| 59 |
|
| 60 | |
| 61 | |
| 62 | |
| 63 | let ptr =
|
| 64 | unsafe { super::allocator::krealloc_aligned(core::ptr::null_mut(), layout, flags) };
|
| 65 | if ptr.is_null() {
|
| 66 | return Err(AllocError);
|
| 67 | }
|
| 68 |
|
| 69 | ptr.cast::<MaybeUninit<T>>()
|
| 70 | };
|
| 71 |
|
| 72 | |
| 73 | |
| 74 | Ok(unsafe { Box::from_raw(ptr) })
|
| 75 | }
|
| 76 |
|
| 77 | fn drop_contents(this: Self) -> Box<MaybeUninit<T>> {
|
| 78 | let ptr = Box::into_raw(this);
|
| 79 | |
| 80 | unsafe { ptr::drop_in_place(ptr) };
|
| 81 |
|
| 82 | |
| 83 | let ptr = ptr.cast::<MaybeUninit<T>>();
|
| 84 |
|
| 85 | |
| 86 | |
| 87 | unsafe { Box::from_raw(ptr) }
|
| 88 | }
|
| 89 | }
|