]> git.proxmox.com Git - rustc.git/blame - library/alloc/src/boxed.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / library / alloc / src / boxed.rs
CommitLineData
85aaf69f
SL
1//! A pointer type for heap allocation.
2//!
416331ca 3//! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
62682a34 4//! heap allocation in Rust. Boxes provide ownership for this allocation, and
74b04a01
XL
5//! drop their contents when they go out of scope. Boxes also ensure that they
6//! never allocate more than `isize::MAX` bytes.
85aaf69f
SL
7//!
8//! # Examples
9//!
0bf4aa26 10//! Move a value from the stack to the heap by creating a [`Box`]:
85aaf69f
SL
11//!
12//! ```
0bf4aa26
XL
13//! let val: u8 = 5;
14//! let boxed: Box<u8> = Box::new(val);
15//! ```
16//!
17//! Move a value from a [`Box`] back to the stack by [dereferencing]:
18//!
19//! ```
20//! let boxed: Box<u8> = Box::new(5);
21//! let val: u8 = *boxed;
85aaf69f
SL
22//! ```
23//!
24//! Creating a recursive data structure:
25//!
26//! ```
27//! #[derive(Debug)]
28//! enum List<T> {
29//! Cons(T, Box<List<T>>),
30//! Nil,
31//! }
32//!
e74abb32
XL
33//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34//! println!("{:?}", list);
85aaf69f
SL
35//! ```
36//!
d9579d0f 37//! This will print `Cons(1, Cons(2, Nil))`.
9346a6ac 38//!
62682a34
SL
39//! Recursive structures must be boxed, because if the definition of `Cons`
40//! looked like this:
9346a6ac 41//!
041b39d2
XL
42//! ```compile_fail,E0072
43//! # enum List<T> {
9346a6ac 44//! Cons(T, List<T>),
041b39d2 45//! # }
9346a6ac
AL
46//! ```
47//!
62682a34
SL
48//! It wouldn't work. This is because the size of a `List` depends on how many
49//! elements are in the list, and so we don't know how much memory to allocate
416331ca 50//! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
62682a34 51//! big `Cons` needs to be.
0bf4aa26 52//!
dc9dc135
XL
53//! # Memory layout
54//!
55//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
56//! its allocation. It is valid to convert both ways between a [`Box`] and a
57//! raw pointer allocated with the [`Global`] allocator, given that the
58//! [`Layout`] used with the allocator is correct for the type. More precisely,
59//! a `value: *mut T` that has been allocated with the [`Global`] allocator
60//! with `Layout::for_value(&*value)` may be converted into a box using
416331ca
XL
61//! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
62//! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
63//! [`Global`] allocator with [`Layout::for_value(&*value)`].
dc9dc135 64//!
fc512014
XL
65//! For zero-sized values, the `Box` pointer still has to be [valid] for reads
66//! and writes and sufficiently aligned. In particular, casting any aligned
67//! non-zero integer literal to a raw pointer produces a valid pointer, but a
68//! pointer pointing into previously allocated memory that since got freed is
69//! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
70//! be used is to use [`ptr::NonNull::dangling`].
71//!
60c5eb7d
XL
72//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
73//! as a single pointer and is also ABI-compatible with C pointers
74//! (i.e. the C type `T*`). This means that if you have extern "C"
75//! Rust functions that will be called from C, you can define those
76//! Rust functions using `Box<T>` types, and use `T*` as corresponding
77//! type on the C side. As an example, consider this C header which
78//! declares functions that create and destroy some kind of `Foo`
79//! value:
80//!
81//! ```c
82//! /* C header */
83//!
84//! /* Returns ownership to the caller */
85//! struct Foo* foo_new(void);
86//!
87//! /* Takes ownership from the caller; no-op when invoked with NULL */
88//! void foo_delete(struct Foo*);
89//! ```
90//!
91//! These two functions might be implemented in Rust as follows. Here, the
92//! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
93//! the ownership constraints. Note also that the nullable argument to
94//! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
95//! cannot be null.
96//!
97//! ```
98//! #[repr(C)]
99//! pub struct Foo;
100//!
101//! #[no_mangle]
f035d41b 102//! #[allow(improper_ctypes_definitions)]
60c5eb7d
XL
103//! pub extern "C" fn foo_new() -> Box<Foo> {
104//! Box::new(Foo)
105//! }
dc9dc135 106//!
60c5eb7d 107//! #[no_mangle]
f035d41b 108//! #[allow(improper_ctypes_definitions)]
60c5eb7d
XL
109//! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
110//! ```
111//!
112//! Even though `Box<T>` has the same representation and C ABI as a C pointer,
113//! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
114//! and expect things to work. `Box<T>` values will always be fully aligned,
115//! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
116//! free the value with the global allocator. In general, the best practice
117//! is to only use `Box<T>` for pointers that originated from the global
118//! allocator.
119//!
120//! **Important.** At least at present, you should avoid using
121//! `Box<T>` types for functions that are defined in C but invoked
122//! from Rust. In those cases, you should directly mirror the C types
123//! as closely as possible. Using types like `Box<T>` where the C
124//! definition is just using `T*` can lead to undefined behavior, as
125//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
126//!
127//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
3dfed10e
XL
128//! [dereferencing]: core::ops::Deref
129//! [`Box<T>`]: Box
130//! [`Box::<T>::from_raw(value)`]: Box::from_raw
131//! [`Box::<T>::into_raw`]: Box::into_raw
132//! [`Global`]: crate::alloc::Global
133//! [`Layout`]: crate::alloc::Layout
134//! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
fc512014 135//! [valid]: ptr#safety
1a4d82fc 136
85aaf69f
SL
137#![stable(feature = "rust1", since = "1.0.0")]
138
1a4d82fc 139use core::any::Any;
e9174d1e 140use core::borrow;
85aaf69f 141use core::cmp::Ordering;
416331ca 142use core::convert::{From, TryFrom};
1a4d82fc 143use core::fmt;
0bf4aa26 144use core::future::Future;
0531ce1d 145use core::hash::{Hash, Hasher};
dfeec247 146use core::iter::{FromIterator, FusedIterator, Iterator};
83c7162d 147use core::marker::{Unpin, Unsize};
b7449926 148use core::mem;
0731742a 149use core::ops::{
dfeec247 150 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
0731742a 151};
dfeec247 152use core::pin::Pin;
3dfed10e 153use core::ptr::{self, Unique};
532ac7d7 154use core::task::{Context, Poll};
c1a9b12d 155
fc512014 156use crate::alloc::{handle_alloc_error, Allocator, Global, Layout};
f9f354fc 157use crate::borrow::Cow;
9fa01778
XL
158use crate::raw_vec::RawVec;
159use crate::str::from_boxed_utf8_unchecked;
dfeec247 160use crate::vec::Vec;
1a4d82fc 161
85aaf69f
SL
162/// A pointer type for heap allocation.
163///
164/// See the [module-level documentation](../../std/boxed/index.html) for more.
1a4d82fc 165#[lang = "owned_box"]
32a655c1 166#[fundamental]
85aaf69f 167#[stable(feature = "rust1", since = "1.0.0")]
29967ef6
XL
168pub struct Box<
169 T: ?Sized,
fc512014 170 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
29967ef6 171>(Unique<T>, A);
c1a9b12d 172
1a4d82fc 173impl<T> Box<T> {
9cc50fc6 174 /// Allocates memory on the heap and then places `x` into it.
85aaf69f 175 ///
8bb4bdeb
XL
176 /// This doesn't actually allocate if `T` is zero-sized.
177 ///
85aaf69f
SL
178 /// # Examples
179 ///
180 /// ```
9cc50fc6 181 /// let five = Box::new(5);
85aaf69f
SL
182 /// ```
183 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 184 #[inline(always)]
29967ef6 185 pub fn new(x: T) -> Self {
1a4d82fc
JJ
186 box x
187 }
0bf4aa26 188
e1599b0c
XL
189 /// Constructs a new box with uninitialized contents.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// #![feature(new_uninit)]
195 ///
196 /// let mut five = Box::<u32>::new_uninit();
197 ///
198 /// let five = unsafe {
199 /// // Deferred initialization:
200 /// five.as_mut_ptr().write(5);
201 ///
202 /// five.assume_init()
203 /// };
204 ///
205 /// assert_eq!(*five, 5)
206 /// ```
207 #[unstable(feature = "new_uninit", issue = "63291")]
29967ef6 208 #[inline]
e1599b0c 209 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
29967ef6 210 Self::new_uninit_in(Global)
e1599b0c
XL
211 }
212
60c5eb7d
XL
213 /// Constructs a new `Box` with uninitialized contents, with the memory
214 /// being filled with `0` bytes.
215 ///
216 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
217 /// of this method.
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// #![feature(new_uninit)]
223 ///
224 /// let zero = Box::<u32>::new_zeroed();
225 /// let zero = unsafe { zero.assume_init() };
226 ///
227 /// assert_eq!(*zero, 0)
228 /// ```
229 ///
1b1a35ee 230 /// [zeroed]: mem::MaybeUninit::zeroed
60c5eb7d 231 #[unstable(feature = "new_uninit", issue = "63291")]
29967ef6 232 #[inline]
60c5eb7d 233 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
29967ef6 234 Self::new_zeroed_in(Global)
60c5eb7d
XL
235 }
236
0731742a
XL
237 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
238 /// `x` will be pinned in memory and unable to be moved.
239 #[stable(feature = "pin", since = "1.33.0")]
0bf4aa26 240 #[inline(always)]
0731742a 241 pub fn pin(x: T) -> Pin<Box<T>> {
0bf4aa26
XL
242 (box x).into()
243 }
29967ef6
XL
244}
245
fc512014 246impl<T, A: Allocator> Box<T, A> {
29967ef6
XL
247 /// Allocates memory in the given allocator then places `x` into it.
248 ///
249 /// This doesn't actually allocate if `T` is zero-sized.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// #![feature(allocator_api)]
255 ///
256 /// use std::alloc::System;
257 ///
258 /// let five = Box::new_in(5, System);
259 /// ```
260 #[unstable(feature = "allocator_api", issue = "32838")]
261 #[inline]
262 pub fn new_in(x: T, alloc: A) -> Self {
263 let mut boxed = Self::new_uninit_in(alloc);
264 unsafe {
265 boxed.as_mut_ptr().write(x);
266 boxed.assume_init()
267 }
268 }
269
270 /// Constructs a new box with uninitialized contents in the provided allocator.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// #![feature(allocator_api, new_uninit)]
276 ///
277 /// use std::alloc::System;
278 ///
279 /// let mut five = Box::<u32, _>::new_uninit_in(System);
280 ///
281 /// let five = unsafe {
282 /// // Deferred initialization:
283 /// five.as_mut_ptr().write(5);
284 ///
285 /// five.assume_init()
286 /// };
287 ///
288 /// assert_eq!(*five, 5)
289 /// ```
290 #[unstable(feature = "allocator_api", issue = "32838")]
291 // #[unstable(feature = "new_uninit", issue = "63291")]
292 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
293 let layout = Layout::new::<mem::MaybeUninit<T>>();
fc512014 294 let ptr = alloc.allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)).cast();
29967ef6
XL
295 unsafe { Box::from_raw_in(ptr.as_ptr(), alloc) }
296 }
297
298 /// Constructs a new `Box` with uninitialized contents, with the memory
299 /// being filled with `0` bytes in the provided allocator.
300 ///
301 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
302 /// of this method.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// #![feature(allocator_api, new_uninit)]
308 ///
309 /// use std::alloc::System;
310 ///
311 /// let zero = Box::<u32, _>::new_zeroed_in(System);
312 /// let zero = unsafe { zero.assume_init() };
313 ///
314 /// assert_eq!(*zero, 0)
315 /// ```
316 ///
317 /// [zeroed]: mem::MaybeUninit::zeroed
318 #[unstable(feature = "allocator_api", issue = "32838")]
319 // #[unstable(feature = "new_uninit", issue = "63291")]
320 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
321 let layout = Layout::new::<mem::MaybeUninit<T>>();
fc512014
XL
322 let ptr =
323 alloc.allocate_zeroed(layout).unwrap_or_else(|_| handle_alloc_error(layout)).cast();
29967ef6
XL
324 unsafe { Box::from_raw_in(ptr.as_ptr(), alloc) }
325 }
326
327 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
328 /// `x` will be pinned in memory and unable to be moved.
329 #[unstable(feature = "allocator_api", issue = "32838")]
330 #[inline(always)]
fc512014
XL
331 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
332 where
333 A: 'static,
334 {
29967ef6
XL
335 Self::new_in(x, alloc).into()
336 }
f9f354fc
XL
337
338 /// Converts a `Box<T>` into a `Box<[T]>`
339 ///
340 /// This conversion does not allocate on the heap and happens in place.
f9f354fc 341 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
29967ef6 342 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
fc512014 343 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
29967ef6 344 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
f9f354fc 345 }
1a4d82fc
JJ
346}
347
e1599b0c
XL
348impl<T> Box<[T]> {
349 /// Constructs a new boxed slice with uninitialized contents.
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// #![feature(new_uninit)]
355 ///
356 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
357 ///
358 /// let values = unsafe {
359 /// // Deferred initialization:
360 /// values[0].as_mut_ptr().write(1);
361 /// values[1].as_mut_ptr().write(2);
362 /// values[2].as_mut_ptr().write(3);
363 ///
364 /// values.assume_init()
365 /// };
366 ///
367 /// assert_eq!(*values, [1, 2, 3])
368 /// ```
369 #[unstable(feature = "new_uninit", issue = "63291")]
370 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
ba9703b0 371 unsafe { RawVec::with_capacity(len).into_box(len) }
e1599b0c 372 }
3dfed10e
XL
373
374 /// Constructs a new boxed slice with uninitialized contents, with the memory
375 /// being filled with `0` bytes.
376 ///
377 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
378 /// of this method.
379 ///
380 /// # Examples
381 ///
382 /// ```
383 /// #![feature(new_uninit)]
384 ///
385 /// let values = Box::<[u32]>::new_zeroed_slice(3);
386 /// let values = unsafe { values.assume_init() };
387 ///
388 /// assert_eq!(*values, [0, 0, 0])
389 /// ```
390 ///
1b1a35ee 391 /// [zeroed]: mem::MaybeUninit::zeroed
3dfed10e
XL
392 #[unstable(feature = "new_uninit", issue = "63291")]
393 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
394 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
395 }
e1599b0c
XL
396}
397
fc512014 398impl<T, A: Allocator> Box<[T], A> {
29967ef6
XL
399 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
400 ///
401 /// # Examples
402 ///
403 /// ```
404 /// #![feature(allocator_api, new_uninit)]
405 ///
406 /// use std::alloc::System;
407 ///
408 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
409 ///
410 /// let values = unsafe {
411 /// // Deferred initialization:
412 /// values[0].as_mut_ptr().write(1);
413 /// values[1].as_mut_ptr().write(2);
414 /// values[2].as_mut_ptr().write(3);
415 ///
416 /// values.assume_init()
417 /// };
418 ///
419 /// assert_eq!(*values, [1, 2, 3])
420 /// ```
421 #[unstable(feature = "allocator_api", issue = "32838")]
422 // #[unstable(feature = "new_uninit", issue = "63291")]
423 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
424 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
425 }
426
427 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
428 /// with the memory being filled with `0` bytes.
429 ///
430 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
431 /// of this method.
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// #![feature(allocator_api, new_uninit)]
437 ///
438 /// use std::alloc::System;
439 ///
440 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
441 /// let values = unsafe { values.assume_init() };
442 ///
443 /// assert_eq!(*values, [0, 0, 0])
444 /// ```
445 ///
446 /// [zeroed]: mem::MaybeUninit::zeroed
447 #[unstable(feature = "allocator_api", issue = "32838")]
448 // #[unstable(feature = "new_uninit", issue = "63291")]
449 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
450 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
451 }
452}
453
fc512014 454impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
29967ef6 455 /// Converts to `Box<T, A>`.
e1599b0c
XL
456 ///
457 /// # Safety
458 ///
459 /// As with [`MaybeUninit::assume_init`],
460 /// it is up to the caller to guarantee that the value
461 /// really is in an initialized state.
462 /// Calling this when the content is not yet fully initialized
463 /// causes immediate undefined behavior.
464 ///
1b1a35ee 465 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
e1599b0c
XL
466 ///
467 /// # Examples
468 ///
469 /// ```
470 /// #![feature(new_uninit)]
471 ///
472 /// let mut five = Box::<u32>::new_uninit();
473 ///
474 /// let five: Box<u32> = unsafe {
475 /// // Deferred initialization:
476 /// five.as_mut_ptr().write(5);
477 ///
478 /// five.assume_init()
479 /// };
480 ///
481 /// assert_eq!(*five, 5)
482 /// ```
483 #[unstable(feature = "new_uninit", issue = "63291")]
484 #[inline]
29967ef6 485 pub unsafe fn assume_init(self) -> Box<T, A> {
fc512014 486 let (raw, alloc) = Box::into_raw_with_allocator(self);
29967ef6 487 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
e1599b0c
XL
488 }
489}
490
fc512014 491impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
29967ef6 492 /// Converts to `Box<[T], A>`.
e1599b0c
XL
493 ///
494 /// # Safety
495 ///
496 /// As with [`MaybeUninit::assume_init`],
497 /// it is up to the caller to guarantee that the values
498 /// really are in an initialized state.
499 /// Calling this when the content is not yet fully initialized
500 /// causes immediate undefined behavior.
501 ///
1b1a35ee 502 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
e1599b0c
XL
503 ///
504 /// # Examples
505 ///
506 /// ```
507 /// #![feature(new_uninit)]
508 ///
509 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
510 ///
511 /// let values = unsafe {
512 /// // Deferred initialization:
513 /// values[0].as_mut_ptr().write(1);
514 /// values[1].as_mut_ptr().write(2);
515 /// values[2].as_mut_ptr().write(3);
516 ///
517 /// values.assume_init()
518 /// };
519 ///
520 /// assert_eq!(*values, [1, 2, 3])
521 /// ```
522 #[unstable(feature = "new_uninit", issue = "63291")]
523 #[inline]
29967ef6 524 pub unsafe fn assume_init(self) -> Box<[T], A> {
fc512014 525 let (raw, alloc) = Box::into_raw_with_allocator(self);
29967ef6 526 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
e1599b0c
XL
527 }
528}
529
92a42be0 530impl<T: ?Sized> Box<T> {
9cc50fc6 531 /// Constructs a box from a raw pointer.
85aaf69f 532 ///
9cc50fc6
SL
533 /// After calling this function, the raw pointer is owned by the
534 /// resulting `Box`. Specifically, the `Box` destructor will call
dc9dc135
XL
535 /// the destructor of `T` and free the allocated memory. For this
536 /// to be safe, the memory must have been allocated in accordance
537 /// with the [memory layout] used by `Box` .
538 ///
539 /// # Safety
85aaf69f 540 ///
9cc50fc6
SL
541 /// This function is unsafe because improper use may lead to
542 /// memory problems. For example, a double-free may occur if the
85aaf69f 543 /// function is called twice on the same raw pointer.
5bcae85e 544 ///
fc512014
XL
545 /// The safety conditions are described in the [memory layout] section.
546 ///
5bcae85e 547 /// # Examples
fc512014 548 ///
dc9dc135
XL
549 /// Recreate a `Box` which was previously converted to a raw pointer
550 /// using [`Box::into_raw`]:
5bcae85e
SL
551 /// ```
552 /// let x = Box::new(5);
553 /// let ptr = Box::into_raw(x);
554 /// let x = unsafe { Box::from_raw(ptr) };
555 /// ```
dc9dc135
XL
556 /// Manually create a `Box` from scratch by using the global allocator:
557 /// ```
558 /// use std::alloc::{alloc, Layout};
559 ///
560 /// unsafe {
561 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
f035d41b
XL
562 /// // In general .write is required to avoid attempting to destruct
563 /// // the (uninitialized) previous contents of `ptr`, though for this
564 /// // simple example `*ptr = 5` would have worked as well.
565 /// ptr.write(5);
dc9dc135
XL
566 /// let x = Box::from_raw(ptr);
567 /// }
568 /// ```
569 ///
3dfed10e
XL
570 /// [memory layout]: self#memory-layout
571 /// [`Layout`]: crate::Layout
e9174d1e 572 #[stable(feature = "box_raw", since = "1.4.0")]
c34b1796 573 #[inline]
85aaf69f 574 pub unsafe fn from_raw(raw: *mut T) -> Self {
29967ef6
XL
575 unsafe { Self::from_raw_in(raw, Global) }
576 }
577}
578
fc512014 579impl<T: ?Sized, A: Allocator> Box<T, A> {
29967ef6
XL
580 /// Constructs a box from a raw pointer in the given allocator.
581 ///
582 /// After calling this function, the raw pointer is owned by the
583 /// resulting `Box`. Specifically, the `Box` destructor will call
584 /// the destructor of `T` and free the allocated memory. For this
585 /// to be safe, the memory must have been allocated in accordance
586 /// with the [memory layout] used by `Box` .
587 ///
588 /// # Safety
589 ///
590 /// This function is unsafe because improper use may lead to
591 /// memory problems. For example, a double-free may occur if the
592 /// function is called twice on the same raw pointer.
593 ///
594 ///
595 /// # Examples
596 ///
597 /// Recreate a `Box` which was previously converted to a raw pointer
fc512014 598 /// using [`Box::into_raw_with_allocator`]:
29967ef6
XL
599 /// ```
600 /// #![feature(allocator_api)]
601 ///
602 /// use std::alloc::System;
603 ///
604 /// let x = Box::new_in(5, System);
fc512014 605 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
29967ef6
XL
606 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
607 /// ```
608 /// Manually create a `Box` from scratch by using the system allocator:
609 /// ```
610 /// #![feature(allocator_api, slice_ptr_get)]
611 ///
fc512014 612 /// use std::alloc::{Allocator, Layout, System};
29967ef6
XL
613 ///
614 /// unsafe {
fc512014 615 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr();
29967ef6
XL
616 /// // In general .write is required to avoid attempting to destruct
617 /// // the (uninitialized) previous contents of `ptr`, though for this
618 /// // simple example `*ptr = 5` would have worked as well.
619 /// ptr.write(5);
620 /// let x = Box::from_raw_in(ptr, System);
621 /// }
622 /// # Ok::<(), std::alloc::AllocError>(())
623 /// ```
624 ///
625 /// [memory layout]: self#memory-layout
626 /// [`Layout`]: crate::Layout
627 #[unstable(feature = "allocator_api", issue = "32838")]
628 #[inline]
629 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
630 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
85aaf69f 631 }
62682a34 632
b7449926
XL
633 /// Consumes the `Box`, returning a wrapped raw pointer.
634 ///
635 /// The pointer will be properly aligned and non-null.
62682a34 636 ///
9cc50fc6
SL
637 /// After calling this function, the caller is responsible for the
638 /// memory previously managed by the `Box`. In particular, the
dc9dc135
XL
639 /// caller should properly destroy `T` and release the memory, taking
640 /// into account the [memory layout] used by `Box`. The easiest way to
641 /// do this is to convert the raw pointer back into a `Box` with the
642 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
643 /// the cleanup.
62682a34 644 ///
9e0c209e
SL
645 /// Note: this is an associated function, which means that you have
646 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
647 /// is so that there is no conflict with a method on the inner type.
648 ///
62682a34 649 /// # Examples
dc9dc135
XL
650 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
651 /// for automatic cleanup:
e9174d1e 652 /// ```
dc9dc135 653 /// let x = Box::new(String::from("Hello"));
5bcae85e 654 /// let ptr = Box::into_raw(x);
dc9dc135
XL
655 /// let x = unsafe { Box::from_raw(ptr) };
656 /// ```
657 /// Manual cleanup by explicitly running the destructor and deallocating
658 /// the memory:
62682a34 659 /// ```
dc9dc135
XL
660 /// use std::alloc::{dealloc, Layout};
661 /// use std::ptr;
662 ///
663 /// let x = Box::new(String::from("Hello"));
664 /// let p = Box::into_raw(x);
665 /// unsafe {
666 /// ptr::drop_in_place(p);
667 /// dealloc(p as *mut u8, Layout::new::<String>());
668 /// }
669 /// ```
670 ///
3dfed10e 671 /// [memory layout]: self#memory-layout
e9174d1e 672 #[stable(feature = "box_raw", since = "1.4.0")]
62682a34 673 #[inline]
29967ef6 674 pub fn into_raw(b: Self) -> *mut T {
fc512014 675 Self::into_raw_with_allocator(b).0
29967ef6
XL
676 }
677
678 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
679 ///
680 /// The pointer will be properly aligned and non-null.
681 ///
682 /// After calling this function, the caller is responsible for the
683 /// memory previously managed by the `Box`. In particular, the
684 /// caller should properly destroy `T` and release the memory, taking
685 /// into account the [memory layout] used by `Box`. The easiest way to
686 /// do this is to convert the raw pointer back into a `Box` with the
687 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
688 /// the cleanup.
689 ///
690 /// Note: this is an associated function, which means that you have
fc512014 691 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
29967ef6
XL
692 /// is so that there is no conflict with a method on the inner type.
693 ///
694 /// # Examples
695 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
696 /// for automatic cleanup:
697 /// ```
698 /// #![feature(allocator_api)]
699 ///
700 /// use std::alloc::System;
701 ///
702 /// let x = Box::new_in(String::from("Hello"), System);
fc512014 703 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
29967ef6
XL
704 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
705 /// ```
706 /// Manual cleanup by explicitly running the destructor and deallocating
707 /// the memory:
708 /// ```
709 /// #![feature(allocator_api)]
710 ///
fc512014 711 /// use std::alloc::{Allocator, Layout, System};
29967ef6
XL
712 /// use std::ptr::{self, NonNull};
713 ///
714 /// let x = Box::new_in(String::from("Hello"), System);
fc512014 715 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
29967ef6
XL
716 /// unsafe {
717 /// ptr::drop_in_place(ptr);
718 /// let non_null = NonNull::new_unchecked(ptr);
fc512014 719 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
29967ef6
XL
720 /// }
721 /// ```
722 ///
723 /// [memory layout]: self#memory-layout
724 #[unstable(feature = "allocator_api", issue = "32838")]
725 #[inline]
fc512014 726 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
29967ef6
XL
727 let (leaked, alloc) = Box::into_unique(b);
728 (leaked.as_ptr(), alloc)
62682a34 729 }
3b2f2976 730
f9f354fc
XL
731 #[unstable(
732 feature = "ptr_internals",
733 issue = "none",
734 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
735 )]
3b2f2976 736 #[inline]
83c7162d 737 #[doc(hidden)]
29967ef6 738 pub fn into_unique(b: Self) -> (Unique<T>, A) {
f9f354fc
XL
739 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
740 // raw pointer for the type system. Turning it directly into a raw pointer would not be
741 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
29967ef6
XL
742 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
743 // behaves correctly.
744 let alloc = unsafe { ptr::read(&b.1) };
745 (Unique::from(Box::leak(b)), alloc)
746 }
747
748 /// Returns a reference to the underlying allocator.
749 ///
750 /// Note: this is an associated function, which means that you have
fc512014 751 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
29967ef6
XL
752 /// is so that there is no conflict with a method on the inner type.
753 #[unstable(feature = "allocator_api", issue = "32838")]
754 #[inline]
fc512014 755 pub fn allocator(b: &Self) -> &A {
29967ef6 756 &b.1
3b2f2976 757 }
ff7c6d11
XL
758
759 /// Consumes and leaks the `Box`, returning a mutable reference,
8faf50e0
XL
760 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
761 /// `'a`. If the type has only static references, or none at all, then this
762 /// may be chosen to be `'static`.
ff7c6d11
XL
763 ///
764 /// This function is mainly useful for data that lives for the remainder of
765 /// the program's life. Dropping the returned reference will cause a memory
766 /// leak. If this is not acceptable, the reference should first be wrapped
767 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
768 /// then be dropped which will properly destroy `T` and release the
769 /// allocated memory.
770 ///
771 /// Note: this is an associated function, which means that you have
772 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
773 /// is so that there is no conflict with a method on the inner type.
774 ///
ff7c6d11
XL
775 /// # Examples
776 ///
777 /// Simple usage:
778 ///
779 /// ```
e74abb32
XL
780 /// let x = Box::new(41);
781 /// let static_ref: &'static mut usize = Box::leak(x);
782 /// *static_ref += 1;
783 /// assert_eq!(*static_ref, 42);
ff7c6d11
XL
784 /// ```
785 ///
786 /// Unsized data:
787 ///
788 /// ```
e74abb32
XL
789 /// let x = vec![1, 2, 3].into_boxed_slice();
790 /// let static_ref = Box::leak(x);
791 /// static_ref[0] = 4;
792 /// assert_eq!(*static_ref, [4, 2, 3]);
ff7c6d11 793 /// ```
0531ce1d 794 #[stable(feature = "box_leak", since = "1.26.0")]
ff7c6d11 795 #[inline]
29967ef6 796 pub fn leak<'a>(b: Self) -> &'a mut T
ff7c6d11 797 where
29967ef6 798 A: 'a,
ff7c6d11 799 {
f9f354fc 800 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
ff7c6d11 801 }
0731742a
XL
802
803 /// Converts a `Box<T>` into a `Pin<Box<T>>`
804 ///
805 /// This conversion does not allocate on the heap and happens in place.
806 ///
807 /// This is also available via [`From`].
416331ca 808 #[unstable(feature = "box_into_pin", issue = "62370")]
fc512014
XL
809 pub fn into_pin(boxed: Self) -> Pin<Self>
810 where
811 A: 'static,
812 {
0731742a
XL
813 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
814 // when `T: !Unpin`, so it's safe to pin it directly without any
815 // additional requirements.
816 unsafe { Pin::new_unchecked(boxed) }
817 }
85aaf69f
SL
818}
819
32a655c1 820#[stable(feature = "rust1", since = "1.0.0")]
fc512014 821unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
32a655c1
SL
822 fn drop(&mut self) {
823 // FIXME: Do nothing, drop is currently performed by compiler.
824 }
825}
826
85aaf69f 827#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 828impl<T: Default> Default for Box<T> {
9e0c209e 829 /// Creates a `Box<T>`, with the `Default` value for T.
29967ef6
XL
830 fn default() -> Self {
831 box T::default()
b039eaaf 832 }
1a4d82fc
JJ
833}
834
85aaf69f 835#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 836impl<T> Default for Box<[T]> {
29967ef6 837 fn default() -> Self {
b039eaaf
SL
838 Box::<[T; 0]>::new([])
839 }
1a4d82fc
JJ
840}
841
8bb4bdeb
XL
842#[stable(feature = "default_box_extra", since = "1.17.0")]
843impl Default for Box<str> {
29967ef6 844 fn default() -> Self {
7cac9316 845 unsafe { from_boxed_utf8_unchecked(Default::default()) }
8bb4bdeb
XL
846 }
847}
848
85aaf69f 849#[stable(feature = "rust1", since = "1.0.0")]
fc512014 850impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
85aaf69f
SL
851 /// Returns a new box with a `clone()` of this box's contents.
852 ///
853 /// # Examples
854 ///
855 /// ```
856 /// let x = Box::new(5);
857 /// let y = x.clone();
416331ca
XL
858 ///
859 /// // The value is the same
860 /// assert_eq!(x, y);
861 ///
862 /// // But they are unique objects
863 /// assert_ne!(&*x as *const i32, &*y as *const i32);
85aaf69f 864 /// ```
9fa01778 865 #[rustfmt::skip]
1a4d82fc 866 #[inline]
29967ef6
XL
867 fn clone(&self) -> Self {
868 Self::new_in((**self).clone(), self.1.clone())
b039eaaf 869 }
416331ca 870
85aaf69f
SL
871 /// Copies `source`'s contents into `self` without creating a new allocation.
872 ///
873 /// # Examples
874 ///
875 /// ```
876 /// let x = Box::new(5);
877 /// let mut y = Box::new(10);
416331ca 878 /// let yp: *const i32 = &*y;
85aaf69f
SL
879 ///
880 /// y.clone_from(&x);
881 ///
416331ca
XL
882 /// // The value is the same
883 /// assert_eq!(x, y);
884 ///
885 /// // And no allocation occurred
886 /// assert_eq!(yp, &*y);
85aaf69f 887 /// ```
1a4d82fc 888 #[inline]
29967ef6 889 fn clone_from(&mut self, source: &Self) {
1a4d82fc
JJ
890 (**self).clone_from(&(**source));
891 }
892}
893
c1a9b12d
SL
894#[stable(feature = "box_slice_clone", since = "1.3.0")]
895impl Clone for Box<str> {
896 fn clone(&self) -> Self {
dc9dc135
XL
897 // this makes a copy of the data
898 let buf: Box<[u8]> = self.as_bytes().into();
dfeec247 899 unsafe { from_boxed_utf8_unchecked(buf) }
c1a9b12d
SL
900 }
901}
902
85aaf69f 903#[stable(feature = "rust1", since = "1.0.0")]
fc512014 904impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1a4d82fc 905 #[inline]
29967ef6 906 fn eq(&self, other: &Self) -> bool {
b039eaaf
SL
907 PartialEq::eq(&**self, &**other)
908 }
1a4d82fc 909 #[inline]
29967ef6 910 fn ne(&self, other: &Self) -> bool {
b039eaaf
SL
911 PartialEq::ne(&**self, &**other)
912 }
1a4d82fc 913}
85aaf69f 914#[stable(feature = "rust1", since = "1.0.0")]
fc512014 915impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1a4d82fc 916 #[inline]
29967ef6 917 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1a4d82fc
JJ
918 PartialOrd::partial_cmp(&**self, &**other)
919 }
920 #[inline]
29967ef6 921 fn lt(&self, other: &Self) -> bool {
b039eaaf
SL
922 PartialOrd::lt(&**self, &**other)
923 }
1a4d82fc 924 #[inline]
29967ef6 925 fn le(&self, other: &Self) -> bool {
b039eaaf
SL
926 PartialOrd::le(&**self, &**other)
927 }
1a4d82fc 928 #[inline]
29967ef6 929 fn ge(&self, other: &Self) -> bool {
b039eaaf
SL
930 PartialOrd::ge(&**self, &**other)
931 }
1a4d82fc 932 #[inline]
29967ef6 933 fn gt(&self, other: &Self) -> bool {
b039eaaf
SL
934 PartialOrd::gt(&**self, &**other)
935 }
1a4d82fc 936}
85aaf69f 937#[stable(feature = "rust1", since = "1.0.0")]
fc512014 938impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1a4d82fc 939 #[inline]
29967ef6 940 fn cmp(&self, other: &Self) -> Ordering {
1a4d82fc
JJ
941 Ord::cmp(&**self, &**other)
942 }
943}
85aaf69f 944#[stable(feature = "rust1", since = "1.0.0")]
fc512014 945impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1a4d82fc 946
85aaf69f 947#[stable(feature = "rust1", since = "1.0.0")]
fc512014 948impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
0531ce1d 949 fn hash<H: Hasher>(&self, state: &mut H) {
1a4d82fc
JJ
950 (**self).hash(state);
951 }
952}
953
ea8adc8c 954#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
fc512014 955impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
ea8adc8c
XL
956 fn finish(&self) -> u64 {
957 (**self).finish()
958 }
959 fn write(&mut self, bytes: &[u8]) {
960 (**self).write(bytes)
961 }
962 fn write_u8(&mut self, i: u8) {
963 (**self).write_u8(i)
964 }
965 fn write_u16(&mut self, i: u16) {
966 (**self).write_u16(i)
967 }
968 fn write_u32(&mut self, i: u32) {
969 (**self).write_u32(i)
970 }
971 fn write_u64(&mut self, i: u64) {
972 (**self).write_u64(i)
973 }
974 fn write_u128(&mut self, i: u128) {
975 (**self).write_u128(i)
976 }
977 fn write_usize(&mut self, i: usize) {
978 (**self).write_usize(i)
979 }
980 fn write_i8(&mut self, i: i8) {
981 (**self).write_i8(i)
982 }
983 fn write_i16(&mut self, i: i16) {
984 (**self).write_i16(i)
985 }
986 fn write_i32(&mut self, i: i32) {
987 (**self).write_i32(i)
988 }
989 fn write_i64(&mut self, i: i64) {
990 (**self).write_i64(i)
991 }
992 fn write_i128(&mut self, i: i128) {
993 (**self).write_i128(i)
994 }
995 fn write_isize(&mut self, i: isize) {
996 (**self).write_isize(i)
997 }
998}
999
92a42be0
SL
1000#[stable(feature = "from_for_ptrs", since = "1.6.0")]
1001impl<T> From<T> for Box<T> {
0731742a
XL
1002 /// Converts a generic type `T` into a `Box<T>`
1003 ///
1004 /// The conversion allocates on the heap and moves `t`
1005 /// from the stack into it.
1006 ///
1007 /// # Examples
1008 /// ```rust
1009 /// let x = 5;
1010 /// let boxed = Box::new(5);
1011 ///
1012 /// assert_eq!(Box::from(x), boxed);
1013 /// ```
92a42be0
SL
1014 fn from(t: T) -> Self {
1015 Box::new(t)
1016 }
1017}
1018
0731742a 1019#[stable(feature = "pin", since = "1.33.0")]
fc512014
XL
1020impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1021where
1022 A: 'static,
1023{
0731742a
XL
1024 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1025 ///
1026 /// This conversion does not allocate on the heap and happens in place.
29967ef6 1027 fn from(boxed: Box<T, A>) -> Self {
0731742a 1028 Box::into_pin(boxed)
0bf4aa26
XL
1029 }
1030}
1031
8bb4bdeb 1032#[stable(feature = "box_from_slice", since = "1.17.0")]
532ac7d7 1033impl<T: Copy> From<&[T]> for Box<[T]> {
0731742a
XL
1034 /// Converts a `&[T]` into a `Box<[T]>`
1035 ///
1036 /// This conversion allocates on the heap
1037 /// and performs a copy of `slice`.
1038 ///
1039 /// # Examples
1040 /// ```rust
1041 /// // create a &[u8] which will be used to create a Box<[u8]>
1042 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1043 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1044 ///
1045 /// println!("{:?}", boxed_slice);
1046 /// ```
532ac7d7 1047 fn from(slice: &[T]) -> Box<[T]> {
dc9dc135
XL
1048 let len = slice.len();
1049 let buf = RawVec::with_capacity(len);
1050 unsafe {
1051 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
ba9703b0 1052 buf.into_box(slice.len()).assume_init()
dc9dc135 1053 }
8bb4bdeb
XL
1054 }
1055}
1056
f9f354fc
XL
1057#[stable(feature = "box_from_cow", since = "1.45.0")]
1058impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1059 #[inline]
1060 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1061 match cow {
1062 Cow::Borrowed(slice) => Box::from(slice),
1063 Cow::Owned(slice) => Box::from(slice),
1064 }
1065 }
1066}
1067
8bb4bdeb 1068#[stable(feature = "box_from_slice", since = "1.17.0")]
532ac7d7 1069impl From<&str> for Box<str> {
0731742a
XL
1070 /// Converts a `&str` into a `Box<str>`
1071 ///
1072 /// This conversion allocates on the heap
1073 /// and performs a copy of `s`.
1074 ///
1075 /// # Examples
1076 /// ```rust
1077 /// let boxed: Box<str> = Box::from("hello");
1078 /// println!("{}", boxed);
1079 /// ```
83c7162d 1080 #[inline]
532ac7d7 1081 fn from(s: &str) -> Box<str> {
7cac9316
XL
1082 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1083 }
1084}
1085
f9f354fc
XL
1086#[stable(feature = "box_from_cow", since = "1.45.0")]
1087impl From<Cow<'_, str>> for Box<str> {
1088 #[inline]
1089 fn from(cow: Cow<'_, str>) -> Box<str> {
1090 match cow {
1091 Cow::Borrowed(s) => Box::from(s),
1092 Cow::Owned(s) => Box::from(s),
1093 }
1094 }
1095}
1096
7cac9316 1097#[stable(feature = "boxed_str_conv", since = "1.19.0")]
fc512014 1098impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
29967ef6 1099 /// Converts a `Box<str>` into a `Box<[u8]>`
0731742a
XL
1100 ///
1101 /// This conversion does not allocate on the heap and happens in place.
1102 ///
1103 /// # Examples
1104 /// ```rust
1105 /// // create a Box<str> which will be used to create a Box<[u8]>
1106 /// let boxed: Box<str> = Box::from("hello");
1107 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1108 ///
1109 /// // create a &[u8] which will be used to create a Box<[u8]>
1110 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1111 /// let boxed_slice = Box::from(slice);
1112 ///
1113 /// assert_eq!(boxed_slice, boxed_str);
1114 /// ```
83c7162d 1115 #[inline]
29967ef6 1116 fn from(s: Box<str, A>) -> Self {
fc512014 1117 let (raw, alloc) = Box::into_raw_with_allocator(s);
29967ef6 1118 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
8bb4bdeb
XL
1119 }
1120}
1121
f9f354fc 1122#[stable(feature = "box_from_array", since = "1.45.0")]
3dfed10e 1123impl<T, const N: usize> From<[T; N]> for Box<[T]> {
f9f354fc
XL
1124 /// Converts a `[T; N]` into a `Box<[T]>`
1125 ///
1126 /// This conversion moves the array to newly heap-allocated memory.
1127 ///
1128 /// # Examples
1129 /// ```rust
1130 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1131 /// println!("{:?}", boxed);
1132 /// ```
1133 fn from(array: [T; N]) -> Box<[T]> {
1134 box array
1135 }
1136}
1137
74b04a01 1138#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
3dfed10e 1139impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
416331ca
XL
1140 type Error = Box<[T]>;
1141
1142 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1143 if boxed_slice.len() == N {
1144 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1145 } else {
1146 Err(boxed_slice)
1147 }
1148 }
1149}
1150
fc512014 1151impl<A: Allocator> Box<dyn Any, A> {
1a4d82fc 1152 #[inline]
c34b1796 1153 #[stable(feature = "rust1", since = "1.0.0")]
bd371182 1154 /// Attempt to downcast the box to a concrete type.
5bcae85e
SL
1155 ///
1156 /// # Examples
1157 ///
1158 /// ```
1159 /// use std::any::Any;
1160 ///
a1dfa0c6 1161 /// fn print_if_string(value: Box<dyn Any>) {
5bcae85e
SL
1162 /// if let Ok(string) = value.downcast::<String>() {
1163 /// println!("String ({}): {}", string.len(), string);
1164 /// }
1165 /// }
1166 ///
e74abb32
XL
1167 /// let my_string = "Hello World".to_string();
1168 /// print_if_string(Box::new(my_string));
1169 /// print_if_string(Box::new(0i8));
5bcae85e 1170 /// ```
29967ef6 1171 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1a4d82fc
JJ
1172 if self.is::<T>() {
1173 unsafe {
fc512014 1174 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
29967ef6 1175 Ok(Box::from_raw_in(raw as *mut T, alloc))
1a4d82fc
JJ
1176 }
1177 } else {
1178 Err(self)
1179 }
1180 }
1181}
1182
fc512014 1183impl<A: Allocator> Box<dyn Any + Send, A> {
c34b1796
AL
1184 #[inline]
1185 #[stable(feature = "rust1", since = "1.0.0")]
bd371182 1186 /// Attempt to downcast the box to a concrete type.
5bcae85e
SL
1187 ///
1188 /// # Examples
1189 ///
1190 /// ```
1191 /// use std::any::Any;
1192 ///
a1dfa0c6 1193 /// fn print_if_string(value: Box<dyn Any + Send>) {
5bcae85e
SL
1194 /// if let Ok(string) = value.downcast::<String>() {
1195 /// println!("String ({}): {}", string.len(), string);
1196 /// }
1197 /// }
1198 ///
e74abb32
XL
1199 /// let my_string = "Hello World".to_string();
1200 /// print_if_string(Box::new(my_string));
1201 /// print_if_string(Box::new(0i8));
5bcae85e 1202 /// ```
29967ef6
XL
1203 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1204 if self.is::<T>() {
1205 unsafe {
fc512014 1206 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
29967ef6
XL
1207 Ok(Box::from_raw_in(raw as *mut T, alloc))
1208 }
1209 } else {
1210 Err(self)
1211 }
c34b1796
AL
1212 }
1213}
1214
85aaf69f 1215#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1216impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
9fa01778 1217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85aaf69f 1218 fmt::Display::fmt(&**self, f)
1a4d82fc
JJ
1219 }
1220}
1221
85aaf69f 1222#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1223impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
9fa01778 1224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85aaf69f 1225 fmt::Debug::fmt(&**self, f)
1a4d82fc
JJ
1226 }
1227}
1228
9346a6ac 1229#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1230impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
9fa01778 1231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9346a6ac
AL
1232 // It's not possible to extract the inner Uniq directly from the Box,
1233 // instead we cast it to a *const which aliases the Unique
1234 let ptr: *const T = &**self;
1235 fmt::Pointer::fmt(&ptr, f)
1236 }
1237}
1238
85aaf69f 1239#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1240impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1a4d82fc
JJ
1241 type Target = T;
1242
b039eaaf
SL
1243 fn deref(&self) -> &T {
1244 &**self
1245 }
1a4d82fc
JJ
1246}
1247
85aaf69f 1248#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1249impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
b039eaaf
SL
1250 fn deref_mut(&mut self) -> &mut T {
1251 &mut **self
1252 }
1a4d82fc
JJ
1253}
1254
dfeec247 1255#[unstable(feature = "receiver_trait", issue = "none")]
fc512014 1256impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
0731742a 1257
85aaf69f 1258#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1259impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
85aaf69f 1260 type Item = I::Item;
b039eaaf
SL
1261 fn next(&mut self) -> Option<I::Item> {
1262 (**self).next()
1263 }
1264 fn size_hint(&self) -> (usize, Option<usize>) {
1265 (**self).size_hint()
1266 }
476ff2be
SL
1267 fn nth(&mut self, n: usize) -> Option<I::Item> {
1268 (**self).nth(n)
1269 }
e74abb32
XL
1270 fn last(self) -> Option<I::Item> {
1271 BoxIter::last(self)
1272 }
1273}
1274
1275trait BoxIter {
1276 type Item;
1277 fn last(self) -> Option<Self::Item>;
1278}
1279
fc512014 1280impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
e74abb32
XL
1281 type Item = I::Item;
1282 default fn last(self) -> Option<I::Item> {
1283 #[inline]
1284 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1285 Some(x)
1286 }
1287
1288 self.fold(None, some)
1289 }
85aaf69f 1290}
416331ca 1291
e74abb32
XL
1292/// Specialization for sized `I`s that uses `I`s implementation of `last()`
1293/// instead of the default.
416331ca 1294#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1295impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
e74abb32 1296 fn last(self) -> Option<I::Item> {
416331ca
XL
1297 (*self).last()
1298 }
1299}
1300
85aaf69f 1301#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1302impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
b039eaaf
SL
1303 fn next_back(&mut self) -> Option<I::Item> {
1304 (**self).next_back()
1305 }
532ac7d7
XL
1306 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1307 (**self).nth_back(n)
1308 }
85aaf69f
SL
1309}
1310#[stable(feature = "rust1", since = "1.0.0")]
fc512014 1311impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
476ff2be
SL
1312 fn len(&self) -> usize {
1313 (**self).len()
1314 }
1315 fn is_empty(&self) -> bool {
1316 (**self).is_empty()
1317 }
1318}
1a4d82fc 1319
0531ce1d 1320#[stable(feature = "fused", since = "1.26.0")]
fc512014 1321impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
9e0c209e 1322
532ac7d7 1323#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
fc512014 1324impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
29967ef6 1325 type Output = <F as FnOnce<Args>>::Output;
532ac7d7 1326
29967ef6
XL
1327 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1328 <F as FnOnce<Args>>::call_once(*self, args)
532ac7d7
XL
1329 }
1330}
1331
1332#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
fc512014 1333impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
29967ef6
XL
1334 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1335 <F as FnMut<Args>>::call_mut(self, args)
532ac7d7
XL
1336 }
1337}
1338
1339#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
fc512014 1340impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
29967ef6
XL
1341 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1342 <F as Fn<Args>>::call(self, args)
532ac7d7
XL
1343 }
1344}
c34b1796 1345
92a42be0 1346#[unstable(feature = "coerce_unsized", issue = "27732")]
fc512014 1347impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
c1a9b12d 1348
dfeec247 1349#[unstable(feature = "dispatch_from_dyn", issue = "none")]
29967ef6 1350impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
a1dfa0c6
XL
1351
1352#[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
29967ef6
XL
1353impl<I> FromIterator<I> for Box<[I]> {
1354 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
a1dfa0c6
XL
1355 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1356 }
1357}
1358
c1a9b12d 1359#[stable(feature = "box_slice_clone", since = "1.3.0")]
fc512014 1360impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
c1a9b12d 1361 fn clone(&self) -> Self {
fc512014
XL
1362 let alloc = Box::allocator(self).clone();
1363 self.to_vec_in(alloc).into_boxed_slice()
c1a9b12d 1364 }
f9f354fc
XL
1365
1366 fn clone_from(&mut self, other: &Self) {
1367 if self.len() == other.len() {
1368 self.clone_from_slice(&other);
1369 } else {
1370 *self = other.clone();
1371 }
1372 }
c1a9b12d
SL
1373}
1374
041b39d2 1375#[stable(feature = "box_borrow", since = "1.1.0")]
fc512014 1376impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
b039eaaf
SL
1377 fn borrow(&self) -> &T {
1378 &**self
1379 }
e9174d1e
SL
1380}
1381
041b39d2 1382#[stable(feature = "box_borrow", since = "1.1.0")]
fc512014 1383impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
b039eaaf
SL
1384 fn borrow_mut(&mut self) -> &mut T {
1385 &mut **self
1386 }
1387}
1388
1389#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
fc512014 1390impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
b039eaaf
SL
1391 fn as_ref(&self) -> &T {
1392 &**self
1393 }
1394}
1395
1396#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
fc512014 1397impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
b039eaaf
SL
1398 fn as_mut(&mut self) -> &mut T {
1399 &mut **self
1400 }
e9174d1e 1401}
ea8adc8c 1402
b7449926
XL
1403/* Nota bene
1404 *
1405 * We could have chosen not to add this impl, and instead have written a
1406 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1407 * because Box<T> implements Unpin even when T does not, as a result of
1408 * this impl.
1409 *
1410 * We chose this API instead of the alternative for a few reasons:
1411 * - Logically, it is helpful to understand pinning in regard to the
1412 * memory region being pointed to. For this reason none of the
1413 * standard library pointer types support projecting through a pin
1414 * (Box<T> is the only pointer type in std for which this would be
1415 * safe.)
1416 * - It is in practice very useful to have Box<T> be unconditionally
1417 * Unpin because of trait objects, for which the structural auto
0731742a 1418 * trait functionality does not apply (e.g., Box<dyn Foo> would
b7449926
XL
1419 * otherwise not be Unpin).
1420 *
1421 * Another type with the same semantics as Box but only a conditional
1422 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1423 * could have a method to project a Pin<T> from it.
1424 */
0731742a 1425#[stable(feature = "pin", since = "1.33.0")]
fc512014 1426impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
b7449926 1427
74b04a01 1428#[unstable(feature = "generator_trait", issue = "43122")]
fc512014
XL
1429impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1430where
1431 A: 'static,
1432{
74b04a01
XL
1433 type Yield = G::Yield;
1434 type Return = G::Return;
1435
1436 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1437 G::resume(Pin::new(&mut *self), arg)
1438 }
1439}
1440
74b04a01 1441#[unstable(feature = "generator_trait", issue = "43122")]
fc512014
XL
1442impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1443where
1444 A: 'static,
1445{
74b04a01
XL
1446 type Yield = G::Yield;
1447 type Return = G::Return;
1448
1449 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1450 G::resume((*self).as_mut(), arg)
1451 }
1452}
1453
48663c56 1454#[stable(feature = "futures_api", since = "1.36.0")]
fc512014
XL
1455impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
1456where
1457 A: 'static,
1458{
94b46f34
XL
1459 type Output = F::Output;
1460
532ac7d7
XL
1461 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1462 F::poll(Pin::new(&mut *self), cx)
94b46f34
XL
1463 }
1464}