]>
Commit | Line | Data |
---|---|---|
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 | //! |
60c5eb7d XL |
65 | //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented |
66 | //! as a single pointer and is also ABI-compatible with C pointers | |
67 | //! (i.e. the C type `T*`). This means that if you have extern "C" | |
68 | //! Rust functions that will be called from C, you can define those | |
69 | //! Rust functions using `Box<T>` types, and use `T*` as corresponding | |
70 | //! type on the C side. As an example, consider this C header which | |
71 | //! declares functions that create and destroy some kind of `Foo` | |
72 | //! value: | |
73 | //! | |
74 | //! ```c | |
75 | //! /* C header */ | |
76 | //! | |
77 | //! /* Returns ownership to the caller */ | |
78 | //! struct Foo* foo_new(void); | |
79 | //! | |
80 | //! /* Takes ownership from the caller; no-op when invoked with NULL */ | |
81 | //! void foo_delete(struct Foo*); | |
82 | //! ``` | |
83 | //! | |
84 | //! These two functions might be implemented in Rust as follows. Here, the | |
85 | //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures | |
86 | //! the ownership constraints. Note also that the nullable argument to | |
87 | //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>` | |
88 | //! cannot be null. | |
89 | //! | |
90 | //! ``` | |
91 | //! #[repr(C)] | |
92 | //! pub struct Foo; | |
93 | //! | |
94 | //! #[no_mangle] | |
95 | //! pub extern "C" fn foo_new() -> Box<Foo> { | |
96 | //! Box::new(Foo) | |
97 | //! } | |
dc9dc135 | 98 | //! |
60c5eb7d XL |
99 | //! #[no_mangle] |
100 | //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {} | |
101 | //! ``` | |
102 | //! | |
103 | //! Even though `Box<T>` has the same representation and C ABI as a C pointer, | |
104 | //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>` | |
105 | //! and expect things to work. `Box<T>` values will always be fully aligned, | |
106 | //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to | |
107 | //! free the value with the global allocator. In general, the best practice | |
108 | //! is to only use `Box<T>` for pointers that originated from the global | |
109 | //! allocator. | |
110 | //! | |
111 | //! **Important.** At least at present, you should avoid using | |
112 | //! `Box<T>` types for functions that are defined in C but invoked | |
113 | //! from Rust. In those cases, you should directly mirror the C types | |
114 | //! as closely as possible. Using types like `Box<T>` where the C | |
115 | //! definition is just using `T*` can lead to undefined behavior, as | |
116 | //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198]. | |
117 | //! | |
118 | //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198 | |
0bf4aa26 XL |
119 | //! [dereferencing]: ../../std/ops/trait.Deref.html |
120 | //! [`Box`]: struct.Box.html | |
416331ca XL |
121 | //! [`Box<T>`]: struct.Box.html |
122 | //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw | |
123 | //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw | |
48663c56 XL |
124 | //! [`Global`]: ../alloc/struct.Global.html |
125 | //! [`Layout`]: ../alloc/struct.Layout.html | |
416331ca | 126 | //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value |
1a4d82fc | 127 | |
85aaf69f SL |
128 | #![stable(feature = "rust1", since = "1.0.0")] |
129 | ||
1a4d82fc | 130 | use core::any::Any; |
416331ca | 131 | use core::array::LengthAtMost32; |
e9174d1e | 132 | use core::borrow; |
85aaf69f | 133 | use core::cmp::Ordering; |
416331ca | 134 | use core::convert::{From, TryFrom}; |
1a4d82fc | 135 | use core::fmt; |
0bf4aa26 | 136 | use core::future::Future; |
0531ce1d | 137 | use core::hash::{Hash, Hasher}; |
dfeec247 | 138 | use core::iter::{FromIterator, FusedIterator, Iterator}; |
83c7162d | 139 | use core::marker::{Unpin, Unsize}; |
b7449926 | 140 | use core::mem; |
0731742a | 141 | use core::ops::{ |
dfeec247 | 142 | CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver, |
0731742a | 143 | }; |
dfeec247 | 144 | use core::pin::Pin; |
2c00a5a8 | 145 | use core::ptr::{self, NonNull, Unique}; |
532ac7d7 | 146 | use core::task::{Context, Poll}; |
c1a9b12d | 147 | |
ba9703b0 | 148 | use crate::alloc::{self, AllocInit, AllocRef, Global}; |
9fa01778 XL |
149 | use crate::raw_vec::RawVec; |
150 | use crate::str::from_boxed_utf8_unchecked; | |
dfeec247 | 151 | use crate::vec::Vec; |
1a4d82fc | 152 | |
85aaf69f SL |
153 | /// A pointer type for heap allocation. |
154 | /// | |
155 | /// See the [module-level documentation](../../std/boxed/index.html) for more. | |
1a4d82fc | 156 | #[lang = "owned_box"] |
32a655c1 | 157 | #[fundamental] |
85aaf69f | 158 | #[stable(feature = "rust1", since = "1.0.0")] |
c1a9b12d SL |
159 | pub struct Box<T: ?Sized>(Unique<T>); |
160 | ||
1a4d82fc | 161 | impl<T> Box<T> { |
9cc50fc6 | 162 | /// Allocates memory on the heap and then places `x` into it. |
85aaf69f | 163 | /// |
8bb4bdeb XL |
164 | /// This doesn't actually allocate if `T` is zero-sized. |
165 | /// | |
85aaf69f SL |
166 | /// # Examples |
167 | /// | |
168 | /// ``` | |
9cc50fc6 | 169 | /// let five = Box::new(5); |
85aaf69f SL |
170 | /// ``` |
171 | #[stable(feature = "rust1", since = "1.0.0")] | |
c34b1796 | 172 | #[inline(always)] |
1a4d82fc JJ |
173 | pub fn new(x: T) -> Box<T> { |
174 | box x | |
175 | } | |
0bf4aa26 | 176 | |
e1599b0c XL |
177 | /// Constructs a new box with uninitialized contents. |
178 | /// | |
179 | /// # Examples | |
180 | /// | |
181 | /// ``` | |
182 | /// #![feature(new_uninit)] | |
183 | /// | |
184 | /// let mut five = Box::<u32>::new_uninit(); | |
185 | /// | |
186 | /// let five = unsafe { | |
187 | /// // Deferred initialization: | |
188 | /// five.as_mut_ptr().write(5); | |
189 | /// | |
190 | /// five.assume_init() | |
191 | /// }; | |
192 | /// | |
193 | /// assert_eq!(*five, 5) | |
194 | /// ``` | |
195 | #[unstable(feature = "new_uninit", issue = "63291")] | |
196 | pub fn new_uninit() -> Box<mem::MaybeUninit<T>> { | |
197 | let layout = alloc::Layout::new::<mem::MaybeUninit<T>>(); | |
ba9703b0 XL |
198 | let ptr = Global |
199 | .alloc(layout, AllocInit::Uninitialized) | |
200 | .unwrap_or_else(|_| alloc::handle_alloc_error(layout)) | |
201 | .ptr | |
202 | .cast(); | |
203 | unsafe { Box::from_raw(ptr.as_ptr()) } | |
e1599b0c XL |
204 | } |
205 | ||
60c5eb7d XL |
206 | /// Constructs a new `Box` with uninitialized contents, with the memory |
207 | /// being filled with `0` bytes. | |
208 | /// | |
209 | /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage | |
210 | /// of this method. | |
211 | /// | |
212 | /// # Examples | |
213 | /// | |
214 | /// ``` | |
215 | /// #![feature(new_uninit)] | |
216 | /// | |
217 | /// let zero = Box::<u32>::new_zeroed(); | |
218 | /// let zero = unsafe { zero.assume_init() }; | |
219 | /// | |
220 | /// assert_eq!(*zero, 0) | |
221 | /// ``` | |
222 | /// | |
223 | /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed | |
224 | #[unstable(feature = "new_uninit", issue = "63291")] | |
225 | pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> { | |
ba9703b0 XL |
226 | let layout = alloc::Layout::new::<mem::MaybeUninit<T>>(); |
227 | let ptr = Global | |
228 | .alloc(layout, AllocInit::Zeroed) | |
229 | .unwrap_or_else(|_| alloc::handle_alloc_error(layout)) | |
230 | .ptr | |
231 | .cast(); | |
232 | unsafe { Box::from_raw(ptr.as_ptr()) } | |
60c5eb7d XL |
233 | } |
234 | ||
0731742a XL |
235 | /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then |
236 | /// `x` will be pinned in memory and unable to be moved. | |
237 | #[stable(feature = "pin", since = "1.33.0")] | |
0bf4aa26 | 238 | #[inline(always)] |
0731742a | 239 | pub fn pin(x: T) -> Pin<Box<T>> { |
0bf4aa26 XL |
240 | (box x).into() |
241 | } | |
1a4d82fc JJ |
242 | } |
243 | ||
e1599b0c XL |
244 | impl<T> Box<[T]> { |
245 | /// Constructs a new boxed slice with uninitialized contents. | |
246 | /// | |
247 | /// # Examples | |
248 | /// | |
249 | /// ``` | |
250 | /// #![feature(new_uninit)] | |
251 | /// | |
252 | /// let mut values = Box::<[u32]>::new_uninit_slice(3); | |
253 | /// | |
254 | /// let values = unsafe { | |
255 | /// // Deferred initialization: | |
256 | /// values[0].as_mut_ptr().write(1); | |
257 | /// values[1].as_mut_ptr().write(2); | |
258 | /// values[2].as_mut_ptr().write(3); | |
259 | /// | |
260 | /// values.assume_init() | |
261 | /// }; | |
262 | /// | |
263 | /// assert_eq!(*values, [1, 2, 3]) | |
264 | /// ``` | |
265 | #[unstable(feature = "new_uninit", issue = "63291")] | |
266 | pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> { | |
ba9703b0 | 267 | unsafe { RawVec::with_capacity(len).into_box(len) } |
e1599b0c XL |
268 | } |
269 | } | |
270 | ||
271 | impl<T> Box<mem::MaybeUninit<T>> { | |
272 | /// Converts to `Box<T>`. | |
273 | /// | |
274 | /// # Safety | |
275 | /// | |
276 | /// As with [`MaybeUninit::assume_init`], | |
277 | /// it is up to the caller to guarantee that the value | |
278 | /// really is in an initialized state. | |
279 | /// Calling this when the content is not yet fully initialized | |
280 | /// causes immediate undefined behavior. | |
281 | /// | |
282 | /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init | |
283 | /// | |
284 | /// # Examples | |
285 | /// | |
286 | /// ``` | |
287 | /// #![feature(new_uninit)] | |
288 | /// | |
289 | /// let mut five = Box::<u32>::new_uninit(); | |
290 | /// | |
291 | /// let five: Box<u32> = unsafe { | |
292 | /// // Deferred initialization: | |
293 | /// five.as_mut_ptr().write(5); | |
294 | /// | |
295 | /// five.assume_init() | |
296 | /// }; | |
297 | /// | |
298 | /// assert_eq!(*five, 5) | |
299 | /// ``` | |
300 | #[unstable(feature = "new_uninit", issue = "63291")] | |
301 | #[inline] | |
302 | pub unsafe fn assume_init(self) -> Box<T> { | |
74b04a01 | 303 | Box::from_raw(Box::into_raw(self) as *mut T) |
e1599b0c XL |
304 | } |
305 | } | |
306 | ||
307 | impl<T> Box<[mem::MaybeUninit<T>]> { | |
308 | /// Converts to `Box<[T]>`. | |
309 | /// | |
310 | /// # Safety | |
311 | /// | |
312 | /// As with [`MaybeUninit::assume_init`], | |
313 | /// it is up to the caller to guarantee that the values | |
314 | /// really are in an initialized state. | |
315 | /// Calling this when the content is not yet fully initialized | |
316 | /// causes immediate undefined behavior. | |
317 | /// | |
318 | /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init | |
319 | /// | |
320 | /// # Examples | |
321 | /// | |
322 | /// ``` | |
323 | /// #![feature(new_uninit)] | |
324 | /// | |
325 | /// let mut values = Box::<[u32]>::new_uninit_slice(3); | |
326 | /// | |
327 | /// let values = unsafe { | |
328 | /// // Deferred initialization: | |
329 | /// values[0].as_mut_ptr().write(1); | |
330 | /// values[1].as_mut_ptr().write(2); | |
331 | /// values[2].as_mut_ptr().write(3); | |
332 | /// | |
333 | /// values.assume_init() | |
334 | /// }; | |
335 | /// | |
336 | /// assert_eq!(*values, [1, 2, 3]) | |
337 | /// ``` | |
338 | #[unstable(feature = "new_uninit", issue = "63291")] | |
339 | #[inline] | |
340 | pub unsafe fn assume_init(self) -> Box<[T]> { | |
74b04a01 | 341 | Box::from_raw(Box::into_raw(self) as *mut [T]) |
e1599b0c XL |
342 | } |
343 | } | |
344 | ||
92a42be0 | 345 | impl<T: ?Sized> Box<T> { |
9cc50fc6 | 346 | /// Constructs a box from a raw pointer. |
85aaf69f | 347 | /// |
9cc50fc6 SL |
348 | /// After calling this function, the raw pointer is owned by the |
349 | /// resulting `Box`. Specifically, the `Box` destructor will call | |
dc9dc135 XL |
350 | /// the destructor of `T` and free the allocated memory. For this |
351 | /// to be safe, the memory must have been allocated in accordance | |
352 | /// with the [memory layout] used by `Box` . | |
353 | /// | |
354 | /// # Safety | |
85aaf69f | 355 | /// |
9cc50fc6 SL |
356 | /// This function is unsafe because improper use may lead to |
357 | /// memory problems. For example, a double-free may occur if the | |
85aaf69f | 358 | /// function is called twice on the same raw pointer. |
5bcae85e SL |
359 | /// |
360 | /// # Examples | |
dc9dc135 XL |
361 | /// Recreate a `Box` which was previously converted to a raw pointer |
362 | /// using [`Box::into_raw`]: | |
5bcae85e SL |
363 | /// ``` |
364 | /// let x = Box::new(5); | |
365 | /// let ptr = Box::into_raw(x); | |
366 | /// let x = unsafe { Box::from_raw(ptr) }; | |
367 | /// ``` | |
dc9dc135 XL |
368 | /// Manually create a `Box` from scratch by using the global allocator: |
369 | /// ``` | |
370 | /// use std::alloc::{alloc, Layout}; | |
371 | /// | |
372 | /// unsafe { | |
373 | /// let ptr = alloc(Layout::new::<i32>()) as *mut i32; | |
374 | /// *ptr = 5; | |
375 | /// let x = Box::from_raw(ptr); | |
376 | /// } | |
377 | /// ``` | |
378 | /// | |
379 | /// [memory layout]: index.html#memory-layout | |
380 | /// [`Layout`]: ../alloc/struct.Layout.html | |
381 | /// [`Box::into_raw`]: struct.Box.html#method.into_raw | |
e9174d1e | 382 | #[stable(feature = "box_raw", since = "1.4.0")] |
c34b1796 | 383 | #[inline] |
85aaf69f | 384 | pub unsafe fn from_raw(raw: *mut T) -> Self { |
2c00a5a8 | 385 | Box(Unique::new_unchecked(raw)) |
85aaf69f | 386 | } |
62682a34 | 387 | |
b7449926 XL |
388 | /// Consumes the `Box`, returning a wrapped raw pointer. |
389 | /// | |
390 | /// The pointer will be properly aligned and non-null. | |
62682a34 | 391 | /// |
9cc50fc6 SL |
392 | /// After calling this function, the caller is responsible for the |
393 | /// memory previously managed by the `Box`. In particular, the | |
dc9dc135 XL |
394 | /// caller should properly destroy `T` and release the memory, taking |
395 | /// into account the [memory layout] used by `Box`. The easiest way to | |
396 | /// do this is to convert the raw pointer back into a `Box` with the | |
397 | /// [`Box::from_raw`] function, allowing the `Box` destructor to perform | |
398 | /// the cleanup. | |
62682a34 | 399 | /// |
9e0c209e SL |
400 | /// Note: this is an associated function, which means that you have |
401 | /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This | |
402 | /// is so that there is no conflict with a method on the inner type. | |
403 | /// | |
62682a34 | 404 | /// # Examples |
dc9dc135 XL |
405 | /// Converting the raw pointer back into a `Box` with [`Box::from_raw`] |
406 | /// for automatic cleanup: | |
e9174d1e | 407 | /// ``` |
dc9dc135 | 408 | /// let x = Box::new(String::from("Hello")); |
5bcae85e | 409 | /// let ptr = Box::into_raw(x); |
dc9dc135 XL |
410 | /// let x = unsafe { Box::from_raw(ptr) }; |
411 | /// ``` | |
412 | /// Manual cleanup by explicitly running the destructor and deallocating | |
413 | /// the memory: | |
62682a34 | 414 | /// ``` |
dc9dc135 XL |
415 | /// use std::alloc::{dealloc, Layout}; |
416 | /// use std::ptr; | |
417 | /// | |
418 | /// let x = Box::new(String::from("Hello")); | |
419 | /// let p = Box::into_raw(x); | |
420 | /// unsafe { | |
421 | /// ptr::drop_in_place(p); | |
422 | /// dealloc(p as *mut u8, Layout::new::<String>()); | |
423 | /// } | |
424 | /// ``` | |
425 | /// | |
426 | /// [memory layout]: index.html#memory-layout | |
427 | /// [`Box::from_raw`]: struct.Box.html#method.from_raw | |
e9174d1e | 428 | #[stable(feature = "box_raw", since = "1.4.0")] |
62682a34 | 429 | #[inline] |
62682a34 | 430 | pub fn into_raw(b: Box<T>) -> *mut T { |
2c00a5a8 | 431 | Box::into_raw_non_null(b).as_ptr() |
62682a34 | 432 | } |
3b2f2976 | 433 | |
2c00a5a8 | 434 | /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`. |
3b2f2976 XL |
435 | /// |
436 | /// After calling this function, the caller is responsible for the | |
437 | /// memory previously managed by the `Box`. In particular, the | |
438 | /// caller should properly destroy `T` and release the memory. The | |
dc9dc135 | 439 | /// easiest way to do so is to convert the `NonNull<T>` pointer |
2c00a5a8 XL |
440 | /// into a raw pointer and back into a `Box` with the [`Box::from_raw`] |
441 | /// function. | |
3b2f2976 XL |
442 | /// |
443 | /// Note: this is an associated function, which means that you have | |
2c00a5a8 XL |
444 | /// to call it as `Box::into_raw_non_null(b)` |
445 | /// instead of `b.into_raw_non_null()`. This | |
3b2f2976 XL |
446 | /// is so that there is no conflict with a method on the inner type. |
447 | /// | |
448 | /// [`Box::from_raw`]: struct.Box.html#method.from_raw | |
449 | /// | |
450 | /// # Examples | |
451 | /// | |
452 | /// ``` | |
2c00a5a8 | 453 | /// #![feature(box_into_raw_non_null)] |
3b2f2976 | 454 | /// |
e74abb32 XL |
455 | /// let x = Box::new(5); |
456 | /// let ptr = Box::into_raw_non_null(x); | |
dc9dc135 | 457 | /// |
e74abb32 XL |
458 | /// // Clean up the memory by converting the NonNull pointer back |
459 | /// // into a Box and letting the Box be dropped. | |
460 | /// let x = unsafe { Box::from_raw(ptr.as_ptr()) }; | |
3b2f2976 | 461 | /// ``` |
2c00a5a8 XL |
462 | #[unstable(feature = "box_into_raw_non_null", issue = "47336")] |
463 | #[inline] | |
464 | pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> { | |
465 | Box::into_unique(b).into() | |
466 | } | |
467 | ||
dfeec247 | 468 | #[unstable(feature = "ptr_internals", issue = "none", reason = "use into_raw_non_null instead")] |
3b2f2976 | 469 | #[inline] |
83c7162d | 470 | #[doc(hidden)] |
dc9dc135 | 471 | pub fn into_unique(b: Box<T>) -> Unique<T> { |
ba9703b0 | 472 | let b = mem::ManuallyDrop::new(b); |
dc9dc135 | 473 | let mut unique = b.0; |
9fa01778 XL |
474 | // Box is kind-of a library type, but recognized as a "unique pointer" by |
475 | // Stacked Borrows. This function here corresponds to "reborrowing to | |
476 | // a raw pointer", but there is no actual reborrow here -- so | |
477 | // without some care, the pointer we are returning here still carries | |
dc9dc135 XL |
478 | // the tag of `b`, with `Unique` permission. |
479 | // We round-trip through a mutable reference to avoid that. | |
480 | unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) } | |
3b2f2976 | 481 | } |
ff7c6d11 XL |
482 | |
483 | /// Consumes and leaks the `Box`, returning a mutable reference, | |
8faf50e0 XL |
484 | /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime |
485 | /// `'a`. If the type has only static references, or none at all, then this | |
486 | /// may be chosen to be `'static`. | |
ff7c6d11 XL |
487 | /// |
488 | /// This function is mainly useful for data that lives for the remainder of | |
489 | /// the program's life. Dropping the returned reference will cause a memory | |
490 | /// leak. If this is not acceptable, the reference should first be wrapped | |
491 | /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can | |
492 | /// then be dropped which will properly destroy `T` and release the | |
493 | /// allocated memory. | |
494 | /// | |
495 | /// Note: this is an associated function, which means that you have | |
496 | /// to call it as `Box::leak(b)` instead of `b.leak()`. This | |
497 | /// is so that there is no conflict with a method on the inner type. | |
498 | /// | |
499 | /// [`Box::from_raw`]: struct.Box.html#method.from_raw | |
500 | /// | |
501 | /// # Examples | |
502 | /// | |
503 | /// Simple usage: | |
504 | /// | |
505 | /// ``` | |
e74abb32 XL |
506 | /// let x = Box::new(41); |
507 | /// let static_ref: &'static mut usize = Box::leak(x); | |
508 | /// *static_ref += 1; | |
509 | /// assert_eq!(*static_ref, 42); | |
ff7c6d11 XL |
510 | /// ``` |
511 | /// | |
512 | /// Unsized data: | |
513 | /// | |
514 | /// ``` | |
e74abb32 XL |
515 | /// let x = vec![1, 2, 3].into_boxed_slice(); |
516 | /// let static_ref = Box::leak(x); | |
517 | /// static_ref[0] = 4; | |
518 | /// assert_eq!(*static_ref, [4, 2, 3]); | |
ff7c6d11 | 519 | /// ``` |
0531ce1d | 520 | #[stable(feature = "box_leak", since = "1.26.0")] |
ff7c6d11 XL |
521 | #[inline] |
522 | pub fn leak<'a>(b: Box<T>) -> &'a mut T | |
523 | where | |
dfeec247 | 524 | T: 'a, // Technically not needed, but kept to be explicit. |
ff7c6d11 XL |
525 | { |
526 | unsafe { &mut *Box::into_raw(b) } | |
527 | } | |
0731742a XL |
528 | |
529 | /// Converts a `Box<T>` into a `Pin<Box<T>>` | |
530 | /// | |
531 | /// This conversion does not allocate on the heap and happens in place. | |
532 | /// | |
533 | /// This is also available via [`From`]. | |
416331ca | 534 | #[unstable(feature = "box_into_pin", issue = "62370")] |
0731742a XL |
535 | pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> { |
536 | // It's not possible to move or replace the insides of a `Pin<Box<T>>` | |
537 | // when `T: !Unpin`, so it's safe to pin it directly without any | |
538 | // additional requirements. | |
539 | unsafe { Pin::new_unchecked(boxed) } | |
540 | } | |
85aaf69f SL |
541 | } |
542 | ||
32a655c1 SL |
543 | #[stable(feature = "rust1", since = "1.0.0")] |
544 | unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> { | |
545 | fn drop(&mut self) { | |
546 | // FIXME: Do nothing, drop is currently performed by compiler. | |
547 | } | |
548 | } | |
549 | ||
85aaf69f | 550 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 551 | impl<T: Default> Default for Box<T> { |
9e0c209e | 552 | /// Creates a `Box<T>`, with the `Default` value for T. |
b039eaaf SL |
553 | fn default() -> Box<T> { |
554 | box Default::default() | |
555 | } | |
1a4d82fc JJ |
556 | } |
557 | ||
85aaf69f | 558 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 559 | impl<T> Default for Box<[T]> { |
b039eaaf SL |
560 | fn default() -> Box<[T]> { |
561 | Box::<[T; 0]>::new([]) | |
562 | } | |
1a4d82fc JJ |
563 | } |
564 | ||
8bb4bdeb XL |
565 | #[stable(feature = "default_box_extra", since = "1.17.0")] |
566 | impl Default for Box<str> { | |
567 | fn default() -> Box<str> { | |
7cac9316 | 568 | unsafe { from_boxed_utf8_unchecked(Default::default()) } |
8bb4bdeb XL |
569 | } |
570 | } | |
571 | ||
85aaf69f | 572 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 573 | impl<T: Clone> Clone for Box<T> { |
85aaf69f SL |
574 | /// Returns a new box with a `clone()` of this box's contents. |
575 | /// | |
576 | /// # Examples | |
577 | /// | |
578 | /// ``` | |
579 | /// let x = Box::new(5); | |
580 | /// let y = x.clone(); | |
416331ca XL |
581 | /// |
582 | /// // The value is the same | |
583 | /// assert_eq!(x, y); | |
584 | /// | |
585 | /// // But they are unique objects | |
586 | /// assert_ne!(&*x as *const i32, &*y as *const i32); | |
85aaf69f | 587 | /// ``` |
9fa01778 | 588 | #[rustfmt::skip] |
1a4d82fc | 589 | #[inline] |
b039eaaf SL |
590 | fn clone(&self) -> Box<T> { |
591 | box { (**self).clone() } | |
592 | } | |
416331ca | 593 | |
85aaf69f SL |
594 | /// Copies `source`'s contents into `self` without creating a new allocation. |
595 | /// | |
596 | /// # Examples | |
597 | /// | |
598 | /// ``` | |
599 | /// let x = Box::new(5); | |
600 | /// let mut y = Box::new(10); | |
416331ca | 601 | /// let yp: *const i32 = &*y; |
85aaf69f SL |
602 | /// |
603 | /// y.clone_from(&x); | |
604 | /// | |
416331ca XL |
605 | /// // The value is the same |
606 | /// assert_eq!(x, y); | |
607 | /// | |
608 | /// // And no allocation occurred | |
609 | /// assert_eq!(yp, &*y); | |
85aaf69f | 610 | /// ``` |
1a4d82fc JJ |
611 | #[inline] |
612 | fn clone_from(&mut self, source: &Box<T>) { | |
613 | (**self).clone_from(&(**source)); | |
614 | } | |
615 | } | |
616 | ||
c1a9b12d SL |
617 | #[stable(feature = "box_slice_clone", since = "1.3.0")] |
618 | impl Clone for Box<str> { | |
619 | fn clone(&self) -> Self { | |
dc9dc135 XL |
620 | // this makes a copy of the data |
621 | let buf: Box<[u8]> = self.as_bytes().into(); | |
dfeec247 | 622 | unsafe { from_boxed_utf8_unchecked(buf) } |
c1a9b12d SL |
623 | } |
624 | } | |
625 | ||
85aaf69f | 626 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
627 | impl<T: ?Sized + PartialEq> PartialEq for Box<T> { |
628 | #[inline] | |
b039eaaf SL |
629 | fn eq(&self, other: &Box<T>) -> bool { |
630 | PartialEq::eq(&**self, &**other) | |
631 | } | |
1a4d82fc | 632 | #[inline] |
b039eaaf SL |
633 | fn ne(&self, other: &Box<T>) -> bool { |
634 | PartialEq::ne(&**self, &**other) | |
635 | } | |
1a4d82fc | 636 | } |
85aaf69f | 637 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
638 | impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> { |
639 | #[inline] | |
640 | fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { | |
641 | PartialOrd::partial_cmp(&**self, &**other) | |
642 | } | |
643 | #[inline] | |
b039eaaf SL |
644 | fn lt(&self, other: &Box<T>) -> bool { |
645 | PartialOrd::lt(&**self, &**other) | |
646 | } | |
1a4d82fc | 647 | #[inline] |
b039eaaf SL |
648 | fn le(&self, other: &Box<T>) -> bool { |
649 | PartialOrd::le(&**self, &**other) | |
650 | } | |
1a4d82fc | 651 | #[inline] |
b039eaaf SL |
652 | fn ge(&self, other: &Box<T>) -> bool { |
653 | PartialOrd::ge(&**self, &**other) | |
654 | } | |
1a4d82fc | 655 | #[inline] |
b039eaaf SL |
656 | fn gt(&self, other: &Box<T>) -> bool { |
657 | PartialOrd::gt(&**self, &**other) | |
658 | } | |
1a4d82fc | 659 | } |
85aaf69f | 660 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
661 | impl<T: ?Sized + Ord> Ord for Box<T> { |
662 | #[inline] | |
663 | fn cmp(&self, other: &Box<T>) -> Ordering { | |
664 | Ord::cmp(&**self, &**other) | |
665 | } | |
666 | } | |
85aaf69f | 667 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
668 | impl<T: ?Sized + Eq> Eq for Box<T> {} |
669 | ||
85aaf69f SL |
670 | #[stable(feature = "rust1", since = "1.0.0")] |
671 | impl<T: ?Sized + Hash> Hash for Box<T> { | |
0531ce1d | 672 | fn hash<H: Hasher>(&self, state: &mut H) { |
1a4d82fc JJ |
673 | (**self).hash(state); |
674 | } | |
675 | } | |
676 | ||
ea8adc8c XL |
677 | #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] |
678 | impl<T: ?Sized + Hasher> Hasher for Box<T> { | |
679 | fn finish(&self) -> u64 { | |
680 | (**self).finish() | |
681 | } | |
682 | fn write(&mut self, bytes: &[u8]) { | |
683 | (**self).write(bytes) | |
684 | } | |
685 | fn write_u8(&mut self, i: u8) { | |
686 | (**self).write_u8(i) | |
687 | } | |
688 | fn write_u16(&mut self, i: u16) { | |
689 | (**self).write_u16(i) | |
690 | } | |
691 | fn write_u32(&mut self, i: u32) { | |
692 | (**self).write_u32(i) | |
693 | } | |
694 | fn write_u64(&mut self, i: u64) { | |
695 | (**self).write_u64(i) | |
696 | } | |
697 | fn write_u128(&mut self, i: u128) { | |
698 | (**self).write_u128(i) | |
699 | } | |
700 | fn write_usize(&mut self, i: usize) { | |
701 | (**self).write_usize(i) | |
702 | } | |
703 | fn write_i8(&mut self, i: i8) { | |
704 | (**self).write_i8(i) | |
705 | } | |
706 | fn write_i16(&mut self, i: i16) { | |
707 | (**self).write_i16(i) | |
708 | } | |
709 | fn write_i32(&mut self, i: i32) { | |
710 | (**self).write_i32(i) | |
711 | } | |
712 | fn write_i64(&mut self, i: i64) { | |
713 | (**self).write_i64(i) | |
714 | } | |
715 | fn write_i128(&mut self, i: i128) { | |
716 | (**self).write_i128(i) | |
717 | } | |
718 | fn write_isize(&mut self, i: isize) { | |
719 | (**self).write_isize(i) | |
720 | } | |
721 | } | |
722 | ||
92a42be0 SL |
723 | #[stable(feature = "from_for_ptrs", since = "1.6.0")] |
724 | impl<T> From<T> for Box<T> { | |
0731742a XL |
725 | /// Converts a generic type `T` into a `Box<T>` |
726 | /// | |
727 | /// The conversion allocates on the heap and moves `t` | |
728 | /// from the stack into it. | |
729 | /// | |
730 | /// # Examples | |
731 | /// ```rust | |
732 | /// let x = 5; | |
733 | /// let boxed = Box::new(5); | |
734 | /// | |
735 | /// assert_eq!(Box::from(x), boxed); | |
736 | /// ``` | |
92a42be0 SL |
737 | fn from(t: T) -> Self { |
738 | Box::new(t) | |
739 | } | |
740 | } | |
741 | ||
0731742a XL |
742 | #[stable(feature = "pin", since = "1.33.0")] |
743 | impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> { | |
744 | /// Converts a `Box<T>` into a `Pin<Box<T>>` | |
745 | /// | |
746 | /// This conversion does not allocate on the heap and happens in place. | |
0bf4aa26 | 747 | fn from(boxed: Box<T>) -> Self { |
0731742a | 748 | Box::into_pin(boxed) |
0bf4aa26 XL |
749 | } |
750 | } | |
751 | ||
8bb4bdeb | 752 | #[stable(feature = "box_from_slice", since = "1.17.0")] |
532ac7d7 | 753 | impl<T: Copy> From<&[T]> for Box<[T]> { |
0731742a XL |
754 | /// Converts a `&[T]` into a `Box<[T]>` |
755 | /// | |
756 | /// This conversion allocates on the heap | |
757 | /// and performs a copy of `slice`. | |
758 | /// | |
759 | /// # Examples | |
760 | /// ```rust | |
761 | /// // create a &[u8] which will be used to create a Box<[u8]> | |
762 | /// let slice: &[u8] = &[104, 101, 108, 108, 111]; | |
763 | /// let boxed_slice: Box<[u8]> = Box::from(slice); | |
764 | /// | |
765 | /// println!("{:?}", boxed_slice); | |
766 | /// ``` | |
532ac7d7 | 767 | fn from(slice: &[T]) -> Box<[T]> { |
dc9dc135 XL |
768 | let len = slice.len(); |
769 | let buf = RawVec::with_capacity(len); | |
770 | unsafe { | |
771 | ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len); | |
ba9703b0 | 772 | buf.into_box(slice.len()).assume_init() |
dc9dc135 | 773 | } |
8bb4bdeb XL |
774 | } |
775 | } | |
776 | ||
777 | #[stable(feature = "box_from_slice", since = "1.17.0")] | |
532ac7d7 | 778 | impl From<&str> for Box<str> { |
0731742a XL |
779 | /// Converts a `&str` into a `Box<str>` |
780 | /// | |
781 | /// This conversion allocates on the heap | |
782 | /// and performs a copy of `s`. | |
783 | /// | |
784 | /// # Examples | |
785 | /// ```rust | |
786 | /// let boxed: Box<str> = Box::from("hello"); | |
787 | /// println!("{}", boxed); | |
788 | /// ``` | |
83c7162d | 789 | #[inline] |
532ac7d7 | 790 | fn from(s: &str) -> Box<str> { |
7cac9316 XL |
791 | unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) } |
792 | } | |
793 | } | |
794 | ||
795 | #[stable(feature = "boxed_str_conv", since = "1.19.0")] | |
796 | impl From<Box<str>> for Box<[u8]> { | |
0731742a XL |
797 | /// Converts a `Box<str>>` into a `Box<[u8]>` |
798 | /// | |
799 | /// This conversion does not allocate on the heap and happens in place. | |
800 | /// | |
801 | /// # Examples | |
802 | /// ```rust | |
803 | /// // create a Box<str> which will be used to create a Box<[u8]> | |
804 | /// let boxed: Box<str> = Box::from("hello"); | |
805 | /// let boxed_str: Box<[u8]> = Box::from(boxed); | |
806 | /// | |
807 | /// // create a &[u8] which will be used to create a Box<[u8]> | |
808 | /// let slice: &[u8] = &[104, 101, 108, 108, 111]; | |
809 | /// let boxed_slice = Box::from(slice); | |
810 | /// | |
811 | /// assert_eq!(boxed_slice, boxed_str); | |
812 | /// ``` | |
83c7162d | 813 | #[inline] |
7cac9316 | 814 | fn from(s: Box<str>) -> Self { |
ea8adc8c | 815 | unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) } |
8bb4bdeb XL |
816 | } |
817 | } | |
818 | ||
74b04a01 | 819 | #[stable(feature = "boxed_slice_try_from", since = "1.43.0")] |
416331ca XL |
820 | impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> |
821 | where | |
822 | [T; N]: LengthAtMost32, | |
823 | { | |
824 | type Error = Box<[T]>; | |
825 | ||
826 | fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> { | |
827 | if boxed_slice.len() == N { | |
828 | Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) }) | |
829 | } else { | |
830 | Err(boxed_slice) | |
831 | } | |
832 | } | |
833 | } | |
834 | ||
8faf50e0 | 835 | impl Box<dyn Any> { |
1a4d82fc | 836 | #[inline] |
c34b1796 | 837 | #[stable(feature = "rust1", since = "1.0.0")] |
bd371182 | 838 | /// Attempt to downcast the box to a concrete type. |
5bcae85e SL |
839 | /// |
840 | /// # Examples | |
841 | /// | |
842 | /// ``` | |
843 | /// use std::any::Any; | |
844 | /// | |
a1dfa0c6 | 845 | /// fn print_if_string(value: Box<dyn Any>) { |
5bcae85e SL |
846 | /// if let Ok(string) = value.downcast::<String>() { |
847 | /// println!("String ({}): {}", string.len(), string); | |
848 | /// } | |
849 | /// } | |
850 | /// | |
e74abb32 XL |
851 | /// let my_string = "Hello World".to_string(); |
852 | /// print_if_string(Box::new(my_string)); | |
853 | /// print_if_string(Box::new(0i8)); | |
5bcae85e | 854 | /// ``` |
8faf50e0 | 855 | pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> { |
1a4d82fc JJ |
856 | if self.is::<T>() { |
857 | unsafe { | |
8faf50e0 | 858 | let raw: *mut dyn Any = Box::into_raw(self); |
9e0c209e | 859 | Ok(Box::from_raw(raw as *mut T)) |
1a4d82fc JJ |
860 | } |
861 | } else { | |
862 | Err(self) | |
863 | } | |
864 | } | |
865 | } | |
866 | ||
8faf50e0 | 867 | impl Box<dyn Any + Send> { |
c34b1796 AL |
868 | #[inline] |
869 | #[stable(feature = "rust1", since = "1.0.0")] | |
bd371182 | 870 | /// Attempt to downcast the box to a concrete type. |
5bcae85e SL |
871 | /// |
872 | /// # Examples | |
873 | /// | |
874 | /// ``` | |
875 | /// use std::any::Any; | |
876 | /// | |
a1dfa0c6 | 877 | /// fn print_if_string(value: Box<dyn Any + Send>) { |
5bcae85e SL |
878 | /// if let Ok(string) = value.downcast::<String>() { |
879 | /// println!("String ({}): {}", string.len(), string); | |
880 | /// } | |
881 | /// } | |
882 | /// | |
e74abb32 XL |
883 | /// let my_string = "Hello World".to_string(); |
884 | /// print_if_string(Box::new(my_string)); | |
885 | /// print_if_string(Box::new(0i8)); | |
5bcae85e | 886 | /// ``` |
8faf50e0 XL |
887 | pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> { |
888 | <Box<dyn Any>>::downcast(self).map_err(|s| unsafe { | |
bd371182 | 889 | // reapply the Send marker |
8faf50e0 | 890 | Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send)) |
bd371182 | 891 | }) |
c34b1796 AL |
892 | } |
893 | } | |
894 | ||
85aaf69f SL |
895 | #[stable(feature = "rust1", since = "1.0.0")] |
896 | impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> { | |
9fa01778 | 897 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 898 | fmt::Display::fmt(&**self, f) |
1a4d82fc JJ |
899 | } |
900 | } | |
901 | ||
85aaf69f SL |
902 | #[stable(feature = "rust1", since = "1.0.0")] |
903 | impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> { | |
9fa01778 | 904 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
85aaf69f | 905 | fmt::Debug::fmt(&**self, f) |
1a4d82fc JJ |
906 | } |
907 | } | |
908 | ||
9346a6ac | 909 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 910 | impl<T: ?Sized> fmt::Pointer for Box<T> { |
9fa01778 | 911 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
9346a6ac AL |
912 | // It's not possible to extract the inner Uniq directly from the Box, |
913 | // instead we cast it to a *const which aliases the Unique | |
914 | let ptr: *const T = &**self; | |
915 | fmt::Pointer::fmt(&ptr, f) | |
916 | } | |
917 | } | |
918 | ||
85aaf69f | 919 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
920 | impl<T: ?Sized> Deref for Box<T> { |
921 | type Target = T; | |
922 | ||
b039eaaf SL |
923 | fn deref(&self) -> &T { |
924 | &**self | |
925 | } | |
1a4d82fc JJ |
926 | } |
927 | ||
85aaf69f | 928 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 929 | impl<T: ?Sized> DerefMut for Box<T> { |
b039eaaf SL |
930 | fn deref_mut(&mut self) -> &mut T { |
931 | &mut **self | |
932 | } | |
1a4d82fc JJ |
933 | } |
934 | ||
dfeec247 | 935 | #[unstable(feature = "receiver_trait", issue = "none")] |
0731742a XL |
936 | impl<T: ?Sized> Receiver for Box<T> {} |
937 | ||
85aaf69f SL |
938 | #[stable(feature = "rust1", since = "1.0.0")] |
939 | impl<I: Iterator + ?Sized> Iterator for Box<I> { | |
940 | type Item = I::Item; | |
b039eaaf SL |
941 | fn next(&mut self) -> Option<I::Item> { |
942 | (**self).next() | |
943 | } | |
944 | fn size_hint(&self) -> (usize, Option<usize>) { | |
945 | (**self).size_hint() | |
946 | } | |
476ff2be SL |
947 | fn nth(&mut self, n: usize) -> Option<I::Item> { |
948 | (**self).nth(n) | |
949 | } | |
e74abb32 XL |
950 | fn last(self) -> Option<I::Item> { |
951 | BoxIter::last(self) | |
952 | } | |
953 | } | |
954 | ||
955 | trait BoxIter { | |
956 | type Item; | |
957 | fn last(self) -> Option<Self::Item>; | |
958 | } | |
959 | ||
960 | impl<I: Iterator + ?Sized> BoxIter for Box<I> { | |
961 | type Item = I::Item; | |
962 | default fn last(self) -> Option<I::Item> { | |
963 | #[inline] | |
964 | fn some<T>(_: Option<T>, x: T) -> Option<T> { | |
965 | Some(x) | |
966 | } | |
967 | ||
968 | self.fold(None, some) | |
969 | } | |
85aaf69f | 970 | } |
416331ca | 971 | |
e74abb32 XL |
972 | /// Specialization for sized `I`s that uses `I`s implementation of `last()` |
973 | /// instead of the default. | |
416331ca | 974 | #[stable(feature = "rust1", since = "1.0.0")] |
e74abb32 XL |
975 | impl<I: Iterator> BoxIter for Box<I> { |
976 | fn last(self) -> Option<I::Item> { | |
416331ca XL |
977 | (*self).last() |
978 | } | |
979 | } | |
980 | ||
85aaf69f SL |
981 | #[stable(feature = "rust1", since = "1.0.0")] |
982 | impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> { | |
b039eaaf SL |
983 | fn next_back(&mut self) -> Option<I::Item> { |
984 | (**self).next_back() | |
985 | } | |
532ac7d7 XL |
986 | fn nth_back(&mut self, n: usize) -> Option<I::Item> { |
987 | (**self).nth_back(n) | |
988 | } | |
85aaf69f SL |
989 | } |
990 | #[stable(feature = "rust1", since = "1.0.0")] | |
476ff2be SL |
991 | impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> { |
992 | fn len(&self) -> usize { | |
993 | (**self).len() | |
994 | } | |
995 | fn is_empty(&self) -> bool { | |
996 | (**self).is_empty() | |
997 | } | |
998 | } | |
1a4d82fc | 999 | |
0531ce1d | 1000 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1001 | impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {} |
1002 | ||
532ac7d7 XL |
1003 | #[stable(feature = "boxed_closure_impls", since = "1.35.0")] |
1004 | impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> { | |
1005 | type Output = <F as FnOnce<A>>::Output; | |
1006 | ||
1007 | extern "rust-call" fn call_once(self, args: A) -> Self::Output { | |
1008 | <F as FnOnce<A>>::call_once(*self, args) | |
1009 | } | |
1010 | } | |
1011 | ||
1012 | #[stable(feature = "boxed_closure_impls", since = "1.35.0")] | |
1013 | impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> { | |
1014 | extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output { | |
1015 | <F as FnMut<A>>::call_mut(self, args) | |
1016 | } | |
1017 | } | |
1018 | ||
1019 | #[stable(feature = "boxed_closure_impls", since = "1.35.0")] | |
1020 | impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> { | |
1021 | extern "rust-call" fn call(&self, args: A) -> Self::Output { | |
1022 | <F as Fn<A>>::call(self, args) | |
1023 | } | |
1024 | } | |
c34b1796 | 1025 | |
92a42be0 SL |
1026 | #[unstable(feature = "coerce_unsized", issue = "27732")] |
1027 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {} | |
c1a9b12d | 1028 | |
dfeec247 | 1029 | #[unstable(feature = "dispatch_from_dyn", issue = "none")] |
a1dfa0c6 XL |
1030 | impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {} |
1031 | ||
1032 | #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] | |
1033 | impl<A> FromIterator<A> for Box<[A]> { | |
1034 | fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self { | |
1035 | iter.into_iter().collect::<Vec<_>>().into_boxed_slice() | |
1036 | } | |
1037 | } | |
1038 | ||
c1a9b12d SL |
1039 | #[stable(feature = "box_slice_clone", since = "1.3.0")] |
1040 | impl<T: Clone> Clone for Box<[T]> { | |
1041 | fn clone(&self) -> Self { | |
dfeec247 | 1042 | self.to_vec().into_boxed_slice() |
c1a9b12d SL |
1043 | } |
1044 | } | |
1045 | ||
041b39d2 | 1046 | #[stable(feature = "box_borrow", since = "1.1.0")] |
e9174d1e | 1047 | impl<T: ?Sized> borrow::Borrow<T> for Box<T> { |
b039eaaf SL |
1048 | fn borrow(&self) -> &T { |
1049 | &**self | |
1050 | } | |
e9174d1e SL |
1051 | } |
1052 | ||
041b39d2 | 1053 | #[stable(feature = "box_borrow", since = "1.1.0")] |
e9174d1e | 1054 | impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> { |
b039eaaf SL |
1055 | fn borrow_mut(&mut self) -> &mut T { |
1056 | &mut **self | |
1057 | } | |
1058 | } | |
1059 | ||
1060 | #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] | |
1061 | impl<T: ?Sized> AsRef<T> for Box<T> { | |
1062 | fn as_ref(&self) -> &T { | |
1063 | &**self | |
1064 | } | |
1065 | } | |
1066 | ||
1067 | #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] | |
1068 | impl<T: ?Sized> AsMut<T> for Box<T> { | |
1069 | fn as_mut(&mut self) -> &mut T { | |
1070 | &mut **self | |
1071 | } | |
e9174d1e | 1072 | } |
ea8adc8c | 1073 | |
b7449926 XL |
1074 | /* Nota bene |
1075 | * | |
1076 | * We could have chosen not to add this impl, and instead have written a | |
1077 | * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound, | |
1078 | * because Box<T> implements Unpin even when T does not, as a result of | |
1079 | * this impl. | |
1080 | * | |
1081 | * We chose this API instead of the alternative for a few reasons: | |
1082 | * - Logically, it is helpful to understand pinning in regard to the | |
1083 | * memory region being pointed to. For this reason none of the | |
1084 | * standard library pointer types support projecting through a pin | |
1085 | * (Box<T> is the only pointer type in std for which this would be | |
1086 | * safe.) | |
1087 | * - It is in practice very useful to have Box<T> be unconditionally | |
1088 | * Unpin because of trait objects, for which the structural auto | |
0731742a | 1089 | * trait functionality does not apply (e.g., Box<dyn Foo> would |
b7449926 XL |
1090 | * otherwise not be Unpin). |
1091 | * | |
1092 | * Another type with the same semantics as Box but only a conditional | |
1093 | * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and | |
1094 | * could have a method to project a Pin<T> from it. | |
1095 | */ | |
0731742a | 1096 | #[stable(feature = "pin", since = "1.33.0")] |
dfeec247 | 1097 | impl<T: ?Sized> Unpin for Box<T> {} |
b7449926 | 1098 | |
74b04a01 XL |
1099 | #[unstable(feature = "generator_trait", issue = "43122")] |
1100 | impl<G: ?Sized + Generator<R> + Unpin, R> Generator<R> for Box<G> { | |
1101 | type Yield = G::Yield; | |
1102 | type Return = G::Return; | |
1103 | ||
1104 | fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> { | |
1105 | G::resume(Pin::new(&mut *self), arg) | |
1106 | } | |
1107 | } | |
1108 | ||
74b04a01 XL |
1109 | #[unstable(feature = "generator_trait", issue = "43122")] |
1110 | impl<G: ?Sized + Generator<R>, R> Generator<R> for Pin<Box<G>> { | |
1111 | type Yield = G::Yield; | |
1112 | type Return = G::Return; | |
1113 | ||
1114 | fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> { | |
1115 | G::resume((*self).as_mut(), arg) | |
1116 | } | |
1117 | } | |
1118 | ||
48663c56 | 1119 | #[stable(feature = "futures_api", since = "1.36.0")] |
8faf50e0 | 1120 | impl<F: ?Sized + Future + Unpin> Future for Box<F> { |
94b46f34 XL |
1121 | type Output = F::Output; |
1122 | ||
532ac7d7 XL |
1123 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
1124 | F::poll(Pin::new(&mut *self), cx) | |
94b46f34 XL |
1125 | } |
1126 | } |