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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use crate::{Storage, StorageAllocError, global_storage::Global};
use cfg_if::cfg_if;
use core::{
alloc::Layout,
marker::PhantomData,
mem::ManuallyDrop,
ops::{Deref, DerefMut},
ptr::NonNull,
};
cfg_if! {
if #[cfg(feature = "nightly")] {
/// A type that owns a single `T` allocated in a [`Storage`]
///
/// This currently stores an extra dangling non-null pointer when using the `nightly` feature,
/// so that [`CoerceUnsized`](core::ops::CoerceUnsized) can attach metadata to it when this [`Box`] get unsized
///
/// [`Box`] does not support `T: ?Sized` types when not using the `nightly` feature
pub struct Box<T: ?Sized, S: Storage = Global> {
handle: S::Handle,
storage: S,
/// for storing metadata in a way that is compatible with [`CoerceUnsized`], this is an extra pointer but whatever :/
metadata_ptr: NonNull<T>,
_data: PhantomData<T>,
}
} else {
/// A type that owns a single `T` allocated in a [`Storage`]
pub struct Box<T, S: Storage = Global> {
handle: S::Handle,
storage: S,
_data: PhantomData<T>,
}
}
}
cfg_if! {
if #[cfg(feature = "nightly")] {
macro_rules! impl_maybe_unsized_methods {
(impl $($trait:path)? $(where [$($where:tt)*])? { $($tokens:tt)* }) => {
impl<T: ?Sized, S: Storage> $($trait for )? Box<T, S> $(where $($where)*)? { $($tokens)* }
};
(unsafe impl $($trait:path)? $(where [$($where:tt)*])? { $($tokens:tt)* }) => {
unsafe impl<T: ?Sized, S: Storage> $($trait for )? Box<T, S> $(where $($where)*)? { $($tokens)* }
};
}
} else {
macro_rules! impl_maybe_unsized_methods {
(impl $($trait:path)? $(where [$($where:tt)*])? { $($tokens:tt)* }) => {
impl<T, S: Storage> $($trait for )? Box<T, S> $(where $($where)*)? { $($tokens)* }
};
(unsafe impl $($trait:path)? $(where [$($where:tt)*])? { $($tokens:tt)* }) => {
unsafe impl<T, S: Storage> $($trait for )? Box<T, S> $(where $($where)*)? { $($tokens)* }
};
}
}
}
impl_maybe_unsized_methods! {
unsafe impl Send
where
[
T: Send,
S: Send,
S::Handle: Send,
] {}
}
impl_maybe_unsized_methods! {
unsafe impl Sync
where
[
T: Sync,
S: Sync,
S::Handle: Sync,
] {}
}
impl<T, S: Storage + Default> Box<T, S> {
/// [`Box::new_in`] but using [`Default::default`] for the [`Storage`]
pub fn new(value: T) -> Result<Self, StorageAllocError> {
Self::new_in(value, Default::default())
}
/// [`Box::new_with_in`] but using [`Default::default`] for the [`Storage`]
///
/// This function has an advantage over [`Box::new`] for large objects where because the allocation is done *before* `f` is called,
/// the stack space for the return value of `f` may be elided by the compiler
pub fn new_with(f: impl FnOnce() -> T) -> Result<Self, StorageAllocError> {
Self::new_with_in(f, Default::default())
}
}
impl<T, S: Storage> Box<T, S> {
/// Allocates room for a `T` in `storage` and moves `value` into it
pub fn new_in(value: T, storage: S) -> Result<Self, StorageAllocError> {
Self::new_with_in(|| value, storage)
}
/// Allocates room for a `T` in `storage` and constructs `value` into it
///
/// This function has an advantage over [`Box::new_in`] for large objects where because the allocation is done *before* `f` is called,
/// the stack space for the return value of `f` may be elided by the compiler
pub fn new_with_in(f: impl FnOnce() -> T, storage: S) -> Result<Self, StorageAllocError> {
let (handle, _) = storage.allocate(Layout::new::<T>())?;
unsafe {
storage.resolve(handle).cast::<T>().write(f());
Ok(Self::from_raw_parts(storage, handle, ()))
}
}
/// Moves the `T` out of this [`Box`]
pub fn into_inner(self) -> T {
unsafe {
let value = self.as_ptr().read();
let (storage, handle, _) = Self::into_raw_parts(self);
storage.deallocate(Layout::new::<T>(), handle);
value
}
}
}
#[doc(hidden)]
pub trait Pointee {
type Metadata;
}
impl<T: ?Sized> Pointee for T {
cfg_if! {
if #[cfg(feature = "nightly")] {
type Metadata = <T as core::ptr::Pointee>::Metadata;
} else {
type Metadata = ();
}
}
}
impl_maybe_unsized_methods! {
impl {
/// Reconstructs a [`Box`] from a [`Storage`], [`Storage::Handle`], and [`Pointee::Metadata`](core::ptr::Pointee::Metadata)
///
/// The opposite of [`Box::into_raw_parts`]
///
/// # Safety
/// - `handle` must represent a valid allocation in `storage` of `size_of::<T>()` bytes
/// - `metadata` must be a valid pointer metadata for the `T` that `handle` represents
pub unsafe fn from_raw_parts(
storage: S,
handle: S::Handle,
#[allow(unused)]
metadata: <T as Pointee>::Metadata,
) -> Self {
Self {
handle,
storage,
#[cfg(feature = "nightly")]
metadata_ptr: NonNull::from_raw_parts(NonNull::<()>::dangling(), metadata),
_data: PhantomData,
}
}
/// Splits the [`Box`] into its [`Storage`], [`Storage::Handle`], and [`Pointee::Metadata`](core::ptr::Pointee::Metadata)
///
/// The opposite of [`Box::from_raw_parts`]
pub fn into_raw_parts(b: Self) -> (S, S::Handle, <T as Pointee>::Metadata) {
unsafe {
let this = ManuallyDrop::new(b);
(
core::ptr::read(&this.storage),
this.handle,
{
#[cfg(feature = "nightly")]
core::ptr::metadata(this.metadata_ptr.as_ptr())
},
)
}
}
/// Gets a [`NonNull<T>`] to the `T` stored in this [`Box`]
pub fn as_ptr(&self) -> NonNull<T> {
let ptr = unsafe { self.storage.resolve(self.handle) };
cfg_if! {
if #[cfg(feature = "nightly")] {
NonNull::from_raw_parts(ptr, core::ptr::metadata(self.metadata_ptr.as_ptr()))
} else {
ptr.cast()
}
}
}
}
}
cfg_if! {
if #[cfg(feature = "nightly")] {
unsafe impl<#[may_dangle] T: ?Sized, S: Storage> Drop for Box<T, S> {
fn drop(&mut self) {
unsafe {
let ptr = self.as_ptr();
let layout = Layout::for_value_raw(ptr.as_ptr());
ptr.drop_in_place();
self.storage
.deallocate(layout, self.handle);
}
}
}
} else {
impl<T, S: Storage> Drop for Box<T, S> {
fn drop(&mut self) {
unsafe {
let ptr = self.as_ptr();
let layout = Layout::new::<T>();
ptr.drop_in_place();
self.storage
.deallocate(layout, ManuallyDrop::take(&mut self.handle));
}
}
}
}
}
impl_maybe_unsized_methods! {
impl Deref {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { self.as_ptr().as_ref() }
}
}
}
impl_maybe_unsized_methods! {
impl DerefMut {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.as_ptr().as_mut() }
}
}
}
#[cfg(feature = "nightly")]
impl<T, U, S> core::ops::CoerceUnsized<Box<U, S>> for Box<T, S>
where
T: core::marker::Unsize<U> + ?Sized,
U: ?Sized,
S: Storage,
{
}
#[cfg(feature = "nightly")]
impl<S: Storage> Box<dyn core::any::Any, S> {
/// Attempts to downcast the [`dyn Any`](core::any::Any) to a `T`
pub fn downcast<T: 'static>(b: Self) -> Result<Box<T, S>, Self> {
if b.is::<T>() {
Ok(unsafe { Self::downcast_unchecked(b) })
} else {
Err(b)
}
}
/// Downcasts the [`dyn Any`](core::any::Any) to a `T`, without any checks
///
/// The safe version of this function is [`Box::downcast`]
///
/// # Safety
/// The contained value must be of type `T`
pub unsafe fn downcast_unchecked<T: 'static>(b: Self) -> Box<T, S> {
debug_assert!(b.is::<T>());
let (storage, handle, _) = Self::into_raw_parts(b);
unsafe { Box::from_raw_parts(storage, handle, ()) }
}
}