1use core::error::Error;
6use core::fmt::{self, Debug, Display, Formatter};
7#[cfg(not(no_global_oom_handling))]
8use core::intrinsics::{const_allocate, const_make_global};
9use core::marker::PhantomData;
10#[cfg(not(no_global_oom_handling))]
11use core::marker::Unsize;
12#[cfg(not(no_global_oom_handling))]
13use core::mem;
14use core::mem::SizedTypeProperties;
15use core::ops::{Deref, DerefMut};
16use core::ptr::{self, NonNull, Pointee};
17
18use crate::alloc::{self, Layout, LayoutError};
19
20#[unstable(feature = "thin_box", issue = "92791")]
38pub struct ThinBox<T: ?Sized> {
39 ptr: WithOpaqueHeader,
42 _marker: PhantomData<T>,
43}
44
45#[unstable(feature = "thin_box", issue = "92791")]
47unsafe impl<T: ?Sized + Send> Send for ThinBox<T> {}
48
49#[unstable(feature = "thin_box", issue = "92791")]
51unsafe impl<T: ?Sized + Sync> Sync for ThinBox<T> {}
52
53#[unstable(feature = "thin_box", issue = "92791")]
54impl<T> ThinBox<T> {
55 #[cfg(not(no_global_oom_handling))]
69 pub fn new(value: T) -> Self {
70 let meta = ptr::metadata(&value);
71 let ptr = WithOpaqueHeader::new(meta, value);
72 ThinBox { ptr, _marker: PhantomData }
73 }
74
75 pub fn try_new(value: T) -> Result<Self, core::alloc::AllocError> {
90 let meta = ptr::metadata(&value);
91 WithOpaqueHeader::try_new(meta, value).map(|ptr| ThinBox { ptr, _marker: PhantomData })
92 }
93}
94
95#[unstable(feature = "thin_box", issue = "92791")]
96impl<Dyn: ?Sized> ThinBox<Dyn> {
97 #[cfg(not(no_global_oom_handling))]
111 pub fn new_unsize<T>(value: T) -> Self
112 where
113 T: Unsize<Dyn>,
114 {
115 if T::IS_ZST {
116 let ptr = WithOpaqueHeader::new_unsize_zst::<Dyn, T>(value);
117 ThinBox { ptr, _marker: PhantomData }
118 } else {
119 let meta = ptr::metadata(&value as &Dyn);
120 let ptr = WithOpaqueHeader::new(meta, value);
121 ThinBox { ptr, _marker: PhantomData }
122 }
123 }
124}
125
126#[unstable(feature = "thin_box", issue = "92791")]
127impl<T: ?Sized + Debug> Debug for ThinBox<T> {
128 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
129 Debug::fmt(self.deref(), f)
130 }
131}
132
133#[unstable(feature = "thin_box", issue = "92791")]
134impl<T: ?Sized + Display> Display for ThinBox<T> {
135 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
136 Display::fmt(self.deref(), f)
137 }
138}
139
140#[unstable(feature = "thin_box", issue = "92791")]
141impl<T: ?Sized> Deref for ThinBox<T> {
142 type Target = T;
143
144 fn deref(&self) -> &T {
145 let value = self.data();
146 let metadata = self.meta();
147 let pointer = ptr::from_raw_parts(value as *const (), metadata);
148 unsafe { &*pointer }
150 }
151}
152
153#[unstable(feature = "thin_box", issue = "92791")]
154impl<T: ?Sized> DerefMut for ThinBox<T> {
155 fn deref_mut(&mut self) -> &mut T {
156 let value = self.data();
157 let metadata = self.meta();
158 let pointer = ptr::from_raw_parts_mut::<T>(value as *mut (), metadata);
159 unsafe { &mut *pointer }
161 }
162}
163
164#[unstable(feature = "thin_box", issue = "92791")]
165impl<T: ?Sized> Drop for ThinBox<T> {
166 fn drop(&mut self) {
167 let value = self.deref_mut();
168 let value = value as *mut T;
169 unsafe {
171 self.with_header().drop::<T>(value);
172 }
173 }
174}
175
176#[unstable(feature = "thin_box", issue = "92791")]
177impl<T: ?Sized> ThinBox<T> {
178 fn meta(&self) -> <T as Pointee>::Metadata {
179 unsafe { *self.with_header().header() }
181 }
182
183 fn data(&self) -> *mut u8 {
184 self.with_header().value()
185 }
186
187 fn with_header(&self) -> &WithHeader<<T as Pointee>::Metadata> {
188 unsafe { &*((&raw const self.ptr) as *const WithHeader<_>) }
190 }
191}
192
193#[repr(transparent)]
199struct WithHeader<H>(NonNull<u8>, PhantomData<H>);
200
201#[repr(transparent)]
204struct WithOpaqueHeader(NonNull<u8>);
205
206impl WithOpaqueHeader {
207 #[cfg(not(no_global_oom_handling))]
208 fn new<H, T>(header: H, value: T) -> Self {
209 let ptr = WithHeader::new(header, value);
210 Self(ptr.0)
211 }
212
213 #[cfg(not(no_global_oom_handling))]
214 fn new_unsize_zst<Dyn, T>(value: T) -> Self
215 where
216 Dyn: ?Sized,
217 T: Unsize<Dyn>,
218 {
219 let ptr = WithHeader::<<Dyn as Pointee>::Metadata>::new_unsize_zst::<Dyn, T>(value);
220 Self(ptr.0)
221 }
222
223 fn try_new<H, T>(header: H, value: T) -> Result<Self, core::alloc::AllocError> {
224 WithHeader::try_new(header, value).map(|ptr| Self(ptr.0))
225 }
226}
227
228impl<H> WithHeader<H> {
229 #[cfg(not(no_global_oom_handling))]
230 fn new<T>(header: H, value: T) -> WithHeader<H> {
231 let value_layout = Layout::new::<T>();
232 let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
233 alloc::handle_alloc_error(Layout::new::<()>());
240 };
241
242 let ptr = if layout.size() == 0 {
246 debug_assert!(value_offset == 0 && T::IS_ZST && H::IS_ZST);
249 layout.dangling_ptr()
250 } else {
251 let ptr = unsafe { alloc::alloc(layout) };
253 if ptr.is_null() {
254 alloc::handle_alloc_error(layout);
255 }
256 unsafe {
259 let ptr = ptr.add(value_offset) as *mut _;
260
261 NonNull::new_unchecked(ptr)
262 }
263 };
264
265 let result = WithHeader(ptr, PhantomData);
266
267 unsafe {
270 ptr::write(result.header(), header);
271 ptr::write(result.value().cast(), value);
272 }
273
274 result
275 }
276
277 fn try_new<T>(header: H, value: T) -> Result<WithHeader<H>, core::alloc::AllocError> {
280 let value_layout = Layout::new::<T>();
281 let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
282 return Err(core::alloc::AllocError);
283 };
284
285 let ptr = if layout.size() == 0 {
289 debug_assert!(value_offset == 0 && T::IS_ZST && H::IS_ZST);
292 layout.dangling_ptr()
293 } else {
294 let ptr = unsafe { alloc::alloc(layout) };
296 if ptr.is_null() {
297 return Err(core::alloc::AllocError);
298 }
299
300 unsafe {
303 let ptr = ptr.add(value_offset) as *mut _;
304
305 NonNull::new_unchecked(ptr)
306 }
307 };
308
309 let result = WithHeader(ptr, PhantomData);
310
311 unsafe {
314 ptr::write(result.header(), header);
315 ptr::write(result.value().cast(), value);
316 }
317
318 Ok(result)
319 }
320
321 #[cfg(not(no_global_oom_handling))]
323 fn new_unsize_zst<Dyn, T>(value: T) -> WithHeader<H>
324 where
325 Dyn: Pointee<Metadata = H> + ?Sized,
326 T: Unsize<Dyn>,
327 {
328 assert!(T::IS_ZST);
329
330 const fn max(a: usize, b: usize) -> usize {
331 if a > b { a } else { b }
332 }
333
334 let alloc: &<Dyn as Pointee>::Metadata = const {
339 let alloc_align = max(align_of::<T>(), align_of::<<Dyn as Pointee>::Metadata>());
343
344 let alloc_size = max(align_of::<T>(), size_of::<<Dyn as Pointee>::Metadata>());
345
346 let alloc: *mut u8 = unsafe { const_allocate(alloc_size, alloc_align) };
348
349 let metadata_offset =
350 alloc_size.checked_sub(size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
351 let metadata_ptr: *mut <Dyn as Pointee>::Metadata =
352 unsafe { alloc.add(metadata_offset).cast() };
354 unsafe {
356 metadata_ptr.write(ptr::metadata::<Dyn>(ptr::dangling::<T>() as *const Dyn));
357 }
358 unsafe { const_make_global(alloc) };
360 unsafe { &*metadata_ptr }
362 };
363
364 let value_ptr =
365 unsafe { (alloc as *const <Dyn as Pointee>::Metadata).add(1) }.cast::<T>().cast_mut();
367 debug_assert!(value_ptr.is_aligned());
368 mem::forget(value);
369 WithHeader(NonNull::new(value_ptr.cast()).unwrap(), PhantomData)
370 }
371
372 unsafe fn drop<T: ?Sized>(&self, value: *mut T) {
377 struct DropGuard<H> {
378 ptr: NonNull<u8>,
379 value_layout: Layout,
380 _marker: PhantomData<H>,
381 }
382
383 impl<H> Drop for DropGuard<H> {
384 fn drop(&mut self) {
385 if self.value_layout.size() == 0 {
387 return;
388 }
389
390 let (layout, value_offset) =
391 unsafe { WithHeader::<H>::alloc_layout(self.value_layout).unwrap_unchecked() };
393
394 debug_assert!(layout.size() != 0);
396 unsafe { alloc::dealloc(self.ptr.as_ptr().sub(value_offset), layout) };
398 }
399 }
400
401 let _guard = DropGuard {
403 ptr: self.0,
404 value_layout: unsafe { Layout::for_value_raw(value) },
406 _marker: PhantomData::<H>,
407 };
408
409 unsafe { ptr::drop_in_place::<T>(value) };
413 }
414
415 fn header(&self) -> *mut H {
416 let hp = unsafe { self.0.as_ptr().sub(Self::header_size()) as *mut H };
424 debug_assert!(hp.is_aligned());
425 hp
426 }
427
428 fn value(&self) -> *mut u8 {
429 self.0.as_ptr()
430 }
431
432 const fn header_size() -> usize {
433 size_of::<H>()
434 }
435
436 fn alloc_layout(value_layout: Layout) -> Result<(Layout, usize), LayoutError> {
437 Layout::new::<H>().extend(value_layout)
438 }
439}
440
441#[unstable(feature = "thin_box", issue = "92791")]
442impl<T: ?Sized + Error> Error for ThinBox<T> {
443 fn source(&self) -> Option<&(dyn Error + 'static)> {
444 self.deref().source()
445 }
446}
447
448#[cfg(not(no_global_oom_handling))]
449#[unstable(feature = "thin_box", issue = "92791")]
450impl<T> From<T> for ThinBox<T> {
451 #[inline(always)]
452 fn from(value: T) -> Self {
453 Self::new(value)
454 }
455}