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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
//! A pointer type for heap allocation. //! //! [`Box<T, B>`], casually referred to as a 'box', provides the simplest form of allocation in //! Rust. Boxes provide ownership for this allocation, and drop their contents when they go out of //! scope. //! //! # Examples //! //! Move a value from the stack to the heap by creating a [`Box`]: //! //! ``` //! use alloc_wg::boxed::Box; //! //! let val: u8 = 5; //! # #[allow(unused_variables)] //! let boxed: Box<u8> = Box::new(val); //! ``` //! //! Move a value from a [`Box`] back to the stack by [dereferencing]: //! //! ``` //! use alloc_wg::boxed::Box; //! //! let boxed: Box<u8> = Box::new(5); //! # #[allow(unused_variables)] //! let val: u8 = *boxed; //! ``` //! //! Creating a recursive data structure: //! //! ``` //! use alloc_wg::boxed::Box; //! //! #[derive(Debug)] //! enum List<T> { //! Cons(T, Box<List<T>>), //! Nil, //! } //! //! fn main() { //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); //! println!("{:?}", list); //! } //! ``` //! //! This will print `Cons(1, Cons(2, Nil))`. //! //! Recursive structures must be boxed, because if the definition of `Cons` //! looked like this: //! //! ```compile_fail,E0072 //! # enum List<T> { //! Cons(T, List<T>), //! # } //! ``` //! //! It wouldn't work. This is because the size of a `List` depends on how many elements are in the //! list, and so we don't know how much memory to allocate for a `Cons`. By introducing a [`Box<T, //! D>`], which has a defined size, we know how big `Cons` needs to be. //! //! # Memory layout //! //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for its allocation if no //! allocator was specified. It is valid to convert both ways between a [`Box`] and a raw pointer //! allocated with the same allocator, given that the [`Layout`] used with the allocator is //! correct for the type. More precisely, a `value: *mut T` that has been allocated with the //! [`Global`] allocator with `Layout::for_value(&*value)` may be converted into a box using //! [`Box::<T>::from_raw(value)`]. For other allocators, [`Box::<T>::from_raw_in(value, alloc)`] may //! be used. Conversely, the memory backing a `value: *mut T` obtained from [`Box::<T>::into_raw`] //! may be deallocated using the specific allocator with [`Layout::for_value(&*value)`]. //! //! //! [dereferencing]: core::ops::Deref //! [`Box`]: crate::boxed::Box //! [`Box<T>`]: crate::boxed::Box //! [`Box::<T>::from_raw(value)`]: crate::boxed::Box::from_raw //! [`Box::<T>::from_raw(value, alloc)`]: crate::boxed::Box::from_raw_in //! [`Box::<T>::into_raw`]: crate::boxed::Box::into_raw //! [`Global`]: crate::alloc::Global //! [`Layout`]: crate::alloc::Layout //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value use crate::{ alloc::{AbortAlloc, AllocRef, BuildAlloc, BuildDealloc, DeallocRef, Global, NonZeroLayout}, UncheckedResultExt, }; use core::{ alloc::Layout, fmt, marker::PhantomData, mem, ops::{Deref, DerefMut}, pin::Pin, ptr::NonNull, slice, }; /// A pointer type for heap allocation. /// /// See the [module-level documentation](index.html) for more. // Using `NonNull` + `PhantomData` instead of `Unique` to stay on stable as long as possible pub struct Box<T: ?Sized, B: BuildDealloc = AbortAlloc<Global>>(NonNull<T>, B, PhantomData<T>); #[allow(clippy::use_self)] impl<T> Box<T> { /// Allocates memory on the heap and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Example /// /// ``` /// use alloc_wg::boxed::Box; /// /// # #[allow(unused_variables)] /// let five = Box::new(5); /// ``` pub fn new(x: T) -> Self { Self::new_in(x, AbortAlloc(Global)) } /// Constructs a new box with uninitialized contents. /// /// # Example /// /// ``` /// use alloc_wg::boxed::Box; /// /// let mut five = Box::<u32>::new_uninit(); /// /// let five = unsafe { /// // Deferred initialization: /// five.as_mut_ptr().write(5); /// /// five.assume_init() /// }; /// /// assert_eq!(*five, 5) /// ``` pub fn new_uninit() -> Box<mem::MaybeUninit<T>> { Self::new_uninit_in(AbortAlloc(Global)) } /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then /// `x` will be pinned in memory and unable to be moved. #[inline(always)] pub fn pin(x: T) -> Pin<Self> { Self::new(x).into() } } #[allow(clippy::use_self)] impl<T, B: BuildDealloc> Box<T, B> where B: BuildAlloc, { /// Allocates memory with the given allocator and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Example /// /// ``` /// use alloc_wg::{ /// alloc::{AbortAlloc, Global}, /// boxed::Box, /// }; /// /// # #[allow(unused_variables)] /// let five: Box<_, AbortAlloc<Global>> = Box::new_in(5, AbortAlloc(Global)); /// ``` pub fn new_in(x: T, a: B::AllocRef) -> Self where B::AllocRef: AllocRef<Error = crate::Never>, { unsafe { Self::try_new_in(x, a).unwrap_unchecked() } } /// Tries to allocate memory with the given allocator and then places `x` into it. /// /// This doesn't actually allocate if `T` is zero-sized. /// /// # Example /// /// ``` /// use alloc_wg::{alloc::Global, boxed::Box}; /// /// # #[allow(unused_variables)] /// let five: Box<_, Global> = Box::try_new_in(5, Global)?; /// # Ok::<_, alloc_wg::alloc::AllocErr>(()) /// ``` pub fn try_new_in(x: T, mut a: B::AllocRef) -> Result<Self, <B::AllocRef as AllocRef>::Error> { let ptr = if let Ok(layout) = NonZeroLayout::new::<T>() { let ptr = a.alloc(layout)?.cast::<T>(); unsafe { ptr.as_ptr().write(x); } ptr } else { NonNull::dangling() }; Ok(Self(ptr, a.get_build_alloc(), PhantomData)) } /// Constructs a new box with uninitialized contents in a specified allocator. /// /// # Example /// /// ``` /// use alloc_wg::{ /// alloc::{AbortAlloc, Global}, /// boxed::Box, /// }; /// /// let mut five = Box::<u32, AbortAlloc<Global>>::new_uninit_in(AbortAlloc(Global)); /// /// let five = unsafe { /// // Deferred initialization: /// five.as_mut_ptr().write(5); /// /// five.assume_init() /// }; /// /// assert_eq!(*five, 5) /// ``` pub fn new_uninit_in(a: B::AllocRef) -> Box<mem::MaybeUninit<T>, B> where B::AllocRef: AllocRef<Error = crate::Never>, { unsafe { Self::try_new_uninit_in(a).unwrap_unchecked() } } /// Tries to construct a new box with uninitialized contents in a specified allocator. /// /// # Example /// /// ``` /// use alloc_wg::{alloc::Global, boxed::Box}; /// /// let mut five = Box::<u32, Global>::try_new_uninit_in(Global)?; /// /// let five = unsafe { /// // Deferred initialization: /// five.as_mut_ptr().write(5); /// /// five.assume_init() /// }; /// /// assert_eq!(*five, 5); /// # Ok::<_, alloc_wg::alloc::AllocErr>(()) /// ``` pub fn try_new_uninit_in( mut a: B::AllocRef, ) -> Result<Box<mem::MaybeUninit<T>, B>, <B::AllocRef as AllocRef>::Error> { let ptr = if let Ok(layout) = NonZeroLayout::new::<T>() { let ptr: NonNull<T> = a.alloc(layout)?.cast(); ptr } else { NonNull::dangling() }; Ok(Self(ptr.cast(), a.get_build_alloc(), PhantomData)) } /// Constructs a new `Pin<Box<T, A>>` with the specified allocator. If `T` does not implement /// `Unpin`, then `x` will be pinned in memory and unable to be moved. #[inline(always)] pub fn pin_in(x: T, a: B::AllocRef) -> Pin<Self> where B::AllocRef: AllocRef<Error = crate::Never>, { unsafe { Self::try_pin_in(x, a).unwrap_unchecked() } } /// Constructs a new `Pin<Box<T, A>>` with the specified allocator. If `T` does not implement /// `Unpin`, then `x` will be pinned in memory and unable to be moved. #[inline(always)] pub fn try_pin_in(x: T, a: B::AllocRef) -> Result<Pin<Self>, <B::AllocRef as AllocRef>::Error> { Self::try_new_in(x, a).map(Pin::from) } } #[allow(clippy::use_self)] impl<T> Box<[T]> { /// Construct a new boxed slice with uninitialized contents. /// /// # Example /// /// ``` /// use alloc_wg::boxed::Box; /// /// let mut values = Box::<[u32]>::new_uninit_slice(3); /// /// let values = unsafe { /// // Deferred initialization: /// values[0].as_mut_ptr().write(1); /// values[1].as_mut_ptr().write(2); /// values[2].as_mut_ptr().write(3); /// /// values.assume_init() /// }; /// /// assert_eq!(*values, [1, 2, 3]); /// ``` pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> { Self::new_uninit_slice_in(len, AbortAlloc(Global)) } } #[allow(clippy::use_self)] impl<T, B: BuildDealloc> Box<[T], B> where B: BuildAlloc, B::AllocRef: AllocRef<Error = crate::Never>, { /// Construct a new boxed slice with uninitialized contents with the spoecified allocator. /// /// # Example /// /// ``` /// use alloc_wg::{ /// alloc::{AbortAlloc, Global}, /// boxed::Box, /// }; /// /// let mut values = Box::<[u32], AbortAlloc<Global>>::new_uninit_slice_in(3, AbortAlloc(Global)); /// /// let values = unsafe { /// // Deferred initialization: /// values[0].as_mut_ptr().write(1); /// values[1].as_mut_ptr().write(2); /// values[2].as_mut_ptr().write(3); /// /// values.assume_init() /// }; /// /// assert_eq!(*values, [1, 2, 3]); /// ``` pub fn new_uninit_slice_in(len: usize, a: B::AllocRef) -> Box<[mem::MaybeUninit<T>], B> { unsafe { Self::try_new_uninit_slice_in(len, a).unwrap_unchecked() } } } #[allow(clippy::use_self)] impl<T, B: BuildDealloc> Box<[T], B> where B: BuildAlloc, { /// Tries to construct a new boxed slice with uninitialized contents with the spoecified /// allocator. /// /// # Example /// /// ``` /// use alloc_wg::{alloc::Global, boxed::Box}; /// /// let mut values = Box::<[u32], Global>::try_new_uninit_slice_in(3, Global)?; /// /// let values = unsafe { /// // Deferred initialization: /// values[0].as_mut_ptr().write(1); /// values[1].as_mut_ptr().write(2); /// values[2].as_mut_ptr().write(3); /// /// values.assume_init() /// }; /// /// assert_eq!(*values, [1, 2, 3]); /// # Ok::<_, alloc_wg::alloc::AllocErr>(()) /// ``` #[allow(clippy::type_complexity)] pub fn try_new_uninit_slice_in( len: usize, mut a: B::AllocRef, ) -> Result<Box<[mem::MaybeUninit<T>], B>, <B::AllocRef as AllocRef>::Error> { let ptr = if mem::size_of::<T>() == 0 || len == 0 { NonNull::dangling() } else { let layout = NonZeroLayout::array::<mem::MaybeUninit<T>>(len).expect("capacity overflow"); a.alloc(layout)? }; unsafe { let slice = slice::from_raw_parts_mut(ptr.cast().as_ptr(), len); Ok(Self(NonNull::from(slice), a.get_build_alloc(), PhantomData)) } } } #[allow(clippy::use_self)] impl<T, B: BuildDealloc> Box<mem::MaybeUninit<T>, B> { /// Converts to `Box<T, B>`. /// /// # Safety /// /// As with [`MaybeUninit::assume_init`], /// it is up to the caller to guarantee that the value /// really is in an initialized state. /// Calling this when the content is not yet fully initialized /// causes immediate undefined behavior. /// /// [`MaybeUninit::assume_init`]: core::mem::MaybeUninit::assume_init /// /// # Example /// /// ``` /// use alloc_wg::boxed::Box; /// /// let mut five = Box::<u32>::new_uninit(); /// /// let five = unsafe { /// // Deferred initialization: /// five.as_mut_ptr().write(5); /// /// five.assume_init() /// }; /// /// assert_eq!(*five, 5) /// ``` #[inline] pub unsafe fn assume_init(mut self) -> Box<T, B> { let a = self.get_alloc(); let ptr = Self::into_raw(self); Box::from_raw_in(ptr as _, a) } } #[allow(clippy::use_self)] impl<T, B: BuildDealloc> Box<[mem::MaybeUninit<T>], B> { /// Converts to `Box<[T], B>`. /// /// # Safety /// /// As with [`MaybeUninit::assume_init`], /// it is up to the caller to guarantee that the values /// really are in an initialized state. /// Calling this when the content is not yet fully initialized /// causes immediate undefined behavior. /// /// [`MaybeUninit::assume_init`]: core::mem::MaybeUninit::assume_init /// /// # Example /// /// ``` /// use alloc_wg::boxed::Box; /// /// let mut values = Box::<[u32]>::new_uninit_slice(3); /// /// let values = unsafe { /// // Deferred initialization: /// values[0].as_mut_ptr().write(1); /// values[1].as_mut_ptr().write(2); /// values[2].as_mut_ptr().write(3); /// /// values.assume_init() /// }; /// /// assert_eq!(*values, [1, 2, 3]) /// ``` #[inline] pub unsafe fn assume_init(mut self) -> Box<[T], B> { let a = self.get_alloc(); let ptr = Self::into_raw(self); Box::from_raw_in(ptr as _, a) } } impl<T: ?Sized> Box<T> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the resulting `Box`.2 Specifically, /// the `Box` destructor will call the destructor of `T` and free the allocated memory. For /// this to be safe, the memory must have been allocated in accordance /// with the [memory layout] used by `Box` . /// /// # Safety /// /// This function is unsafe because improper use may lead to memory problems. For example, a /// double-free may occur if the function is called twice on the same raw pointer. /// /// # Examples /// /// Recreate a `Box` which was previously converted to a raw pointer using [`Box::into_raw`][]: /// ``` /// use alloc_wg::boxed::Box; /// /// let x = Box::new(5); /// let ptr = Box::into_raw(x); /// # #[allow(unused_variables)] /// let x = unsafe { Box::from_raw(ptr) }; /// ``` /// Manually create a `Box` from scratch by using the global allocator: /// ``` /// use alloc_wg::{ /// alloc::{alloc, Layout}, /// boxed::Box, /// }; /// /// unsafe { /// let ptr = alloc(Layout::new::<i32>()) as *mut i32; /// *ptr = 5; /// # #[allow(unused_variables)] /// let x = Box::from_raw(ptr); /// } /// ``` /// /// [memory layout]: index.html#memory-layout pub unsafe fn from_raw(raw: *mut T) -> Self { Self::from_raw_in(raw, AbortAlloc(Global)) } } impl<T: ?Sized, B: BuildDealloc> Box<T, B> { /// Constructs a box from a raw pointer. /// /// After calling this function, the raw pointer is owned by the resulting `Box`. Specifically, /// the `Box` destructor will call the destructor of `T` and free the allocated memory. For /// this to be safe, the memory must have been allocated in accordance /// with the [memory layout] used by `Box` . /// /// # Safety /// /// This function is unsafe because improper use may lead to memory problems. For example, a /// double-free may occur if the function is called twice on the same raw pointer. /// /// # Example /// /// Manually create a `Box` from scratch by using the global allocator: /// ``` /// use alloc_wg::{ /// alloc::{alloc, Global, Layout}, /// boxed::Box, /// }; /// /// unsafe { /// let ptr = alloc(Layout::new::<i32>()) as *mut i32; /// *ptr = 5; /// # #[allow(unused_variables)] /// let x: Box<_, Global> = Box::from_raw_in(ptr, Global); /// } /// ``` #[inline] pub unsafe fn from_raw_in(raw: *mut T, mut d: B::DeallocRef) -> Self { Self( NonNull::new_unchecked(raw), d.get_build_dealloc(), PhantomData, ) } pub fn get_alloc(&mut self) -> B::DeallocRef { unsafe { self.1 .build_dealloc_ref(self.0.cast(), Layout::for_value(self.as_ref())) } } /// Consumes the `Box`, returning a wrapped raw pointer. /// /// The pointer will be properly aligned and non-null. /// /// After calling this function, the caller is responsible for the memory previously managed by /// the `Box`. In particular, the caller should properly destroy `T` and release the memory, /// taking into account the [memory layout] used by `Box`. The easiest way to do this is to /// convert the raw pointer back into a `Box` with the [`Box::from_raw`][] function, /// allowing the `Box` destructor to perform the cleanup. /// /// Note: this is an associated function, which means that you have to call it as /// `Box::into_raw(b)` instead of `b.into_raw()`. This is so that there is no conflict with /// a method on the inner type. /// /// # Examples /// Converting the raw pointer back into a `Box` with [`Box::from_raw`][] for automatic cleanup: /// ``` /// use alloc_wg::boxed::Box; /// /// let x = Box::new(String::from("Hello")); /// let ptr = Box::into_raw(x); /// # #[allow(unused_variables)] /// let x = unsafe { Box::from_raw(ptr) }; /// ``` /// Manual cleanup by explicitly running the destructor and deallocating /// the memory: /// ``` /// use alloc_wg::{ /// alloc::{dealloc, Layout}, /// boxed::Box, /// }; /// use core::ptr; /// /// let x = Box::new(String::from("Hello")); /// let p = Box::into_raw(x); /// unsafe { /// ptr::drop_in_place(p); /// dealloc(p as *mut u8, Layout::new::<String>()); /// } /// ``` /// /// [memory layout]: index.html#memory-layout #[inline] pub fn into_raw(b: Self) -> *mut T { Self::into_raw_non_null(b).as_ptr() } /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. /// /// After calling this function, the caller is responsible for the memory previously managed by /// the `Box`. In particular, the caller should properly destroy `T` and release the memory. /// The easiest way to do so is to convert the `NonNull<T>` pointer /// into a raw pointer and back into a `Box` with the [`Box::from_raw`][] /// function. /// /// Note: this is an associated function, which means that you have to call it as /// `Box::into_raw_non_null(b)` instead of `b.into_raw_non_null()`. This is so that there is no /// conflict with a method on the inner type. /// /// # Examples /// /// ``` /// use alloc_wg::boxed::Box; /// /// let x = Box::new(5); /// let ptr = Box::into_raw_non_null(x); /// /// // Clean up the memory by converting the NonNull pointer back /// // into a Box and letting the Box be dropped. /// # #[allow(unused_variables)] /// let x = unsafe { Box::from_raw(ptr.as_ptr()) }; /// ``` #[inline] pub fn into_raw_non_null(b: Self) -> NonNull<T> { // TODO: Replace with `Self::into_unique(b).into()` let mut ptr = b.0; mem::forget(b); unsafe { NonNull::new_unchecked(ptr.as_mut()) } } // TODO: Uncomment this when changing `NonNull` to `Unique` // #[inline] // #[doc(hidden)] // pub fn into_unique(b: Self) -> Unique<T> { // let mut unique = b.0; // mem::forget(b); // // // Box is kind-of a library type, but recognized as a "unique pointer" by // // Stacked Borrows. This function here corresponds to "reborrowing to // // a raw pointer", but there is no actual reborrow here -- so // // without some care, the pointer we are returning here still carries // // the tag of `b`, with `Unique` permission. // // We round-trip through a mutable reference to avoid that. // unsafe { Unique::new_unchecked(unique.as_mut()) } // } /// Consumes and leaks the `Box`, returning a mutable reference, /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime /// `'a`. If the type has only static references, or none at all, then this /// may be chosen to be `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory /// leak. If this is not acceptable, the reference should first be wrapped /// with the [`Box::from_raw`][] function producing a `Box`. This `Box` can /// then be dropped which will properly destroy `T` and release the /// allocated memory. /// /// Note: this is an associated function, which means that you have /// to call it as `Box::leak(b)` instead of `b.leak()`. This /// is so that there is no conflict with a method on the inner type. /// /// # Examples /// /// Simple usage: /// /// ``` /// use alloc_wg::boxed::Box; /// /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x); /// *static_ref += 1; /// assert_eq!(*static_ref, 42); /// ``` // TODO: Example for unsized data #[inline] pub fn leak<'a>(b: Self) -> &'a mut T where T: 'a, // Technically not needed, but kept to be explicit. { unsafe { &mut *Self::into_raw(b) } } /// Converts a `Box<T, B>` into a `Pin<Box<T, B>>` /// /// This conversion does not allocate and happens in place. /// /// This is also available via [`From`][]. pub fn into_pin(boxed: Self) -> Pin<Self> { // It's not possible to move or replace the insides of a `Pin<Box<T>>` // when `T: !Unpin`, so it's safe to pin it directly without any // additional requirements. unsafe { Pin::new_unchecked(boxed) } } } impl<T: ?Sized, B: BuildDealloc> Deref for Box<T, B> { type Target = T; fn deref(&self) -> &T { unsafe { self.0.as_ref() } } } impl<T: ?Sized, B: BuildDealloc> DerefMut for Box<T, B> { fn deref_mut(&mut self) -> &mut T { unsafe { self.0.as_mut() } } } impl<T: ?Sized, B: BuildDealloc> From<Box<T, B>> for Pin<Box<T, B>> { /// Converts a `Box<T, B>` into a `Pin<Box<T, B>>` /// /// This conversion does not allocate on the heap and happens in place. fn from(boxed: Box<T, B>) -> Self { Box::into_pin(boxed) } } impl<T: fmt::Display + ?Sized, B: BuildDealloc> fmt::Display for Box<T, B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl<T: fmt::Debug + ?Sized, B: BuildDealloc> fmt::Debug for Box<T, B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl<T: ?Sized, B: BuildDealloc> AsRef<T> for Box<T, B> { fn as_ref(&self) -> &T { &**self } } impl<T: ?Sized, B: BuildDealloc> AsMut<T> for Box<T, B> { fn as_mut(&mut self) -> &mut T { &mut **self } } #[cfg(feature = "dropck_eyepatch")] unsafe impl<#[may_dangle] T: ?Sized, B: BuildDealloc> Drop for Box<T, B> { fn drop(&mut self) { unsafe { self.get_alloc().dealloc( self.0.cast(), NonZeroLayout::for_value_unchecked(self.0.as_ref()), ) } } } #[cfg(not(feature = "dropck_eyepatch"))] impl<T: ?Sized, B: BuildDealloc> Drop for Box<T, B> { fn drop(&mut self) { unsafe { self.get_alloc().dealloc( self.0.cast(), NonZeroLayout::for_value_unchecked(self.0.as_ref()), ) } } }