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