Skip to main content

bumpalo/
boxed.rs

1//! A pointer type for bump allocation.
2//!
3//! [`Box<'a, T>`] provides the simplest form of
4//! bump allocation in `bumpalo`. Boxes provide ownership for this allocation, and
5//! drop their contents when they go out of scope.
6//!
7//! # Examples
8//!
9//! Move a value from the stack to the heap by creating a [`Box`]:
10//!
11//! ```
12//! use bumpalo::{Bump, boxed::Box};
13//!
14//! let b = Bump::new();
15//!
16//! let val: u8 = 5;
17//! let boxed: Box<u8> = Box::new_in(val, &b);
18//! ```
19//!
20//! Move a value from a [`Box`] back to the stack by [dereferencing]:
21//!
22//! ```
23//! use bumpalo::{Bump, boxed::Box};
24//!
25//! let b = Bump::new();
26//!
27//! let boxed: Box<u8> = Box::new_in(5, &b);
28//! let val: u8 = *boxed;
29//! ```
30//!
31//! Running [`Drop`] implementations on bump-allocated values:
32//!
33//! ```
34//! use bumpalo::{Bump, boxed::Box};
35//! use std::sync::atomic::{AtomicUsize, Ordering};
36//!
37//! static NUM_DROPPED: AtomicUsize = AtomicUsize::new(0);
38//!
39//! struct CountDrops;
40//!
41//! impl Drop for CountDrops {
42//!     fn drop(&mut self) {
43//!         NUM_DROPPED.fetch_add(1, Ordering::SeqCst);
44//!     }
45//! }
46//!
47//! // Create a new bump arena.
48//! let bump = Bump::new();
49//!
50//! // Create a `CountDrops` inside the bump arena.
51//! let mut c = Box::new_in(CountDrops, &bump);
52//!
53//! // No `CountDrops` have been dropped yet.
54//! assert_eq!(NUM_DROPPED.load(Ordering::SeqCst), 0);
55//!
56//! // Drop our `Box<CountDrops>`.
57//! drop(c);
58//!
59//! // Its `Drop` implementation was run, and so `NUM_DROPS` has been incremented.
60//! assert_eq!(NUM_DROPPED.load(Ordering::SeqCst), 1);
61//! ```
62//!
63//! Creating a recursive data structure:
64//!
65//! ```
66//! use bumpalo::{Bump, boxed::Box};
67//!
68//! let b = Bump::new();
69//!
70//! #[derive(Debug)]
71//! enum List<'a, T> {
72//!     Cons(T, Box<'a, List<'a, T>>),
73//!     Nil,
74//! }
75//!
76//! let list: List<i32> = List::Cons(1, Box::new_in(List::Cons(2, Box::new_in(List::Nil, &b)), &b));
77//! println!("{:?}", list);
78//! ```
79//!
80//! This will print `Cons(1, Cons(2, Nil))`.
81//!
82//! Recursive structures must be boxed, because if the definition of `Cons`
83//! looked like this:
84//!
85//! ```compile_fail,E0072
86//! # enum List<T> {
87//! Cons(T, List<T>),
88//! # }
89//! ```
90//!
91//! It wouldn't work. This is because the size of a `List` depends on how many
92//! elements are in the list, and so we don't know how much memory to allocate
93//! for a `Cons`. By introducing a [`Box<'a, T>`], which has a defined size, we know how
94//! big `Cons` needs to be.
95//!
96//! # Memory layout
97//!
98//! For non-zero-sized values, a [`Box`] will use the provided [`Bump`] allocator for
99//! its allocation. It is valid to convert both ways between a [`Box`] and a
100//! pointer allocated with the [`Bump`] allocator, given that the
101//! [`Layout`] used with the allocator is correct for the type. More precisely,
102//! a `value: *mut T` that has been allocated with the [`Bump`] allocator
103//! with `Layout::for_value(&*value)` may be converted into a box using
104//! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
105//! T` obtained from [`Box::<T>::into_raw`] will be deallocated by the
106//! [`Bump`] allocator with [`Layout::for_value(&*value)`].
107//!
108//! Note that roundtrip `Box::from_raw(Box::into_raw(b))` looses the lifetime bound to the
109//! [`Bump`] immutable borrow which guarantees that the allocator will not be reset
110//! and memory will not be freed.
111//!
112//! [dereferencing]: https://doc.rust-lang.org/std/ops/trait.Deref.html
113//! [`Box`]: struct.Box.html
114//! [`Box<'a, T>`]: struct.Box.html
115//! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
116//! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
117//! [`Bump`]: ../struct.Bump.html
118//! [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html
119//! [`Layout`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html
120//! [`Layout::for_value(&*value)`]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.for_value
121
122use {
123    crate::Bump,
124    core::{
125        any::Any,
126        borrow,
127        cmp::Ordering,
128        convert::TryFrom,
129        future::Future,
130        hash::{Hash, Hasher},
131        iter::FusedIterator,
132        marker::PhantomData,
133        mem::ManuallyDrop,
134        ops::{Deref, DerefMut},
135        pin::Pin,
136        ptr::NonNull,
137        task::{Context, Poll},
138    },
139    core_alloc::fmt,
140};
141
142/// An owned pointer to a bump-allocated `T` value, that runs `Drop`
143/// implementations.
144///
145/// See the [module-level documentation][crate::boxed] for more details.
146#[repr(transparent)]
147pub struct Box<'a, T: ?Sized>(NonNull<T>, PhantomData<&'a T>);
148
149impl<'a, T> Box<'a, T> {
150    /// Allocates memory on the heap and then places `x` into it.
151    ///
152    /// This doesn't actually allocate if `T` is zero-sized.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use bumpalo::{Bump, boxed::Box};
158    ///
159    /// let b = Bump::new();
160    ///
161    /// let five = Box::new_in(5, &b);
162    /// ```
163    #[inline(always)]
164    pub fn new_in(x: T, a: &'a Bump) -> Box<'a, T> {
165        Box(a.alloc(x).into(), PhantomData)
166    }
167
168    /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
169    /// `x` will be pinned in memory and unable to be moved.
170    #[inline(always)]
171    pub fn pin_in(x: T, a: &'a Bump) -> Pin<Box<'a, T>> {
172        Box(a.alloc(x).into(), PhantomData).into()
173    }
174
175    /// Consumes the `Box`, returning the wrapped value.
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// use bumpalo::{Bump, boxed::Box};
181    ///
182    /// let b = Bump::new();
183    ///
184    /// let hello = Box::new_in("hello".to_owned(), &b);
185    /// assert_eq!(Box::into_inner(hello), "hello");
186    /// ```
187    pub fn into_inner(b: Box<'a, T>) -> T {
188        // `Box::into_raw` returns a pointer that is properly aligned and non-null.
189        // The underlying `Bump` only frees the memory, but won't call the destructor.
190        unsafe { core::ptr::read(Box::into_raw(b)) }
191    }
192}
193
194impl<'a, T: ?Sized> Box<'a, T> {
195    /// Constructs a box from a raw pointer.
196    ///
197    /// After calling this function, the raw pointer is owned by the
198    /// resulting `Box`. Specifically, the `Box` destructor will call
199    /// the destructor of `T` and free the allocated memory. For this
200    /// to be safe, the memory must have been allocated in accordance
201    /// with the memory layout used by `Box` .
202    ///
203    /// # Safety
204    ///
205    /// This function is unsafe because improper use may lead to
206    /// memory problems. For example, a double-free may occur if the
207    /// function is called twice on the same raw pointer.
208    ///
209    /// # Examples
210    ///
211    /// Recreate a `Box` which was previously converted to a raw pointer
212    /// using [`Box::into_raw`]:
213    /// ```
214    /// use bumpalo::{Bump, boxed::Box};
215    ///
216    /// let b = Bump::new();
217    ///
218    /// let x = Box::new_in(5, &b);
219    /// let ptr = Box::into_raw(x);
220    /// let x = unsafe { Box::from_raw(ptr) }; // Note that new `x`'s lifetime is unbound. It must be bound to the `b` immutable borrow before `b` is reset.
221    /// ```
222    /// Manually create a `Box` from scratch by using the bump allocator:
223    /// ```
224    /// use std::alloc::{alloc, Layout};
225    /// use bumpalo::{Bump, boxed::Box};
226    ///
227    /// let b = Bump::new();
228    ///
229    /// unsafe {
230    ///     let ptr = b.alloc_layout(Layout::new::<i32>()).as_ptr() as *mut i32;
231    ///     *ptr = 5;
232    ///     let x = Box::from_raw(ptr); // Note that `x`'s lifetime is unbound. It must be bound to the `b` immutable borrow before `b` is reset.
233    /// }
234    /// ```
235    #[inline]
236    pub unsafe fn from_raw(raw: *mut T) -> Self {
237        // Safety: part of this function's unsafe contract is that the raw
238        // pointer be non-null.
239        Box(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
240    }
241
242    /// Consumes the `Box`, returning a wrapped raw pointer.
243    ///
244    /// The pointer will be properly aligned and non-null.
245    ///
246    /// After calling this function, the caller is responsible for the
247    /// value previously managed by the `Box`. In particular, the
248    /// caller should properly destroy `T`. The easiest way to
249    /// do this is to convert the raw pointer back into a `Box` with the
250    /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
251    /// the cleanup.
252    ///
253    /// Note: this is an associated function, which means that you have
254    /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
255    /// is so that there is no conflict with a method on the inner type.
256    ///
257    /// # Examples
258    ///
259    /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
260    /// for automatic cleanup:
261    /// ```
262    /// use bumpalo::{Bump, boxed::Box};
263    ///
264    /// let b = Bump::new();
265    ///
266    /// let x = Box::new_in(String::from("Hello"), &b);
267    /// let ptr = Box::into_raw(x);
268    /// let x = unsafe { Box::from_raw(ptr) }; // Note that new `x`'s lifetime is unbound. It must be bound to the `b` immutable borrow before `b` is reset.
269    /// ```
270    /// Manual cleanup by explicitly running the destructor:
271    /// ```
272    /// use std::ptr;
273    /// use bumpalo::{Bump, boxed::Box};
274    ///
275    /// let b = Bump::new();
276    ///
277    /// let mut x = Box::new_in(String::from("Hello"), &b);
278    /// let p = Box::into_raw(x);
279    /// unsafe {
280    ///     ptr::drop_in_place(p);
281    /// }
282    /// ```
283    #[inline]
284    pub fn into_raw(b: Box<'a, T>) -> *mut T {
285        let b = ManuallyDrop::new(b);
286        b.0.as_ptr()
287    }
288
289    /// Consumes and leaks the `Box`, returning a mutable reference,
290    /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
291    /// `'a`. If the type has only static references, or none at all, then this
292    /// may be chosen to be `'static`.
293    ///
294    /// This function is mainly useful for data that lives for the remainder of
295    /// the program's life. Dropping the returned reference will cause a memory
296    /// leak. If this is not acceptable, the reference should first be wrapped
297    /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
298    /// then be dropped which will properly destroy `T` and release the
299    /// allocated memory.
300    ///
301    /// Note: this is an associated function, which means that you have
302    /// to call it as `Box::leak(b)` instead of `b.leak()`. This
303    /// is so that there is no conflict with a method on the inner type.
304    ///
305    /// # Examples
306    ///
307    /// Simple usage:
308    ///
309    /// ```
310    /// use bumpalo::{Bump, boxed::Box};
311    ///
312    /// let b = Bump::new();
313    ///
314    /// let x = Box::new_in(41, &b);
315    /// let reference: &mut usize = Box::leak(x);
316    /// *reference += 1;
317    /// assert_eq!(*reference, 42);
318    /// ```
319    ///
320    ///```
321    /// # #[cfg(feature = "collections")]
322    /// # {
323    /// use bumpalo::{Bump, boxed::Box, vec};
324    ///
325    /// let b = Bump::new();
326    ///
327    /// let x = vec![in &b; 1, 2, 3].into_boxed_slice();
328    /// let reference = Box::leak(x);
329    /// reference[0] = 4;
330    /// assert_eq!(*reference, [4, 2, 3]);
331    /// # }
332    ///```
333    #[inline]
334    pub fn leak(b: Box<'a, T>) -> &'a mut T {
335        unsafe { &mut *Box::into_raw(b) }
336    }
337}
338
339impl<'a, T: ?Sized> Drop for Box<'a, T> {
340    fn drop(&mut self) {
341        unsafe {
342            // `Box` owns value of `T`, but not memory behind it.
343            core::ptr::drop_in_place(self.0.as_ptr());
344        }
345    }
346}
347
348impl<'a, T> Default for Box<'a, [T]> {
349    fn default() -> Box<'a, [T]> {
350        // It should be OK to `drop_in_place` empty slice of anything.
351        Box(
352            NonNull::new(&mut []).expect("Reference to empty list is NonNull"),
353            PhantomData,
354        )
355    }
356}
357
358impl<'a> Default for Box<'a, str> {
359    fn default() -> Box<'a, str> {
360        // Empty slice is valid string.
361        // It should be OK to `drop_in_place` empty str.
362        unsafe { Box::from_raw(Box::into_raw(Box::<[u8]>::default()) as *mut str) }
363    }
364}
365
366impl<'a, 'b, T: ?Sized + PartialEq> PartialEq<Box<'b, T>> for Box<'a, T> {
367    #[inline]
368    fn eq(&self, other: &Box<'b, T>) -> bool {
369        PartialEq::eq(&**self, &**other)
370    }
371    #[inline]
372    fn ne(&self, other: &Box<'b, T>) -> bool {
373        PartialEq::ne(&**self, &**other)
374    }
375}
376
377impl<'a, 'b, T: ?Sized + PartialOrd> PartialOrd<Box<'b, T>> for Box<'a, T> {
378    #[inline]
379    fn partial_cmp(&self, other: &Box<'b, T>) -> Option<Ordering> {
380        PartialOrd::partial_cmp(&**self, &**other)
381    }
382    #[inline]
383    fn lt(&self, other: &Box<'b, T>) -> bool {
384        PartialOrd::lt(&**self, &**other)
385    }
386    #[inline]
387    fn le(&self, other: &Box<'b, T>) -> bool {
388        PartialOrd::le(&**self, &**other)
389    }
390    #[inline]
391    fn ge(&self, other: &Box<'b, T>) -> bool {
392        PartialOrd::ge(&**self, &**other)
393    }
394    #[inline]
395    fn gt(&self, other: &Box<'b, T>) -> bool {
396        PartialOrd::gt(&**self, &**other)
397    }
398}
399
400impl<'a, T: ?Sized + Ord> Ord for Box<'a, T> {
401    #[inline]
402    fn cmp(&self, other: &Box<'a, T>) -> Ordering {
403        Ord::cmp(&**self, &**other)
404    }
405}
406
407impl<'a, T: ?Sized + Eq> Eq for Box<'a, T> {}
408
409impl<'a, T: ?Sized + Hash> Hash for Box<'a, T> {
410    fn hash<H: Hasher>(&self, state: &mut H) {
411        (**self).hash(state);
412    }
413}
414
415impl<'a, T: ?Sized + Hasher> Hasher for Box<'a, T> {
416    fn finish(&self) -> u64 {
417        (**self).finish()
418    }
419    fn write(&mut self, bytes: &[u8]) {
420        (**self).write(bytes)
421    }
422    fn write_u8(&mut self, i: u8) {
423        (**self).write_u8(i)
424    }
425    fn write_u16(&mut self, i: u16) {
426        (**self).write_u16(i)
427    }
428    fn write_u32(&mut self, i: u32) {
429        (**self).write_u32(i)
430    }
431    fn write_u64(&mut self, i: u64) {
432        (**self).write_u64(i)
433    }
434    fn write_u128(&mut self, i: u128) {
435        (**self).write_u128(i)
436    }
437    fn write_usize(&mut self, i: usize) {
438        (**self).write_usize(i)
439    }
440    fn write_i8(&mut self, i: i8) {
441        (**self).write_i8(i)
442    }
443    fn write_i16(&mut self, i: i16) {
444        (**self).write_i16(i)
445    }
446    fn write_i32(&mut self, i: i32) {
447        (**self).write_i32(i)
448    }
449    fn write_i64(&mut self, i: i64) {
450        (**self).write_i64(i)
451    }
452    fn write_i128(&mut self, i: i128) {
453        (**self).write_i128(i)
454    }
455    fn write_isize(&mut self, i: isize) {
456        (**self).write_isize(i)
457    }
458}
459
460impl<'a, T: ?Sized> From<Box<'a, T>> for Pin<Box<'a, T>> {
461    /// Converts a `Box<T>` into a `Pin<Box<T>>`.
462    ///
463    /// This conversion does not allocate on the heap and happens in place.
464    fn from(boxed: Box<'a, T>) -> Self {
465        // It's not possible to move or replace the insides of a `Pin<Box<T>>`
466        // when `T: !Unpin`,  so it's safe to pin it directly without any
467        // additional requirements.
468        unsafe { Pin::new_unchecked(boxed) }
469    }
470}
471
472impl<'a> Box<'a, dyn Any> {
473    #[inline]
474    /// Attempt to downcast the box to a concrete type.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use std::any::Any;
480    ///
481    /// fn print_if_string(value: Box<dyn Any>) {
482    ///     if let Ok(string) = value.downcast::<String>() {
483    ///         println!("String ({}): {}", string.len(), string);
484    ///     }
485    /// }
486    ///
487    /// let my_string = "Hello World".to_string();
488    /// print_if_string(Box::new(my_string));
489    /// print_if_string(Box::new(0i8));
490    /// ```
491    pub fn downcast<T: Any>(self) -> Result<Box<'a, T>, Box<'a, dyn Any>> {
492        if self.is::<T>() {
493            unsafe {
494                let raw: *mut dyn Any = Box::into_raw(self);
495                Ok(Box::from_raw(raw as *mut T))
496            }
497        } else {
498            Err(self)
499        }
500    }
501}
502
503impl<'a> Box<'a, dyn Any + Send> {
504    #[inline]
505    /// Attempt to downcast the box to a concrete type.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use std::any::Any;
511    ///
512    /// fn print_if_string(value: Box<dyn Any + Send>) {
513    ///     if let Ok(string) = value.downcast::<String>() {
514    ///         println!("String ({}): {}", string.len(), string);
515    ///     }
516    /// }
517    ///
518    /// let my_string = "Hello World".to_string();
519    /// print_if_string(Box::new(my_string));
520    /// print_if_string(Box::new(0i8));
521    /// ```
522    pub fn downcast<T: Any>(self) -> Result<Box<'a, T>, Box<'a, dyn Any + Send>> {
523        if self.is::<T>() {
524            unsafe {
525                let raw: *mut (dyn Any + Send) = Box::into_raw(self);
526                Ok(Box::from_raw(raw as *mut T))
527            }
528        } else {
529            Err(self)
530        }
531    }
532}
533
534impl<'a, T: fmt::Display + ?Sized> fmt::Display for Box<'a, T> {
535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536        fmt::Display::fmt(&**self, f)
537    }
538}
539
540impl<'a, T: fmt::Debug + ?Sized> fmt::Debug for Box<'a, T> {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        fmt::Debug::fmt(&**self, f)
543    }
544}
545
546impl<'a, T: ?Sized> fmt::Pointer for Box<'a, T> {
547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548        // It's not possible to extract the inner Uniq directly from the Box,
549        // instead we cast it to a *const which aliases the Unique
550        let ptr: *const T = &**self;
551        fmt::Pointer::fmt(&ptr, f)
552    }
553}
554
555/// This function tests that box isn't contravariant.
556///
557/// ```compile_fail
558/// fn _box_is_not_contravariant<'sub, 'sup :'sub>(
559///     a: Box<&'sup u32>,
560///     b: Box<&'sub u32>,
561///     f: impl Fn(Box<&'sup u32>),
562/// ) {
563///     f(a);
564///     f(b);
565/// }
566/// ```
567///
568/// This function tests that `Box` isn't Send when the inner type isn't Send.
569/// ```compile_fail
570/// fn _requires_send<T: Send>(_value: T) {}
571/// fn _box_inherets_send_not_send(a: Box<NonNull<()>>) {
572///    _requires_send(a);
573/// }
574/// ```
575///
576/// This function tests that `Box` isn't Sync when the inner type isn't Sync.
577/// ```compile_fail
578/// fn _requires_sync<T: Sync>(_value: T) {}
579/// fn _box_inherets_sync_not_sync(a: Box<NonNull<()>>) {
580///    _requires_sync(a);
581/// }
582/// ```
583#[cfg(doctest)]
584fn _doctest_only() {}
585
586impl<'a, T: ?Sized> Deref for Box<'a, T> {
587    type Target = T;
588
589    fn deref(&self) -> &T {
590        // Safety: Our pointer always points to a valid instance of `T`
591        // allocated within a `Bump` and the `&self` borrow ensures that there
592        // are no active exclusive borrows.
593        unsafe { self.0.as_ref() }
594    }
595}
596
597impl<'a, T: ?Sized> DerefMut for Box<'a, T> {
598    fn deref_mut(&mut self) -> &mut T {
599        // Safety: Our pointer always points to a valid instance of `T`
600        // allocated within a `Bump` and the `&mut self` borrow ensures that
601        // there are no other active borrows.
602        unsafe { self.0.as_mut() }
603    }
604}
605
606impl<'a, I: Iterator + ?Sized> Iterator for Box<'a, I> {
607    type Item = I::Item;
608    fn next(&mut self) -> Option<I::Item> {
609        (**self).next()
610    }
611    fn size_hint(&self) -> (usize, Option<usize>) {
612        (**self).size_hint()
613    }
614    fn nth(&mut self, n: usize) -> Option<I::Item> {
615        (**self).nth(n)
616    }
617    fn last(self) -> Option<I::Item> {
618        #[inline]
619        fn some<T>(_: Option<T>, x: T) -> Option<T> {
620            Some(x)
621        }
622        self.fold(None, some)
623    }
624}
625
626impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<'a, I> {
627    fn next_back(&mut self) -> Option<I::Item> {
628        (**self).next_back()
629    }
630    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
631        (**self).nth_back(n)
632    }
633}
634impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<'a, I> {
635    fn len(&self) -> usize {
636        (**self).len()
637    }
638}
639
640impl<'a, I: FusedIterator + ?Sized> FusedIterator for Box<'a, I> {}
641
642#[cfg(feature = "collections")]
643impl<'a, A> Box<'a, [A]> {
644    /// Creates a value from an iterator.
645    /// This method is an adapted version of [`FromIterator::from_iter`][from_iter].
646    /// It cannot be made as that trait implementation given different signature.
647    ///
648    /// [from_iter]: https://doc.rust-lang.org/std/iter/trait.FromIterator.html#tymethod.from_iter
649    ///
650    /// # Examples
651    ///
652    /// Basic usage:
653    /// ```
654    /// use bumpalo::{Bump, boxed::Box, vec};
655    ///
656    /// let b = Bump::new();
657    ///
658    /// let five_fives = std::iter::repeat(5).take(5);
659    /// let slice = Box::from_iter_in(five_fives, &b);
660    /// assert_eq!(vec![in &b; 5, 5, 5, 5, 5], &*slice);
661    /// ```
662    pub fn from_iter_in<T: IntoIterator<Item = A>>(iter: T, a: &'a Bump) -> Self {
663        use crate::collections::Vec;
664        let mut vec = Vec::new_in(a);
665        vec.extend(iter);
666        vec.into_boxed_slice()
667    }
668}
669
670impl<'a, T: ?Sized> borrow::Borrow<T> for Box<'a, T> {
671    fn borrow(&self) -> &T {
672        &**self
673    }
674}
675
676impl<'a, T: ?Sized> borrow::BorrowMut<T> for Box<'a, T> {
677    fn borrow_mut(&mut self) -> &mut T {
678        &mut **self
679    }
680}
681
682impl<'a, T: ?Sized> AsRef<T> for Box<'a, T> {
683    fn as_ref(&self) -> &T {
684        &**self
685    }
686}
687
688impl<'a, T: ?Sized> AsMut<T> for Box<'a, T> {
689    fn as_mut(&mut self) -> &mut T {
690        &mut **self
691    }
692}
693
694impl<'a, T: ?Sized> Unpin for Box<'a, T> {}
695
696// Safety: If T is Send the box is too because Box has exclusive access to its wrapped T.
697unsafe impl<'a, T: ?Sized + Send> Send for Box<'a, T> {}
698
699// Safety: If T is Sync the box is too because Box has exclusive access to its wrapped T.
700unsafe impl<'a, T: ?Sized + Sync> Sync for Box<'a, T> {}
701
702impl<'a, F: ?Sized + Future + Unpin> Future for Box<'a, F> {
703    type Output = F::Output;
704
705    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
706        F::poll(Pin::new(&mut *self), cx)
707    }
708}
709
710/// This impl replaces unsize coercion.
711impl<'a, T, const N: usize> From<Box<'a, [T; N]>> for Box<'a, [T]> {
712    fn from(arr: Box<'a, [T; N]>) -> Box<'a, [T]> {
713        let mut arr = ManuallyDrop::new(arr);
714        let ptr = core::ptr::slice_from_raw_parts_mut(arr.as_mut_ptr(), N);
715        unsafe { Box::from_raw(ptr) }
716    }
717}
718
719/// This impl replaces unsize coercion.
720impl<'a, T, const N: usize> TryFrom<Box<'a, [T]>> for Box<'a, [T; N]> {
721    type Error = Box<'a, [T]>;
722    fn try_from(slice: Box<'a, [T]>) -> Result<Box<'a, [T; N]>, Box<'a, [T]>> {
723        if slice.len() == N {
724            let mut slice = ManuallyDrop::new(slice);
725            let ptr = slice.as_mut_ptr() as *mut [T; N];
726            Ok(unsafe { Box::from_raw(ptr) })
727        } else {
728            Err(slice)
729        }
730    }
731}
732
733#[cfg(feature = "serde")]
734mod serialize {
735    use super::*;
736
737    use serde::{Serialize, Serializer};
738
739    impl<'a, T> Serialize for Box<'a, T>
740    where
741        T: Serialize,
742    {
743        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
744            T::serialize(self, serializer)
745        }
746    }
747}