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