allocator_api/liballoc/boxed.rs
1//! A pointer type for heap allocation.
2//!
3//! `Box<T, A>` is similar to
4//! [`std::boxed::Box<T>`](https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html),
5//! but pointers are associated with a specific allocator, allowing boxed pointers
6//! in different heaps.
7
8use core::borrow;
9use core::cmp::Ordering;
10use core::convert::From;
11use core::fmt;
12use core::hash::{Hash, Hasher};
13use core::iter::{Iterator, FusedIterator};
14use core::marker::{PhantomData, Unpin};
15use core::mem;
16use core::pin::Pin;
17use core::ops::{Deref, DerefMut};
18use core::ptr::{self, NonNull};
19
20use crate::alloc::{Alloc, Layout, handle_alloc_error};
21#[cfg(feature = "std")]
22use crate::alloc::Global;
23use crate::raw_vec::RawVec;
24
25/// A pointer type for heap allocation.
26global_alloc! {
27 pub struct Box<T: ?Sized, A: Alloc> {
28 ptr: NonNull<T>,
29 marker: PhantomData<T>,
30 pub(crate) a: A,
31 }
32}
33
34impl<T, A: Alloc> Box<T, A> {
35 /// Allocates memory in the given allocator and then places `x` into it.
36 ///
37 /// This doesn't actually allocate if `T` is zero-sized.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// # #[macro_use] extern crate allocator_api;
43 /// # test_using_global! {
44 /// use allocator_api::{Box, Global};
45 /// # fn main() {
46 /// let five = Box::new_in(5, Global);
47 /// # }
48 /// # }
49 /// ```
50 #[inline(always)]
51 pub fn new_in(x: T, a: A) -> Box<T, A> {
52 let mut a = a;
53 let layout = Layout::for_value(&x);
54 let size = layout.size();
55 let ptr = if size == 0 {
56 NonNull::dangling()
57 } else {
58 unsafe {
59 let ptr = a.alloc(layout).unwrap_or_else(|_| { handle_alloc_error(layout) });
60 ptr.cast()
61 }
62 };
63 unsafe {
64 ptr::write(ptr.as_ptr() as *mut T, x);
65 }
66 Box {
67 ptr: ptr,
68 marker: PhantomData,
69 a: a,
70 }
71 }
72
73 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
74 /// `x` will be pinned in memory and unable to be moved.
75 #[inline(always)]
76 pub fn pin_in(x: T, a: A) -> Pin<Box<T, A>> {
77 Box::new_in(x, a).into()
78 }
79
80}
81
82#[cfg(feature = "std")]
83impl<T> Box<T> {
84 /// Allocates memory on the heap and then places `x` into it.
85 ///
86 /// This doesn't actually allocate if `T` is zero-sized.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// use allocator_api::Box;
92 /// # fn main() {
93 /// let five = Box::new(5);
94 /// # }
95 /// ```
96 #[inline(always)]
97 pub fn new(x: T) -> Box<T> {
98 Box::new_in(x, Global)
99 }
100
101 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
102 /// `x` will be pinned in memory and unable to be moved.
103 #[inline(always)]
104 pub fn pin(x: T) -> Pin<Box<T>> {
105 Box::new(x).into()
106 }
107}
108
109#[cfg(feature = "std")]
110impl<T: ?Sized> Box<T> {
111 /// Constructs a box from a raw pointer.
112 ///
113 /// After calling this function, the raw pointer is owned by the
114 /// resulting `Box`. Specifically, the `Box` destructor will call
115 /// the destructor of `T` and free the allocated memory. Since the
116 /// way `Box` allocates and releases memory is unspecified, the
117 /// only valid pointer to pass to this function is the one taken
118 /// from another `Box` via the [`Box::into_raw`] function.
119 ///
120 /// This function is unsafe because improper use may lead to
121 /// memory problems. For example, a double-free may occur if the
122 /// function is called twice on the same raw pointer.
123 ///
124 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// use allocator_api::Box;
130 /// # fn main() {
131 /// let x = Box::new(5);
132 /// let ptr = Box::into_raw(x);
133 /// let x = unsafe { Box::from_raw(ptr) };
134 /// # }
135 /// ```
136 #[inline]
137 pub unsafe fn from_raw(raw: *mut T) -> Self {
138 Box::from_raw_in(raw, Global)
139 }
140}
141
142impl<T: ?Sized, A: Alloc> Box<T, A> {
143 /// Constructs a box from a raw pointer in the given allocator.
144 ///
145 /// This is similar to the [`Box::from_raw`] function, but assumes
146 /// the pointer was allocated with the given allocator.
147 ///
148 /// This function is unsafe because improper use may lead to
149 /// memory problems. For example, specifying the wrong allocator
150 /// may corrupt the allocator state.
151 ///
152 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
153 ///
154 /// # Examples
155 ///
156 /// ```
157 /// # #[macro_use] extern crate allocator_api;
158 /// # test_using_global! {
159 /// use allocator_api::{Box, Global};
160 /// # fn main() {
161 /// let x = Box::new_in(5, Global);
162 /// let ptr = Box::into_raw(x);
163 /// let x = unsafe { Box::from_raw_in(ptr, Global) };
164 /// # }
165 /// # }
166 /// ```
167 #[inline]
168 pub unsafe fn from_raw_in(raw: *mut T, a: A) -> Self {
169 Box {
170 ptr: NonNull::new_unchecked(raw),
171 marker: PhantomData,
172 a: a,
173 }
174 }
175
176 /// Consumes the `Box`, returning a wrapped raw pointer.
177 ///
178 /// The pointer will be properly aligned and non-null.
179 ///
180 /// After calling this function, the caller is responsible for the
181 /// memory previously managed by the `Box`. In particular, the
182 /// caller should properly destroy `T` and release the memory. The
183 /// proper way to do so is to convert the raw pointer back into a
184 /// `Box` with the [`Box::from_raw`] or the [`Box::from_raw_in`]
185 /// functions, with the appropriate allocator.
186 ///
187 /// Note: this is an associated function, which means that you have
188 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
189 /// is so that there is no conflict with a method on the inner type.
190 ///
191 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// # #[macro_use] extern crate allocator_api;
197 /// # test_using_global! {
198 /// use allocator_api::Box;
199 /// # fn main() {
200 /// let x = Box::new(5);
201 /// let ptr = Box::into_raw(x);
202 /// # }
203 /// # }
204 /// ```
205 #[inline]
206 pub fn into_raw(b: Box<T, A>) -> *mut T {
207 Box::into_raw_non_null(b).as_ptr()
208 }
209
210 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
211 ///
212 /// After calling this function, the caller is responsible for the
213 /// memory previously managed by the `Box`. In particular, the
214 /// caller should properly destroy `T` and release the memory. The
215 /// proper way to do so is to convert the `NonNull<T>` pointer
216 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
217 /// function.
218 ///
219 /// Note: this is an associated function, which means that you have
220 /// to call it as `Box::into_raw_non_null(b)`
221 /// instead of `b.into_raw_non_null()`. This
222 /// is so that there is no conflict with a method on the inner type.
223 ///
224 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// # #[macro_use] extern crate allocator_api;
230 /// # test_using_global! {
231 /// use allocator_api::Box;
232 ///
233 /// fn main() {
234 /// let x = Box::new(5);
235 /// let ptr = Box::into_raw_non_null(x);
236 /// }
237 /// # }
238 /// ```
239 #[inline]
240 pub fn into_raw_non_null(b: Box<T, A>) -> NonNull<T> {
241 let ptr = b.ptr;
242 mem::forget(b);
243 ptr
244 }
245
246 /// Consumes and leaks the `Box`, returning a mutable reference,
247 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
248 /// `'a`. If the type has only static references, or none at all, then this
249 /// may be chosen to be `'static`.
250 ///
251 /// This function is mainly useful for data that lives for the remainder of
252 /// the program's life. Dropping the returned reference will cause a memory
253 /// leak. If this is not acceptable, the reference should first be wrapped
254 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
255 /// then be dropped which will properly destroy `T` and release the
256 /// allocated memory.
257 ///
258 /// Note: this is an associated function, which means that you have
259 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
260 /// is so that there is no conflict with a method on the inner type.
261 ///
262 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
263 ///
264 /// # Examples
265 ///
266 /// Simple usage:
267 ///
268 /// ```
269 /// # #[macro_use] extern crate allocator_api;
270 /// # test_using_global! {
271 /// use allocator_api::Box;
272 /// fn main() {
273 /// let x = Box::new(41);
274 /// let static_ref: &'static mut usize = Box::leak(x);
275 /// *static_ref += 1;
276 /// assert_eq!(*static_ref, 42);
277 /// }
278 /// # }
279 /// ```
280 ///
281 /// Unsized data:
282 ///
283 /// ```
284 /// # #[macro_use] extern crate allocator_api;
285 /// # test_using_global! {
286 /// # use std::ptr;
287 /// use allocator_api::{Box, RawVec};
288 /// struct MyVec<T> {
289 /// buf: RawVec<T>,
290 /// len: usize,
291 /// }
292 ///
293 /// impl<T> MyVec<T> {
294 /// pub fn push(&mut self, elem: T) {
295 /// if self.len == self.buf.cap() { self.buf.double(); }
296 /// // double would have aborted or panicked if the len exceeded
297 /// // `isize::MAX` so this is safe to do unchecked now.
298 /// unsafe {
299 /// ptr::write(self.buf.ptr().offset(self.len as isize), elem);
300 /// }
301 /// self.len += 1;
302 /// }
303 /// }
304 /// fn main() {
305 /// //let x = vec![1, 2, 3].into_boxed_slice();
306 /// let mut v = MyVec { buf: RawVec::new(), len: 0 };
307 /// v.push(1);
308 /// v.push(2);
309 /// v.push(3);
310 /// v.buf.shrink_to_fit(v.len);
311 /// let x = unsafe { v.buf.into_box() };
312 /// let static_ref = Box::leak(x);
313 /// static_ref[0] = 4;
314 /// assert_eq!(*static_ref, [4, 2, 3]);
315 /// }
316 /// # }
317 /// ```
318 #[inline]
319 pub fn leak<'a>(b: Box<T, A>) -> &'a mut T
320 where
321 T: 'a // Technically not needed, but kept to be explicit.
322 {
323 unsafe { &mut *Box::into_raw(b) }
324 }
325
326 /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`
327 ///
328 /// This conversion does not allocate and happens in place.
329 ///
330 /// This is also available via [`From`].
331 fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>> {
332 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
333 // when `T: !Unpin`, so it's safe to pin it directly without any
334 // additional requirements.
335 unsafe { Pin::new_unchecked(boxed) }
336 }
337}
338
339impl<T: ?Sized, A: Alloc> Drop for Box<T, A> {
340 fn drop(&mut self) {
341 unsafe {
342 let layout = Layout::for_value(self.ptr.as_ref());
343 ptr::drop_in_place(self.ptr.as_ptr());
344 if layout.size() != 0 {
345 self.a.dealloc(self.ptr.cast(), layout);
346 }
347 }
348 }
349}
350
351impl<T: Default, A: Alloc + Default> Default for Box<T, A> {
352 /// Creates a `Box<T>`, with the `Default` value for T.
353 fn default() -> Box<T, A> {
354 Box::new_in(Default::default(), Default::default())
355 }
356}
357
358impl<T, A: Alloc + Default> Default for Box<[T], A> {
359 fn default() -> Box<[T], A> {
360 let a = A::default();
361 let b = Box::<[T; 0], A>::new_in([], a);
362 let raw = b.ptr.as_ptr();
363 let a = unsafe { ptr::read(&b.a) };
364 mem::forget(b);
365 unsafe { Box::from_raw_in(raw, a) }
366 }
367}
368
369/// Converts a boxed slice of bytes to a boxed string slice without checking
370/// that the string contains valid UTF-8.
371#[inline]
372pub unsafe fn from_boxed_utf8_unchecked<A: Alloc>(v: Box<[u8], A>) -> Box<str, A> {
373 let a = ptr::read(&v.a);
374 Box::from_raw_in(Box::into_raw(v) as *mut str, a)
375}
376
377impl<A: Alloc + Default> Default for Box<str, A> {
378 fn default() -> Box<str, A> {
379 unsafe { from_boxed_utf8_unchecked(Default::default()) }
380 }
381}
382
383impl<T: Clone, A: Alloc + Clone> Clone for Box<T, A> {
384 /// Returns a new box with a `clone()` of this box's contents.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// # #[macro_use] extern crate allocator_api;
390 /// # test_using_global! {
391 /// use allocator_api::Box;
392 /// # fn main() {
393 /// let x = Box::new(5);
394 /// let y = x.clone();
395 /// # }
396 /// # }
397 /// ```
398 #[inline]
399 fn clone(&self) -> Box<T, A> {
400 Box::new_in((**self).clone(), self.a.clone())
401 }
402 /// Copies `source`'s contents into `self` without creating a new allocation.
403 ///
404 /// # Examples
405 ///
406 /// ```
407 /// # #[macro_use] extern crate allocator_api;
408 /// # test_using_global! {
409 /// use allocator_api::Box;
410 /// # fn main() {
411 /// let x = Box::new(5);
412 /// let mut y = Box::new(10);
413 ///
414 /// y.clone_from(&x);
415 ///
416 /// assert_eq!(*y, 5);
417 /// # }
418 /// # }
419 /// ```
420 #[inline]
421 fn clone_from(&mut self, source: &Box<T, A>) {
422 (**self).clone_from(&(**source));
423 }
424}
425
426impl<A: Alloc + Clone> Clone for Box<str, A> {
427 fn clone(&self) -> Self {
428 let len = self.len();
429 let buf = RawVec::with_capacity_in(len, self.a.clone());
430 unsafe {
431 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
432 from_boxed_utf8_unchecked(buf.into_box())
433 }
434 }
435}
436
437impl<T: ?Sized + PartialEq, A: Alloc> PartialEq for Box<T, A> {
438 #[inline]
439 fn eq(&self, other: &Box<T, A>) -> bool {
440 PartialEq::eq(&**self, &**other)
441 }
442 #[inline]
443 fn ne(&self, other: &Box<T, A>) -> bool {
444 PartialEq::ne(&**self, &**other)
445 }
446}
447
448impl<T: ?Sized + PartialOrd, A: Alloc> PartialOrd for Box<T, A> {
449 #[inline]
450 fn partial_cmp(&self, other: &Box<T, A>) -> Option<Ordering> {
451 PartialOrd::partial_cmp(&**self, &**other)
452 }
453 #[inline]
454 fn lt(&self, other: &Box<T, A>) -> bool {
455 PartialOrd::lt(&**self, &**other)
456 }
457 #[inline]
458 fn le(&self, other: &Box<T, A>) -> bool {
459 PartialOrd::le(&**self, &**other)
460 }
461 #[inline]
462 fn ge(&self, other: &Box<T, A>) -> bool {
463 PartialOrd::ge(&**self, &**other)
464 }
465 #[inline]
466 fn gt(&self, other: &Box<T, A>) -> bool {
467 PartialOrd::gt(&**self, &**other)
468 }
469}
470
471impl<T: ?Sized + Ord, A: Alloc> Ord for Box<T, A> {
472 #[inline]
473 fn cmp(&self, other: &Box<T, A>) -> Ordering {
474 Ord::cmp(&**self, &**other)
475 }
476}
477
478impl<T: ?Sized + Eq, A: Alloc> Eq for Box<T, A> {}
479
480impl<T: ?Sized + Hash, A: Alloc> Hash for Box<T, A> {
481 fn hash<H: Hasher>(&self, state: &mut H) {
482 (**self).hash(state);
483 }
484}
485
486impl<T: ?Sized + Hasher, A: Alloc> Hasher for Box<T, A> {
487 fn finish(&self) -> u64 {
488 (**self).finish()
489 }
490 fn write(&mut self, bytes: &[u8]) {
491 (**self).write(bytes)
492 }
493 fn write_u8(&mut self, i: u8) {
494 (**self).write_u8(i)
495 }
496 fn write_u16(&mut self, i: u16) {
497 (**self).write_u16(i)
498 }
499 fn write_u32(&mut self, i: u32) {
500 (**self).write_u32(i)
501 }
502 fn write_u64(&mut self, i: u64) {
503 (**self).write_u64(i)
504 }
505 fn write_u128(&mut self, i: u128) {
506 (**self).write_u128(i)
507 }
508 fn write_usize(&mut self, i: usize) {
509 (**self).write_usize(i)
510 }
511 fn write_i8(&mut self, i: i8) {
512 (**self).write_i8(i)
513 }
514 fn write_i16(&mut self, i: i16) {
515 (**self).write_i16(i)
516 }
517 fn write_i32(&mut self, i: i32) {
518 (**self).write_i32(i)
519 }
520 fn write_i64(&mut self, i: i64) {
521 (**self).write_i64(i)
522 }
523 fn write_i128(&mut self, i: i128) {
524 (**self).write_i128(i)
525 }
526 fn write_isize(&mut self, i: isize) {
527 (**self).write_isize(i)
528 }
529}
530
531impl<T, A: Alloc + Default> From<T> for Box<T, A> {
532 /// Converts a generic type `T` into a `Box<T, A>`
533 ///
534 /// The conversion allocates with the associated allocator and moves `t`
535 /// from the stack into it.
536 ///
537 /// # Examples
538 /// ```rust
539 /// # #[macro_use] extern crate allocator_api;
540 /// # test_using_global! {
541 /// use allocator_api::Box;
542 /// # fn main() {
543 /// let x = 5;
544 /// let boxed = Box::new(5);
545 ///
546 /// assert_eq!(Box::from(x), boxed);
547 /// # }
548 /// # }
549 /// ```
550 fn from(t: T) -> Self {
551 Box::new_in(t, Default::default())
552 }
553}
554
555impl<T: ?Sized, A: Alloc> From<Box<T, A>> for Pin<Box<T, A>> {
556 /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`
557 ///
558 /// This conversion does not allocate and happens in place.
559 fn from(boxed: Box<T, A>) -> Self {
560 Box::into_pin(boxed)
561 }
562}
563
564impl<'a, T: Copy, A: Alloc + Default> From<&'a [T]> for Box<[T], A> {
565 /// Converts a `&[T]` into a `Box<[T], A>`
566 ///
567 /// This conversion allocates with the associated allocator
568 /// and performs a copy of `slice`.
569 ///
570 /// # Examples
571 /// ```rust
572 /// # #[macro_use] extern crate allocator_api;
573 /// # test_using_global! {
574 /// use allocator_api::Box;
575 /// # fn main() {
576 /// // create a &[u8] which will be used to create a Box<[u8]>
577 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
578 /// let boxed_slice: Box<[u8]> = Box::from(slice);
579 ///
580 /// println!("{:?}", boxed_slice);
581 /// # }
582 /// # }
583 /// ```
584 fn from(slice: &'a [T]) -> Box<[T], A> {
585 let a = Default::default();
586 let mut boxed = unsafe { RawVec::with_capacity_in(slice.len(), a).into_box() };
587 boxed.copy_from_slice(slice);
588 boxed
589 }
590}
591
592impl<'a, A: Alloc + Default> From<&'a str> for Box<str, A> {
593 /// Converts a `&str` into a `Box<str, A>`
594 ///
595 /// This conversion allocates with the associated allocator
596 /// and performs a copy of `s`.
597 ///
598 /// # Examples
599 /// ```rust
600 /// # #[macro_use] extern crate allocator_api;
601 /// # test_using_global! {
602 /// use allocator_api::Box;
603 /// # fn main() {
604 /// let boxed: Box<str> = Box::from("hello");
605 /// println!("{}", boxed);
606 /// # }
607 /// # }
608 /// ```
609 #[inline]
610 fn from(s: &'a str) -> Box<str, A> {
611 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
612 }
613}
614
615impl<A: Alloc> From<Box<str, A>> for Box<[u8], A> {
616 /// Converts a `Box<str, A>` into a `Box<[u8], A>`
617 ///
618 /// This conversion does not allocate on the heap and happens in place.
619 ///
620 /// # Examples
621 /// ```rust
622 /// # #[macro_use] extern crate allocator_api;
623 /// # test_using_global! {
624 /// use allocator_api::Box;
625 /// # fn main() {
626 /// // create a Box<str> which will be used to create a Box<[u8]>
627 /// let boxed: Box<str> = Box::from("hello");
628 /// let boxed_str: Box<[u8]> = Box::from(boxed);
629 ///
630 /// // create a &[u8] which will be used to create a Box<[u8]>
631 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
632 /// let boxed_slice = Box::from(slice);
633 ///
634 /// assert_eq!(boxed_slice, boxed_str);
635 /// # }
636 /// # }
637 /// ```
638 #[inline]
639 fn from(s: Box<str, A>) -> Self {
640 unsafe {
641 let a = ptr::read(&s.a);
642 Box::from_raw_in(Box::into_raw(s) as *mut [u8], a)
643 }
644 }
645}
646
647impl<T: fmt::Display + ?Sized, A: Alloc> fmt::Display for Box<T, A> {
648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649 fmt::Display::fmt(&**self, f)
650 }
651}
652
653impl<T: fmt::Debug + ?Sized, A: Alloc> fmt::Debug for Box<T, A> {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 fmt::Debug::fmt(&**self, f)
656 }
657}
658
659impl<T: ?Sized, A: Alloc> fmt::Pointer for Box<T, A> {
660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 // It's not possible to extract the inner Uniq directly from the Box,
662 // instead we cast it to a *const which aliases the Unique
663 let ptr: *const T = &**self;
664 fmt::Pointer::fmt(&ptr, f)
665 }
666}
667
668impl<T: ?Sized, A: Alloc> Deref for Box<T, A> {
669 type Target = T;
670
671 fn deref(&self) -> &T {
672 unsafe { self.ptr.as_ref() }
673 }
674}
675
676impl<T: ?Sized, A: Alloc> DerefMut for Box<T, A> {
677 fn deref_mut(&mut self) -> &mut T {
678 unsafe { self.ptr.as_mut() }
679 }
680}
681
682impl<I: Iterator + ?Sized, A: Alloc> Iterator for Box<I, A> {
683 type Item = I::Item;
684 fn next(&mut self) -> Option<I::Item> {
685 (**self).next()
686 }
687 fn size_hint(&self) -> (usize, Option<usize>) {
688 (**self).size_hint()
689 }
690 fn nth(&mut self, n: usize) -> Option<I::Item> {
691 (**self).nth(n)
692 }
693}
694
695impl<I: DoubleEndedIterator + ?Sized, A: Alloc> DoubleEndedIterator for Box<I, A> {
696 fn next_back(&mut self) -> Option<I::Item> {
697 (**self).next_back()
698 }
699}
700
701impl<I: ExactSizeIterator + ?Sized, A: Alloc> ExactSizeIterator for Box<I, A> {
702 fn len(&self) -> usize {
703 (**self).len()
704 }
705}
706
707impl<I: FusedIterator + ?Sized, A: Alloc> FusedIterator for Box<I, A> {}
708
709impl<T: Clone, A: Alloc + Clone> Clone for Box<[T], A> {
710 fn clone(&self) -> Self {
711 let mut new = BoxBuilder {
712 data: RawVec::with_capacity_in(self.len(), self.a.clone()),
713 len: 0,
714 };
715
716 let mut target = new.data.ptr();
717
718 for item in self.iter() {
719 unsafe {
720 ptr::write(target, item.clone());
721 target = target.offset(1);
722 };
723
724 new.len += 1;
725 }
726
727 return unsafe { new.into_box() };
728
729 // Helper type for responding to panics correctly.
730 struct BoxBuilder<T, A: Alloc> {
731 data: RawVec<T, A>,
732 len: usize,
733 }
734
735 impl<T, A: Alloc> BoxBuilder<T, A> {
736 unsafe fn into_box(self) -> Box<[T], A> {
737 let raw = ptr::read(&self.data);
738 mem::forget(self);
739 raw.into_box()
740 }
741 }
742
743 impl<T, A: Alloc> Drop for BoxBuilder<T, A> {
744 fn drop(&mut self) {
745 let mut data = self.data.ptr();
746 let max = unsafe { data.add(self.len) };
747
748 while data != max {
749 unsafe {
750 ptr::read(data);
751 data = data.offset(1);
752 }
753 }
754 }
755 }
756 }
757}
758
759impl<T: ?Sized, A: Alloc> borrow::Borrow<T> for Box<T, A> {
760 fn borrow(&self) -> &T {
761 &**self
762 }
763}
764
765impl<T: ?Sized, A: Alloc> borrow::BorrowMut<T> for Box<T, A> {
766 fn borrow_mut(&mut self) -> &mut T {
767 &mut **self
768 }
769}
770
771impl<T: ?Sized, A: Alloc> AsRef<T> for Box<T, A> {
772 fn as_ref(&self) -> &T {
773 &**self
774 }
775}
776
777impl<T: ?Sized, A: Alloc> AsMut<T> for Box<T, A> {
778 fn as_mut(&mut self) -> &mut T {
779 &mut **self
780 }
781}
782
783/* Nota bene
784 *
785 * We could have chosen not to add this impl, and instead have written a
786 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
787 * because Box<T> implements Unpin even when T does not, as a result of
788 * this impl.
789 *
790 * We chose this API instead of the alternative for a few reasons:
791 * - Logically, it is helpful to understand pinning in regard to the
792 * memory region being pointed to. For this reason none of the
793 * standard library pointer types support projecting through a pin
794 * (Box<T> is the only pointer type in std for which this would be
795 * safe.)
796 * - It is in practice very useful to have Box<T> be unconditionally
797 * Unpin because of trait objects, for which the structural auto
798 * trait functionality does not apply (e.g., Box<dyn Foo> would
799 * otherwise not be Unpin).
800 *
801 * Another type with the same semantics as Box but only a conditional
802 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
803 * could have a method to project a Pin<T> from it.
804 */
805impl<T: ?Sized, A: Alloc> Unpin for Box<T, A> { }