| 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 |
//! ``` |
| 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<'a, 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 the lifetime bound to the |
| 109 |
//! [`Bump`] immutable borrow which guarantees that the 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<'a, T>`]: struct.Box.html |
| 115 |
//! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw |
| 116 |
//! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw |
| 117 |
//! [`Bump`]: ../struct.Bump.html |
| 118 |
//! [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.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::ManuallyDrop, |
| 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)] |
| 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)] |
| 171 |
pub fn pin_in(x: T, a: &'a Bump) -> Pin<Box<'a, T>> { |
| 172 |
Box(a.alloc(x)).into() |
| 173 |
} |
| 174 |
|
| 175 |
/// Consumes the `Box`, returning the wrapped value. |
| 176 |
/// |
| 177 |
/// # Examples |
| 178 |
/// |
| 179 |
/// ``` |
| 180 |
/// use bumpalo::{Bump, boxed::Box}; |
| 181 |
/// |
| 182 |
/// let b = Bump::new(); |
| 183 |
/// |
| 184 |
/// let hello = Box::new_in("hello".to_owned(), &b); |
| 185 |
/// assert_eq!(Box::into_inner(hello), "hello"); |
| 186 |
/// ``` |
| 187 |
pub fn into_inner(b: Box<'a, T>) -> T { |
| 188 |
// `Box::into_raw` returns a pointer that is properly aligned and non-null. |
| 189 |
// The underlying `Bump` only frees the memory, but won't call the destructor. |
| 190 |
unsafe { core::ptr::read(Box::into_raw(b)) } |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
impl<'a, T: ?Sized> Box<'a, T> { |
| 195 |
/// Constructs a box from a raw pointer. |
| 196 |
/// |
| 197 |
/// After calling this function, the raw pointer is owned by the |
| 198 |
/// resulting `Box`. Specifically, the `Box` destructor will call |
| 199 |
/// the destructor of `T` and free the allocated memory. For this |
| 200 |
/// to be safe, the memory must have been allocated in accordance |
| 201 |
/// with the memory layout used by `Box` . |
| 202 |
/// |
| 203 |
/// # Safety |
| 204 |
/// |
| 205 |
/// This function is unsafe because improper use may lead to |
| 206 |
/// memory problems. For example, a double-free may occur if the |
| 207 |
/// function is called twice on the same raw pointer. |
| 208 |
/// |
| 209 |
/// # Examples |
| 210 |
/// |
| 211 |
/// Recreate a `Box` which was previously converted to a raw pointer |
| 212 |
/// using [`Box::into_raw`]: |
| 213 |
/// ``` |
| 214 |
/// use bumpalo::{Bump, boxed::Box}; |
| 215 |
/// |
| 216 |
/// let b = Bump::new(); |
| 217 |
/// |
| 218 |
/// let x = Box::new_in(5, &b); |
| 219 |
/// let ptr = Box::into_raw(x); |
| 220 |
/// 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. |
| 221 |
/// ``` |
| 222 |
/// Manually create a `Box` from scratch by using the bump allocator: |
| 223 |
/// ``` |
| 224 |
/// use std::alloc::{alloc, Layout}; |
| 225 |
/// use bumpalo::{Bump, boxed::Box}; |
| 226 |
/// |
| 227 |
/// let b = Bump::new(); |
| 228 |
/// |
| 229 |
/// unsafe { |
| 230 |
/// let ptr = b.alloc_layout(Layout::new::<i32>()).as_ptr() as *mut i32; |
| 231 |
/// *ptr = 5; |
| 232 |
/// 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. |
| 233 |
/// } |
| 234 |
/// ``` |
| 235 |
#[inline] |
| 236 |
pub unsafe fn from_raw(raw: *mut T) -> Self { |
| 237 |
Box(&mut *raw) |
| 238 |
} |
| 239 |
|
| 240 |
/// Consumes the `Box`, returning a wrapped raw pointer. |
| 241 |
/// |
| 242 |
/// The pointer will be properly aligned and non-null. |
| 243 |
/// |
| 244 |
/// After calling this function, the caller is responsible for the |
| 245 |
/// value previously managed by the `Box`. In particular, the |
| 246 |
/// caller should properly destroy `T`. The easiest way to |
| 247 |
/// do this is to convert the raw pointer back into a `Box` with the |
| 248 |
/// [`Box::from_raw`] function, allowing the `Box` destructor to perform |
| 249 |
/// the cleanup. |
| 250 |
/// |
| 251 |
/// Note: this is an associated function, which means that you have |
| 252 |
/// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This |
| 253 |
/// is so that there is no conflict with a method on the inner type. |
| 254 |
/// |
| 255 |
/// # Examples |
| 256 |
/// |
| 257 |
/// Converting the raw pointer back into a `Box` with [`Box::from_raw`] |
| 258 |
/// for automatic cleanup: |
| 259 |
/// ``` |
| 260 |
/// use bumpalo::{Bump, boxed::Box}; |
| 261 |
/// |
| 262 |
/// let b = Bump::new(); |
| 263 |
/// |
| 264 |
/// let x = Box::new_in(String::from("Hello"), &b); |
| 265 |
/// let ptr = Box::into_raw(x); |
| 266 |
/// 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. |
| 267 |
/// ``` |
| 268 |
/// Manual cleanup by explicitly running the destructor: |
| 269 |
/// ``` |
| 270 |
/// use std::ptr; |
| 271 |
/// use bumpalo::{Bump, boxed::Box}; |
| 272 |
/// |
| 273 |
/// let b = Bump::new(); |
| 274 |
/// |
| 275 |
/// let mut x = Box::new_in(String::from("Hello"), &b); |
| 276 |
/// let p = Box::into_raw(x); |
| 277 |
/// unsafe { |
| 278 |
/// ptr::drop_in_place(p); |
| 279 |
/// } |
| 280 |
/// ``` |
| 281 |
#[inline] |
| 282 |
pub fn into_raw(b: Box<'a, T>) -> *mut T { |
| 283 |
let mut b = ManuallyDrop::new(b); |
| 284 |
b.deref_mut().0 as *mut T |
| 285 |
} |
| 286 |
|
| 287 |
/// Consumes and leaks the `Box`, returning a mutable reference, |
| 288 |
/// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime |
| 289 |
/// `'a`. If the type has only static references, or none at all, then this |
| 290 |
/// may be chosen to be `'static`. |
| 291 |
/// |
| 292 |
/// This function is mainly useful for data that lives for the remainder of |
| 293 |
/// the program's life. Dropping the returned reference will cause a memory |
| 294 |
/// leak. If this is not acceptable, the reference should first be wrapped |
| 295 |
/// with the [`Box::from_raw`] function producing a `Box`. This `Box` can |
| 296 |
/// then be dropped which will properly destroy `T` and release the |
| 297 |
/// allocated memory. |
| 298 |
/// |
| 299 |
/// Note: this is an associated function, which means that you have |
| 300 |
/// to call it as `Box::leak(b)` instead of `b.leak()`. This |
| 301 |
/// is so that there is no conflict with a method on the inner type. |
| 302 |
/// |
| 303 |
/// # Examples |
| 304 |
/// |
| 305 |
/// Simple usage: |
| 306 |
/// |
| 307 |
/// ``` |
| 308 |
/// use bumpalo::{Bump, boxed::Box}; |
| 309 |
/// |
| 310 |
/// let b = Bump::new(); |
| 311 |
/// |
| 312 |
/// let x = Box::new_in(41, &b); |
| 313 |
/// let reference: &mut usize = Box::leak(x); |
| 314 |
/// *reference += 1; |
| 315 |
/// assert_eq!(*reference, 42); |
| 316 |
/// ``` |
| 317 |
/// |
| 318 |
///``` |
| 319 |
/// # #[cfg(feature = "collections")] |
| 320 |
/// # { |
| 321 |
/// use bumpalo::{Bump, boxed::Box, vec}; |
| 322 |
/// |
| 323 |
/// let b = Bump::new(); |
| 324 |
/// |
| 325 |
/// let x = vec![in &b; 1, 2, 3].into_boxed_slice(); |
| 326 |
/// let reference = Box::leak(x); |
| 327 |
/// reference[0] = 4; |
| 328 |
/// assert_eq!(*reference, [4, 2, 3]); |
| 329 |
/// # } |
| 330 |
///``` |
| 331 |
#[inline] |
| 332 |
pub fn leak(b: Box<'a, T>) -> &'a mut T { |
| 333 |
unsafe { &mut *Box::into_raw(b) } |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
impl<'a, T: ?Sized> Drop for Box<'a, T> { |
| 338 |
fn drop(&mut self) { |
| 339 |
unsafe { |
| 340 |
// `Box` owns value of `T`, but not memory behind it. |
| 341 |
core::ptr::drop_in_place(self.0); |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
impl<'a, T> Default for Box<'a, [T]> { |
| 347 |
fn default() -> Box<'a, [T]> { |
| 348 |
// It should be OK to `drop_in_place` empty slice of anything. |
| 349 |
Box(&mut []) |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
impl<'a> Default for Box<'a, str> { |
| 354 |
fn default() -> Box<'a, str> { |
| 355 |
// Empty slice is valid string. |
| 356 |
// It should be OK to `drop_in_place` empty str. |
| 357 |
unsafe { Box::from_raw(Box::into_raw(Box::<[u8]>::default()) as *mut str) } |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
impl<'a, 'b, T: ?Sized + PartialEq> PartialEq<Box<'b, T>> for Box<'a, T> { |
| 362 |
#[inline] |
| 363 |
fn eq(&self, other: &Box<'b, T>) -> bool { |
| 364 |
PartialEq::eq(&**self, &**other) |
| 365 |
} |
| 366 |
#[inline] |
| 367 |
fn ne(&self, other: &Box<'b, T>) -> bool { |
| 368 |
PartialEq::ne(&**self, &**other) |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
impl<'a, 'b, T: ?Sized + PartialOrd> PartialOrd<Box<'b, T>> for Box<'a, T> { |
| 373 |
#[inline] |
| 374 |
fn partial_cmp(&self, other: &Box<'b, T>) -> Option<Ordering> { |
| 375 |
PartialOrd::partial_cmp(&**self, &**other) |
| 376 |
} |
| 377 |
#[inline] |
| 378 |
fn lt(&self, other: &Box<'b, T>) -> bool { |
| 379 |
PartialOrd::lt(&**self, &**other) |
| 380 |
} |
| 381 |
#[inline] |
| 382 |
fn le(&self, other: &Box<'b, T>) -> bool { |
| 383 |
PartialOrd::le(&**self, &**other) |
| 384 |
} |
| 385 |
#[inline] |
| 386 |
fn ge(&self, other: &Box<'b, T>) -> bool { |
| 387 |
PartialOrd::ge(&**self, &**other) |
| 388 |
} |
| 389 |
#[inline] |
| 390 |
fn gt(&self, other: &Box<'b, T>) -> bool { |
| 391 |
PartialOrd::gt(&**self, &**other) |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
impl<'a, T: ?Sized + Ord> Ord for Box<'a, T> { |
| 396 |
#[inline] |
| 397 |
fn cmp(&self, other: &Box<'a, T>) -> Ordering { |
| 398 |
Ord::cmp(&**self, &**other) |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
impl<'a, T: ?Sized + Eq> Eq for Box<'a, T> {} |
| 403 |
|
| 404 |
impl<'a, T: ?Sized + Hash> Hash for Box<'a, T> { |
| 405 |
fn hash<H: Hasher>(&self, state: &mut H) { |
| 406 |
(**self).hash(state); |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
impl<'a, T: ?Sized + Hasher> Hasher for Box<'a, T> { |
| 411 |
fn finish(&self) -> u64 { |
| 412 |
(**self).finish() |
| 413 |
} |
| 414 |
fn write(&mut self, bytes: &[u8]) { |
| 415 |
(**self).write(bytes) |
| 416 |
} |
| 417 |
fn write_u8(&mut self, i: u8) { |
| 418 |
(**self).write_u8(i) |
| 419 |
} |
| 420 |
fn write_u16(&mut self, i: u16) { |
| 421 |
(**self).write_u16(i) |
| 422 |
} |
| 423 |
fn write_u32(&mut self, i: u32) { |
| 424 |
(**self).write_u32(i) |
| 425 |
} |
| 426 |
fn write_u64(&mut self, i: u64) { |
| 427 |
(**self).write_u64(i) |
| 428 |
} |
| 429 |
fn write_u128(&mut self, i: u128) { |
| 430 |
(**self).write_u128(i) |
| 431 |
} |
| 432 |
fn write_usize(&mut self, i: usize) { |
| 433 |
(**self).write_usize(i) |
| 434 |
} |
| 435 |
fn write_i8(&mut self, i: i8) { |
| 436 |
(**self).write_i8(i) |
| 437 |
} |
| 438 |
fn write_i16(&mut self, i: i16) { |
| 439 |
(**self).write_i16(i) |
| 440 |
} |
| 441 |
fn write_i32(&mut self, i: i32) { |
| 442 |
(**self).write_i32(i) |
| 443 |
} |
| 444 |
fn write_i64(&mut self, i: i64) { |
| 445 |
(**self).write_i64(i) |
| 446 |
} |
| 447 |
fn write_i128(&mut self, i: i128) { |
| 448 |
(**self).write_i128(i) |
| 449 |
} |
| 450 |
fn write_isize(&mut self, i: isize) { |
| 451 |
(**self).write_isize(i) |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
impl<'a, T: ?Sized> From<Box<'a, T>> for Pin<Box<'a, T>> { |
| 456 |
/// Converts a `Box<T>` into a `Pin<Box<T>>`. |
| 457 |
/// |
| 458 |
/// This conversion does not allocate on the heap and happens in place. |
| 459 |
fn from(boxed: Box<'a, T>) -> Self { |
| 460 |
// It's not possible to move or replace the insides of a `Pin<Box<T>>` |
| 461 |
// when `T: !Unpin`, so it's safe to pin it directly without any |
| 462 |
// additional requirements. |
| 463 |
unsafe { Pin::new_unchecked(boxed) } |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
impl<'a> Box<'a, dyn Any> { |
| 468 |
#[inline] |
| 469 |
/// Attempt to downcast the box to a concrete type. |
| 470 |
/// |
| 471 |
/// # Examples |
| 472 |
/// |
| 473 |
/// ``` |
| 474 |
/// use std::any::Any; |
| 475 |
/// |
| 476 |
/// fn print_if_string(value: Box<dyn Any>) { |
| 477 |
/// if let Ok(string) = value.downcast::<String>() { |
| 478 |
/// println!("String ({}): {}", string.len(), string); |
| 479 |
/// } |
| 480 |
/// } |
| 481 |
/// |
| 482 |
/// let my_string = "Hello World".to_string(); |
| 483 |
/// print_if_string(Box::new(my_string)); |
| 484 |
/// print_if_string(Box::new(0i8)); |
| 485 |
/// ``` |
| 486 |
pub fn downcast<T: Any>(self) -> Result<Box<'a, T>, Box<'a, dyn Any>> { |
| 487 |
if self.is::<T>() { |
| 488 |
unsafe { |
| 489 |
let raw: *mut dyn Any = Box::into_raw(self); |
| 490 |
Ok(Box::from_raw(raw as *mut T)) |
| 491 |
} |
| 492 |
} else { |
| 493 |
Err(self) |
| 494 |
} |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
impl<'a> Box<'a, dyn Any + Send> { |
| 499 |
#[inline] |
| 500 |
/// Attempt to downcast the box to a concrete type. |
| 501 |
/// |
| 502 |
/// # Examples |
| 503 |
/// |
| 504 |
/// ``` |
| 505 |
/// use std::any::Any; |
| 506 |
/// |
| 507 |
/// fn print_if_string(value: Box<dyn Any + Send>) { |
| 508 |
/// if let Ok(string) = value.downcast::<String>() { |
| 509 |
/// println!("String ({}): {}", string.len(), string); |
| 510 |
/// } |
| 511 |
/// } |
| 512 |
/// |
| 513 |
/// let my_string = "Hello World".to_string(); |
| 514 |
/// print_if_string(Box::new(my_string)); |
| 515 |
/// print_if_string(Box::new(0i8)); |
| 516 |
/// ``` |
| 517 |
pub fn downcast<T: Any>(self) -> Result<Box<'a, T>, Box<'a, dyn Any + Send>> { |
| 518 |
if self.is::<T>() { |
| 519 |
unsafe { |
| 520 |
let raw: *mut (dyn Any + Send) = Box::into_raw(self); |
| 521 |
Ok(Box::from_raw(raw as *mut T)) |
| 522 |
} |
| 523 |
} else { |
| 524 |
Err(self) |
| 525 |
} |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
impl<'a, T: fmt::Display + ?Sized> fmt::Display for Box<'a, T> { |
| 530 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 531 |
fmt::Display::fmt(&**self, f) |
| 532 |
} |
| 533 |
} |
| 534 |
|
| 535 |
impl<'a, T: fmt::Debug + ?Sized> fmt::Debug for Box<'a, T> { |
| 536 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 537 |
fmt::Debug::fmt(&**self, f) |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
impl<'a, T: ?Sized> fmt::Pointer for Box<'a, T> { |
| 542 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 543 |
// It's not possible to extract the inner Uniq directly from the Box, |
| 544 |
// instead we cast it to a *const which aliases the Unique |
| 545 |
let ptr: *const T = &**self; |
| 546 |
fmt::Pointer::fmt(&ptr, f) |
| 547 |
} |
| 548 |
} |
| 549 |
|
| 550 |
impl<'a, T: ?Sized> Deref for Box<'a, T> { |
| 551 |
type Target = T; |
| 552 |
|
| 553 |
fn deref(&self) -> &T { |
| 554 |
&*self.0 |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
impl<'a, T: ?Sized> DerefMut for Box<'a, T> { |
| 559 |
fn deref_mut(&mut self) -> &mut T { |
| 560 |
self.0 |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
impl<'a, I: Iterator + ?Sized> Iterator for Box<'a, I> { |
| 565 |
type Item = I::Item; |
| 566 |
fn next(&mut self) -> Option<I::Item> { |
| 567 |
(**self).next() |
| 568 |
} |
| 569 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 570 |
(**self).size_hint() |
| 571 |
} |
| 572 |
fn nth(&mut self, n: usize) -> Option<I::Item> { |
| 573 |
(**self).nth(n) |
| 574 |
} |
| 575 |
fn last(self) -> Option<I::Item> { |
| 576 |
#[inline] |
| 577 |
fn some<T>(_: Option<T>, x: T) -> Option<T> { |
| 578 |
Some(x) |
| 579 |
} |
| 580 |
self.fold(None, some) |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<'a, I> { |
| 585 |
fn next_back(&mut self) -> Option<I::Item> { |
| 586 |
(**self).next_back() |
| 587 |
} |
| 588 |
fn nth_back(&mut self, n: usize) -> Option<I::Item> { |
| 589 |
(**self).nth_back(n) |
| 590 |
} |
| 591 |
} |
| 592 |
impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<'a, I> { |
| 593 |
fn len(&self) -> usize { |
| 594 |
(**self).len() |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
impl<'a, I: FusedIterator + ?Sized> FusedIterator for Box<'a, I> {} |
| 599 |
|
| 600 |
#[cfg(feature = "collections")] |
| 601 |
impl<'a, A> Box<'a, [A]> { |
| 602 |
/// Creates a value from an iterator. |
| 603 |
/// This method is an adapted version of [`FromIterator::from_iter`][from_iter]. |
| 604 |
/// It cannot be made as that trait implementation given different signature. |
| 605 |
/// |
| 606 |
/// [from_iter]: https://doc.rust-lang.org/std/iter/trait.FromIterator.html#tymethod.from_iter |
| 607 |
/// |
| 608 |
/// # Examples |
| 609 |
/// |
| 610 |
/// Basic usage: |
| 611 |
/// ``` |
| 612 |
/// use bumpalo::{Bump, boxed::Box, vec}; |
| 613 |
/// |
| 614 |
/// let b = Bump::new(); |
| 615 |
/// |
| 616 |
/// let five_fives = std::iter::repeat(5).take(5); |
| 617 |
/// let slice = Box::from_iter_in(five_fives, &b); |
| 618 |
/// assert_eq!(vec![in &b; 5, 5, 5, 5, 5], &*slice); |
| 619 |
/// ``` |
| 620 |
pub fn from_iter_in<T: IntoIterator<Item = A>>(iter: T, a: &'a Bump) -> Self { |
| 621 |
use crate::collections::Vec; |
| 622 |
let mut vec = Vec::new_in(a); |
| 623 |
vec.extend(iter); |
| 624 |
vec.into_boxed_slice() |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
impl<'a, T: ?Sized> borrow::Borrow<T> for Box<'a, T> { |
| 629 |
fn borrow(&self) -> &T { |
| 630 |
&**self |
| 631 |
} |
| 632 |
} |
| 633 |
|
| 634 |
impl<'a, T: ?Sized> borrow::BorrowMut<T> for Box<'a, T> { |
| 635 |
fn borrow_mut(&mut self) -> &mut T { |
| 636 |
&mut **self |
| 637 |
} |
| 638 |
} |
| 639 |
|
| 640 |
impl<'a, T: ?Sized> AsRef<T> for Box<'a, T> { |
| 641 |
fn as_ref(&self) -> &T { |
| 642 |
&**self |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
impl<'a, T: ?Sized> AsMut<T> for Box<'a, T> { |
| 647 |
fn as_mut(&mut self) -> &mut T { |
| 648 |
&mut **self |
| 649 |
} |
| 650 |
} |
| 651 |
|
| 652 |
impl<'a, T: ?Sized> Unpin for Box<'a, T> {} |
| 653 |
|
| 654 |
impl<'a, F: ?Sized + Future + Unpin> Future for Box<'a, F> { |
| 655 |
type Output = F::Output; |
| 656 |
|
| 657 |
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 658 |
F::poll(Pin::new(&mut *self), cx) |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
/// This impl replaces unsize coercion. |
| 663 |
impl<'a, T, const N: usize> From<Box<'a, [T; N]>> for Box<'a, [T]> { |
| 664 |
fn from(arr: Box<'a, [T; N]>) -> Box<'a, [T]> { |
| 665 |
let mut arr = ManuallyDrop::new(arr); |
| 666 |
let ptr = core::ptr::slice_from_raw_parts_mut(arr.as_mut_ptr(), N); |
| 667 |
unsafe { Box::from_raw(ptr) } |
| 668 |
} |
| 669 |
} |
| 670 |
|
| 671 |
/// This impl replaces unsize coercion. |
| 672 |
impl<'a, T, const N: usize> TryFrom<Box<'a, [T]>> for Box<'a, [T; N]> { |
| 673 |
type Error = Box<'a, [T]>; |
| 674 |
fn try_from(slice: Box<'a, [T]>) -> Result<Box<'a, [T; N]>, Box<'a, [T]>> { |
| 675 |
if slice.len() == N { |
| 676 |
let mut slice = ManuallyDrop::new(slice); |
| 677 |
let ptr = slice.as_mut_ptr() as *mut [T; N]; |
| 678 |
Ok(unsafe { Box::from_raw(ptr) }) |
| 679 |
} else { |
| 680 |
Err(slice) |
| 681 |
} |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
#[cfg(feature = "serde")] |
| 686 |
mod serialize { |
| 687 |
use super::*; |
| 688 |
|
| 689 |
use serde::{Serialize, Serializer}; |
| 690 |
|
| 691 |
impl<'a, T> Serialize for Box<'a, T> |
| 692 |
where |
| 693 |
T: Serialize, |
| 694 |
{ |
| 695 |
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| 696 |
T::serialize(self, serializer) |
| 697 |
} |
| 698 |
} |
| 699 |
} |