Struct bump_scope::BumpBox

source ·
pub struct BumpBox<'a, T: ?Sized> { /* private fields */ }
Expand description

A pointer type that uniquely owns a bump allocation of type T. This type is returned whenever a bump allocation is made.

You can turn a BumpBox into a reference with into_ref and into_mut and into a Box with into_box.

Unlike Box, BumpBox can not implement Clone or free the allocated space as it does not store its allocator. It’s essentially just an owned reference.

§BumpBox has a lot of methods

§No pinning

There is no way to safely pin a BumpBox in the general case. The drop guarantee of Pin requires the value to be dropped before its memory is reused. Preventing reuse of memory is not an option as that’s what this crate is all about. So we need to drop the pinned value. But there is no way to ensure that a value is dropped in an async context.

Example of an unsound pin macro implementation.

We define a bump_box_pin macro that turns a BumpBox<T> into a Pin<&mut T>. This is only sound in synchronous code. Here the memory Foo(1) is allocated at is reused by Foo(2) without dropping Foo(1) first which violates the drop guarantee.

macro_rules! bump_box_pin {
    ($name:ident) => {
        let mut boxed: BumpBox<_> = $name;
        let $name = unsafe { Pin::new_unchecked(&mut *boxed) };
    };
}

struct Foo(i32);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("dropped Foo({}) at {:?}", self.0, self as *const Foo);
    }
}

fn use_pinned(_foo: Pin<&mut Foo>) {}

fn violate_drop_guarantee(cx: &mut Context) {
    let mut bump: Bump = Bump::new();

    let mut future = Box::pin(async {
        let foo = bump.alloc(Foo(1));
        println!("created Foo({}) at {:?}", foo.0, &*foo as *const Foo);
        bump_box_pin!(foo);
        println!("pinned Foo({}) at {:?}", foo.0, &*foo as *const Foo);
        yield_now().await;
        use_pinned(foo);
    });

    assert_eq!(future.as_mut().poll(cx), Poll::Pending);
    mem::forget(future);

    bump.reset();
    let foo = bump.alloc(Foo(2));
    println!("created Foo({}) at {:?}", foo.0, &*foo as *const Foo);
}

This will print something like:

created Foo(1) at 0x78a4f4000d30
pinned  Foo(1) at 0x78a4f4000d30
created Foo(2) at 0x78a4f4000d30
dropped Foo(2) at 0x78a4f4000d30

Implementations§

source§

impl<'a, T: ?Sized + NoDrop> BumpBox<'a, T>

source

pub fn into_ref(self) -> &'a T

Turns this BumpBox<T> into &T that is live for the entire bump scope. This is only available for NoDrop types so you don’t omit dropping a value for which it matters.

!NoDrop types can still be turned into references via leak.

source

pub fn into_mut(self) -> &'a mut T

Turns this BumpBox<T> into &mut T that is live for the entire bump scope. This is only available for NoDrop types so you don’t omit dropping a value for which it matters.

!NoDrop types can still be turned into references via leak.

source§

impl<'a, T: ?Sized> BumpBox<'a, T>

source

pub fn into_box<A: BumpAllocator>(self, bump: A) -> Box<T, WithLifetime<'a, A>>

Available on crate feature alloc only.

Turns this BumpBox<T> into Box<T>. The bump allocator is not required to be the allocator this box was allocated in.

Unlike BumpBox, Box implements Clone and frees space iff it is the last allocation:

let a = bump.alloc(3i32).into_box(&bump);
let b = a.clone();
assert_eq!(a, b);
drop(b);
drop(a);
assert_eq!(bump.stats().allocated(), 0);
source

pub fn deallocate_in<A: BumpAllocator>(self, bump: A)

Drops this box and frees its memory iff it is the last allocation:

let boxed = bump.alloc(3i32);
assert_eq!(bump.stats().allocated(), 4);
boxed.deallocate_in(&bump);
assert_eq!(bump.stats().allocated(), 0);
source

pub fn leak(boxed: Self) -> &'a mut T

Turns this BumpBox<T> into &mut T that is live for the entire bump scope. T won’t be dropped which may leak resources.

If T is NoDrop, prefer to call into_mut to signify that nothing gets leaked.

source§

impl<'a, T> BumpBox<'a, T>

source

pub fn into_inner(self) -> T

Consumes the BumpBox, returning the wrapped value.

§Examples
let c = bump.alloc(5);
assert_eq!(c.into_inner(), 5);
source

pub fn into_boxed_slice(self) -> BumpBox<'a, [T]>

Converts a BumpBox<T> into a BumpBox<[T]>

This conversion happens in place.

source§

impl<'a> BumpBox<'a, [u8]>

source

pub const fn into_boxed_str( self, ) -> Result<BumpBox<'a, str>, FromUtf8Error<Self>>

Converts a slice of bytes to a string slice.

§Errors

Returns Err if the slice is not UTF-8 with a description as to why the provided bytes are not UTF-8. The vector you moved in is also included.

source

pub const unsafe fn into_boxed_str_unchecked(self) -> BumpBox<'a, str>

Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8.

See the safe version, into_boxed_str, for more information.

§Safety

The bytes passed in must be valid UTF-8.

source§

impl<'a> BumpBox<'a, str>

source

pub const EMPTY_STR: Self = _

Empty str.

source

pub fn into_boxed_bytes(self) -> BumpBox<'a, [u8]>

Converts a BumpBox<str> into a BumpBox<[u8]>.

source§

impl<'a, T: Sized> BumpBox<'a, MaybeUninit<T>>

source

pub fn init(self, value: T) -> BumpBox<'a, T>

Initializes self with value.

§Examples
let uninit = bump.alloc_uninit();
let init = uninit.init(1);
assert_eq!(*init, 1);
source

pub unsafe fn assume_init(self) -> BumpBox<'a, T>

§Safety

It is up to the caller to guarantee that the MaybeUninit<T> really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

See MaybeUninit::assume_init.

source§

impl<'a, T: Sized> BumpBox<'a, [MaybeUninit<T>]>

source

pub fn init_fill(self, value: T) -> BumpBox<'a, [T]>
where T: Clone,

Initializes self by filling it with elements by cloning value.

§Examples
let buf = bump.alloc_uninit_slice(10);
let buf = buf.init_fill(1);
assert_eq!(buf, [1; 10]);
source

pub fn init_fill_with(self, f: impl FnMut() -> T) -> BumpBox<'a, [T]>

Initializes self by filling it with elements returned by calling a closure repeatedly.

This method uses a closure to create new values. If you’d rather Clone a given value, use init_fill. If you want to use the Default trait to generate values, you can pass Default::default as the argument.

§Examples
let buf = bump.alloc_uninit_slice(10);
let buf = buf.init_fill_with(Default::default);
assert_eq!(buf, [0; 10]);
source

pub fn init_fill_iter(self, iter: impl Iterator<Item = T>) -> BumpBox<'a, [T]>

Initializes self by filling it with elements returned from an iterator.

§Panics

This function will panic if the iterator runs out of items before the slice is filled.

§Examples
let buf = bump.alloc_uninit_slice(5);
let buf = buf.init_fill_iter(['a', 'b'].iter().copied().cycle());
assert_eq!(buf, ['a', 'b', 'a', 'b', 'a']);
source

pub fn init_copy(self, slice: &[T]) -> BumpBox<'a, [T]>
where T: Copy,

Initializes self by copying the elements from slice into self.

The length of slice must be the same as self.

§Panics

This function will panic if the two slices have different lengths.

source

pub fn init_clone(self, slice: &[T]) -> BumpBox<'a, [T]>
where T: Clone,

Initializes self by cloning the elements from slice into self.

The length of slice must be the same as self.

§Panics

This function will panic if the two slices have different lengths.

source

pub unsafe fn assume_init(self) -> BumpBox<'a, [T]>

§Safety

It is up to the caller to guarantee that each MaybeUninit<T> really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

See MaybeUninit::assume_init.

source§

impl<'a, T> BumpBox<'a, [T]>

source

pub const EMPTY: Self = _

Empty slice.

source

pub const fn len(&self) -> usize

Returns the number of elements in the slice, also referred to as its ‘length’.

source

pub const fn is_empty(&self) -> bool

Returns true if the slice contains no elements.

source

pub fn pop(&mut self) -> Option<T>

Removes the last element from a slice and returns it, or None if it is empty.

source

pub fn clear(&mut self)

Clears the slice, removing all values.

§Examples
let mut slice = bump.alloc_slice_copy(&[1, 2, 3]);
slice.clear();
assert!(slice.is_empty());
source

pub fn truncate(&mut self, len: usize)

Shortens the slice, keeping the first len elements and dropping the rest.

If len is greater than the slice’s current length, this has no effect.

The drain method can emulate truncate, but causes the excess elements to be returned instead of dropped.

Note that this method has no effect on the allocated capacity of the vector.

§Examples

Truncating a five element vector to two elements:

let mut slice = bump.alloc_slice_copy(&[1, 2, 3, 4, 5]);
slice.truncate(2);
assert_eq!(slice, [1, 2]);

No truncation occurs when len is greater than the slice’s current length:

let mut slice = bump.alloc_slice_copy(&[1, 2, 3]);
slice.truncate(8);
assert_eq!(slice, [1, 2, 3]);

Truncating when len == 0 is equivalent to calling the clear method.

let mut slice = bump.alloc_slice_copy(&[1, 2, 3]);
slice.truncate(0);
assert_eq!(slice, []);
source

pub const fn as_slice(&self) -> &[T]

Extracts a slice containing the entire boxed slice.

Equivalent to &s[..].

source

pub fn as_mut_slice(&mut self) -> &mut [T]

Extracts a mutable slice containing the entire boxed slice.

Equivalent to &mut s[..].

source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice, or a dangling raw pointer valid for zero sized reads.

source

pub fn as_mut_ptr(&mut self) -> *mut T

Returns an unsafe mutable pointer to slice, or a dangling raw pointer valid for zero sized reads.

source

pub fn as_non_null_ptr(&self) -> NonNull<T>

Returns a raw nonnull pointer to the slice, or a dangling raw pointer valid for zero sized reads.

source

pub fn as_non_null_slice(&self) -> NonNull<[T]>

Returns a raw nonnull pointer to the slice, or a dangling raw pointer valid for zero sized reads.

source

pub unsafe fn set_len(&mut self, new_len: usize)

Forces the length of the slice to new_len.

This is a low-level operation that maintains none of the normal invariants of the type. Normally changing the length of a boxed slice is done using one of the safe operations instead, such as truncate or clear.

§Safety
  • new_len must be less than or equal to the capacity (capacity is not tracked by this type).
  • The elements at old_len..new_len must be initialized.
source

pub fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, shifting all elements after it to the left.

Note: Because this shifts over the remaining elements, it has a worst-case performance of O(n). If you don’t need the order of elements to be preserved, use swap_remove instead.

§Panics

Panics if index is out of bounds.

§Examples
let mut v = bump.alloc_slice_copy(&[1, 2, 3]);
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);
source

pub fn swap_remove(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

The removed element is replaced by the last element of the vector.

This does not preserve ordering, but is O(1). If you need to preserve the element order, use remove instead.

§Panics

Panics if index is out of bounds.

§Examples
let mut v = bump.alloc_slice_copy(&["foo", "bar", "baz", "qux"]);

assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);

assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);
source

pub fn split_at(self, mid: usize) -> (Self, Self)

Divides one slice into two at an index.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

§Panics

Panics if mid > len.

§Examples
let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

{
   let (left, right) = v.split_at(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

{
    let (left, right) = v.split_at(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

{
    let (left, right) = v.split_at(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
source

pub unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self)

Divides one slice into two at an index, without doing bounds checking.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

For a safe alternative see split_at.

§Safety

Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. The caller has to ensure that 0 <= mid <= self.len().

§Examples
let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

unsafe {
   let (left, right) = v.split_at_unchecked(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

unsafe {
    let (left, right) = v.split_at_unchecked(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

unsafe {
    let (left, right) = v.split_at_unchecked(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
source

pub fn split_first(self) -> Option<(BumpBox<'a, T>, BumpBox<'a, [T]>)>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

This does consume the BumpBox. You can create a new empty one with BumpBox::default.

§Examples
let x = bump.alloc_slice_copy(&[0, 1, 2]);

if let Some((first, elements)) = x.split_first() {
    assert_eq!(&*first, &0);
    assert_eq!(&*elements, &[1, 2]);
}
source

pub fn split_last(self) -> Option<(BumpBox<'a, T>, BumpBox<'a, [T]>)>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

This does consume the BumpBox. You can create a new empty one with BumpBox::default.

§Examples
let x = bump.alloc_slice_copy(&[0, 1, 2]);

if let Some((last, elements)) = x.split_last() {
    assert_eq!(&*last, &2);
    assert_eq!(&*elements, &[0, 1]);
}
source

pub fn merge(self, other: Self) -> Self

Merges two contiguous slices into one.

§Panics

Panics if self and other are not contiguous. Panics if T is a zero-sized type and adding the lengths overflows.

§Examples

Split and merge back together.

let v = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);

let (left, right) = v.split_at(3);
assert_eq!(left, [1, 2, 3]);
assert_eq!(right, [4, 5, 6]);

let merged = left.merge(right);
assert_eq!(merged, [1, 2, 3, 4, 5, 6]);
source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&mut T) -> bool,

Retains only the elements specified by the predicate, passing a mutable reference to it.

In other words, remove all elements e such that f(&mut e) returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

§Examples
let mut slice = bump.alloc_slice_copy(&[1, 2, 3, 4]);

slice.retain(|x| if *x <= 3 {
    *x += 1;
    true
} else {
    false
});

assert_eq!(slice, [2, 3, 4]);
source

pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
where R: RangeBounds<usize>,

Removes the specified range from the slice in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.

The returned iterator keeps a mutable borrow on the slice to optimize its implementation.

§Panics

Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

§Leaking

If the returned iterator goes out of scope without being dropped (due to mem::forget, for example), the vector may have lost and leaked elements arbitrarily, including elements outside the range.

§Examples
let mut v = bump.alloc_slice_copy(&[1, 2, 3]);
let u = bump.alloc_iter(v.drain(1..));
assert_eq!(v, [1]);
assert_eq!(u, [2, 3]);

// A full range clears the slice, like `clear()` does
v.drain(..);
assert_eq!(v, []);
source

pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, T, F>
where F: FnMut(&mut T) -> bool,

Creates an iterator which uses a closure to determine if an element should be removed.

If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the slice and will not be yielded by the iterator.

If the returned ExtractIf is not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Use retain with a negated predicate if you do not need the returned iterator.

Using this method is equivalent to the following code:

let mut i = 0;
while i < slice.len() {
    if some_predicate(&mut slice[i]) {
        let val = slice.remove(i);
        // your code here
    } else {
        i += 1;
    }
}

But extract_if is easier to use. extract_if is also more efficient, because it can backshift the elements of the array in bulk.

Note that extract_if also lets you mutate every element in the filter closure, regardless of whether you choose to keep or remove it.

§Examples

Splitting an array into evens and odds, reusing the original allocation:

let mut numbers = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);

let evens = bump.alloc_iter(numbers.extract_if(|x| *x % 2 == 0));
let odds = numbers;

assert_eq!(evens, [2, 4, 6, 8, 14]);
assert_eq!(odds, [1, 3, 5, 9, 11, 13, 15]);
source

pub fn dedup(&mut self)
where T: PartialEq,

Removes consecutive repeated elements in the slice according to the PartialEq trait implementation.

If the slice is sorted, this removes all duplicates.

§Examples
let mut slice = bump.alloc_slice_copy(&[1, 2, 2, 3, 2]);

slice.dedup();

assert_eq!(slice, [1, 2, 3, 2]);
source

pub fn dedup_by_key<F, K>(&mut self, key: F)
where F: FnMut(&mut T) -> K, K: PartialEq,

Removes all but the first of consecutive elements in the slice that resolve to the same key.

If the slice is sorted, this removes all duplicates.

§Examples
let mut slice = bump.alloc_slice_copy(&[10, 20, 21, 30, 20]);

slice.dedup_by_key(|i| *i / 10);

assert_eq!(slice, [10, 20, 30, 20]);
source

pub fn dedup_by<F>(&mut self, same_bucket: F)
where F: FnMut(&mut T, &mut T) -> bool,

Removes all but the first of consecutive elements in the vector satisfying a given equality relation.

The same_bucket function is passed references to two elements from the vector and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so if same_bucket(a, b) returns true, a is removed.

If the vector is sorted, this removes all duplicates.

§Examples
let mut slice = bump.alloc_slice_copy(&["foo", "bar", "Bar", "baz", "bar"]);

slice.dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(slice, ["foo", "bar", "baz", "bar"]);
source

pub fn partition<F>(self, f: F) -> (Self, Self)
where F: FnMut(&T) -> bool,

Consumes self, creating two boxed slices from it.

The predicate passed to partition() can return true, or false. partition() returns a pair, all of the elements for which it returned true, and all of the elements for which it returned false.

See also is_partitioned() and partition_in_place().

§Examples

Basic usage:

let slice = bump.alloc_slice_copy(&[1, 2, 3, 4, 5, 6, 7]);

let (even, odd) = slice.partition(|n| n % 2 == 0);

assert!(even.iter().all(|n| n % 2 == 0));
assert!(odd.iter().all(|n| n % 2 != 0));
source§

impl<'a, T, const N: usize> BumpBox<'a, [[T; N]]>

source

pub fn into_flattened(self) -> BumpBox<'a, [T]>

Takes a BumpBox<[[T; N]]> and flattens it into a BumpBox<[T]>.

§Panics

Panics if the length of the resulting slice would overflow a usize.

This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If size_of::<T>() > 0, this will never panic.

§Examples
let mut slice = bump.alloc_slice_copy(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
assert_eq!(slice.pop(), Some([7, 8, 9]));

let mut flattened = slice.into_flattened();
assert_eq!(flattened.pop(), Some(6));
source§

impl<'a, T: ?Sized> BumpBox<'a, T>

source

pub fn into_raw(self) -> NonNull<T>

Consumes the BumpBox, returning a wrapped raw pointer.

The pointer will be properly aligned and non-null. It is only valid for the lifetime 'a.

After calling this function, the caller is responsible for dropping the value previously managed by the BumpBox. The easiest way to do this is to p.drop_in_place().

You can turn this pointer back into a BumpBox with BumpBox::from_raw.

§Examples

Manually dropping T:

use bump_scope::{ Bump, BumpBox };
let bump: Bump = Bump::new();
let x = bump.alloc(String::from("Hello"));
let p = BumpBox::into_raw(x);
unsafe { p.as_ptr().drop_in_place() }
source

pub unsafe fn from_raw(ptr: NonNull<T>) -> Self

Constructs a BumpBox from a raw pointer.

After calling this function, the pointed to value is owned by the resulting BumpBox. Specifically, the BumpBox destructor will call the destructor of T. For this to be safe, the pointer must point to a valid T for the lifetime of 'a.

§Safety
  • ptr must point to a valid value for the lifetime 'a
§Examples

Recreate a BumpBox which was previously converted to a raw pointer using BumpBox::into_raw:

use bump_scope::{ Bump, BumpBox };
use core::ptr::NonNull;

unsafe fn from_raw_in<'a, T>(ptr: NonNull<T>, bump: &'a Bump) -> BumpBox<'a, T> {
    BumpBox::from_raw(ptr)
}

let bump: Bump = Bump::new();
let x = bump.alloc(String::from("Hello"));
let ptr = BumpBox::into_raw(x);
let x = unsafe { from_raw_in(ptr, &bump) };
assert_eq!(x.as_str(), "Hello");
drop(x);

Manually create a BumpBox from scratch by using the bump allocator:

use bump_scope::{ Bump, BumpBox };
use core::alloc::Layout;
use core::ptr::NonNull;

unsafe fn from_raw_in<'a, T>(ptr: NonNull<T>, bump: &'a Bump) -> BumpBox<'a, T> {
    BumpBox::from_raw(ptr)
}

let bump: Bump = Bump::new();

let five = unsafe {
    let ptr = bump.alloc_layout(Layout::new::<i32>());
    // In general .write is required to avoid attempting to destruct
    // the (uninitialized) previous contents of `ptr`, though for this
    // simple example `*ptr = 5` would have worked as well.
    ptr.as_ptr().write(5);
    from_raw_in(ptr, &bump)
};

assert_eq!(*five, 5);
source§

impl<'a> BumpBox<'a, dyn Any>

source

pub fn downcast<T: Any>(self) -> Result<BumpBox<'a, T>, Self>

Attempt to downcast the box to a concrete type.

source

pub unsafe fn downcast_unchecked<T: Any>(self) -> BumpBox<'a, T>

Downcasts the box to a concrete type.

For a safe alternative see downcast.

§Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

source§

impl<'a> BumpBox<'a, dyn Any + Send>

source

pub fn downcast<T: Any>(self) -> Result<BumpBox<'a, T>, Self>

Attempt to downcast the box to a concrete type.

source

pub unsafe fn downcast_unchecked<T: Any>(self) -> BumpBox<'a, T>

Downcasts the box to a concrete type.

For a safe alternative see downcast.

§Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

source§

impl<'a> BumpBox<'a, dyn Any + Send + Sync>

source

pub fn downcast<T: Any>(self) -> Result<BumpBox<'a, T>, Self>

Attempt to downcast the box to a concrete type.

source

pub unsafe fn downcast_unchecked<T: Any>(self) -> BumpBox<'a, T>

Downcasts the box to a concrete type.

For a safe alternative see downcast.

§Safety

The contained value must be of type T. Calling this method with the incorrect type is undefined behavior.

source§

impl<'a, T> BumpBox<'a, MaybeUninit<T>>
where T: FromZeroes,

source

pub fn init_zeroed(self) -> BumpBox<'a, T>

Available on crate feature zerocopy only.

Initializes self by filling it with zero.

§Examples
let uninit = bump.alloc_uninit::<i32>();
let init = uninit.init_zeroed();
assert_eq!(*init, 0);
source§

impl<'a, T> BumpBox<'a, [MaybeUninit<T>]>
where T: FromZeroes,

source

pub fn init_zeroed(self) -> BumpBox<'a, [T]>

Available on crate feature zerocopy only.

Initializes self by filling it with zeroes.

§Examples
let uninit = bump.alloc_uninit_slice::<i32>(10);
let init = uninit.init_zeroed();
assert_eq!(*init, [0; 10]);

Trait Implementations§

source§

impl<T: ?Sized> AsMut<T> for BumpBox<'_, T>

source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T: ?Sized> AsRef<T> for BumpBox<'_, T>

source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T: ?Sized> Borrow<T> for BumpBox<'_, T>

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T: ?Sized> BorrowMut<T> for BumpBox<'_, T>

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T: ?Sized + BufRead> BufRead for BumpBox<'_, T>

Available on crate feature std only.
source§

fn fill_buf(&mut self) -> Result<&[u8]>

Returns the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more
source§

fn consume(&mut self, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to read. Read more
source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
source§

fn read_line(&mut self, buf: &mut String) -> Result<usize>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if the underlying Read has any data left to be read. Read more
source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

🔬This is a nightly-only experimental API. (bufread_skip_until)
Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
source§

impl<'a, T: ?Sized + Debug> Debug for BumpBox<'a, T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a, T> Default for BumpBox<'a, [T]>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'a> Default for BumpBox<'a, str>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'a, T: ?Sized> Deref for BumpBox<'a, T>

source§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl<'a, T: ?Sized> DerefMut for BumpBox<'a, T>

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<'a, T: ?Sized + Display> Display for BumpBox<'a, T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a, T: ?Sized> Drop for BumpBox<'a, T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a> Extend<BumpBox<'a, str>> for String

Available on crate feature alloc only.
source§

fn extend<T: IntoIterator<Item = BumpBox<'a, str>>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<'a, T: ?Sized + Hash> Hash for BumpBox<'a, T>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<'a, T: ?Sized + Hasher> Hasher for BumpBox<'a, T>

source§

fn finish(&self) -> u64

Returns the hash value for the values written so far. Read more
source§

fn write(&mut self, bytes: &[u8])

Writes some data into this Hasher. Read more
source§

fn write_u8(&mut self, i: u8)

Writes a single u8 into this hasher.
source§

fn write_u16(&mut self, i: u16)

Writes a single u16 into this hasher.
source§

fn write_u32(&mut self, i: u32)

Writes a single u32 into this hasher.
source§

fn write_u64(&mut self, i: u64)

Writes a single u64 into this hasher.
source§

fn write_u128(&mut self, i: u128)

Writes a single u128 into this hasher.
source§

fn write_usize(&mut self, i: usize)

Writes a single usize into this hasher.
source§

fn write_i8(&mut self, i: i8)

Writes a single i8 into this hasher.
source§

fn write_i16(&mut self, i: i16)

Writes a single i16 into this hasher.
source§

fn write_i32(&mut self, i: i32)

Writes a single i32 into this hasher.
source§

fn write_i64(&mut self, i: i64)

Writes a single i64 into this hasher.
source§

fn write_i128(&mut self, i: i128)

Writes a single i128 into this hasher.
source§

fn write_isize(&mut self, i: isize)

Writes a single isize into this hasher.
source§

fn write_length_prefix(&mut self, len: usize)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a length prefix into this hasher, as part of being prefix-free. Read more
source§

fn write_str(&mut self, s: &str)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a single str into this hasher. Read more
source§

impl<T, I: SliceIndex<[T]>> Index<I> for BumpBox<'_, [T]>

source§

type Output = <I as SliceIndex<[T]>>::Output

The returned type after indexing.
source§

fn index(&self, index: I) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl<T, I: SliceIndex<[T]>> IndexMut<I> for BumpBox<'_, [T]>

source§

fn index_mut(&mut self, index: I) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'b, 'a, T> IntoIterator for &'b BumpBox<'a, [T]>

source§

type Item = &'b T

The type of the elements being iterated over.
source§

type IntoIter = Iter<'b, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'b, 'a, T> IntoIterator for &'b mut BumpBox<'a, [T]>

source§

type Item = &'b mut T

The type of the elements being iterated over.
source§

type IntoIter = IterMut<'b, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T> IntoIterator for BumpBox<'a, [T]>

source§

type Item = T

The type of the elements being iterated over.
source§

type IntoIter = IntoIter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T: ?Sized + Ord> Ord for BumpBox<'a, T>

source§

fn cmp(&self, other: &BumpBox<'a, T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl<T: ?Sized + PartialEq> PartialEq<&T> for BumpBox<'_, T>

source§

fn eq(&self, other: &&T) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &&T) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: ?Sized + PartialEq> PartialEq<&mut T> for BumpBox<'_, T>

source§

fn eq(&self, other: &&mut T) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &&mut T) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialEq, const N: usize> PartialEq<[T; N]> for BumpBox<'_, [T]>

source§

fn eq(&self, other: &[T; N]) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &[T; N]) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'a, T, U> PartialEq<BumpBox<'a, [U]>> for &[T]
where T: PartialEq<U>,

source§

fn eq(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'a, T, U> PartialEq<BumpBox<'a, [U]>> for &mut [T]
where T: PartialEq<U>,

source§

fn eq(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'a, T, U> PartialEq<BumpBox<'a, [U]>> for [T]
where T: PartialEq<U>,

source§

fn eq(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &BumpBox<'a, [U]>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'b, 'a, T: ?Sized + PartialEq> PartialEq<BumpBox<'b, T>> for BumpBox<'a, T>

source§

fn eq(&self, other: &BumpBox<'b, T>) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &BumpBox<'b, T>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: ?Sized + PartialEq> PartialEq<T> for BumpBox<'_, T>

source§

fn eq(&self, other: &T) -> bool

Tests for self and other values to be equal, and is used by ==.
source§

fn ne(&self, other: &T) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'b, 'a, T: ?Sized + PartialOrd> PartialOrd<BumpBox<'b, T>> for BumpBox<'a, T>

source§

fn partial_cmp(&self, other: &BumpBox<'b, T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
source§

fn lt(&self, other: &BumpBox<'b, T>) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
source§

fn le(&self, other: &BumpBox<'b, T>) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
source§

fn ge(&self, other: &BumpBox<'b, T>) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

fn gt(&self, other: &BumpBox<'b, T>) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
source§

impl<T: ?Sized + Read> Read for BumpBox<'_, T>

Available on crate feature std only.
source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Like read, except that it reads into a slice of buffers. Read more
source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>

Reads all bytes until EOF in this source, placing them into buf. Read more
source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize>

Reads all bytes until EOF in this source, appending them to buf. Read more
source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>

Reads the exact number of bytes required to fill buf. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
source§

impl<T: ?Sized + Seek> Seek for BumpBox<'_, T>

Available on crate feature std only.
source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64>

Seek to an offset, in bytes, in a stream. Read more
source§

fn stream_position(&mut self) -> Result<u64>

Returns the current seek position from the start of the stream. Read more
1.55.0 · source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.80.0 · source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
source§

impl<T> Serialize for BumpBox<'_, T>
where T: Serialize + ?Sized,

Available on crate feature serde only.
source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<T: ?Sized + Write> Write for BumpBox<'_, T>

Available on crate feature std only.
source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>

Like write, except that it writes from a slice of buffers. Read more
source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
source§

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>

Writes a formatted string into this writer, returning any error encountered. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
source§

impl<'a, T, U> CoerceUnsized<BumpBox<'a, U>> for BumpBox<'a, T>
where T: ?Sized + Unsize<U>, U: ?Sized,

Available on crate feature nightly-coerce-unsized only.
source§

impl<'a, T: ?Sized + Eq> Eq for BumpBox<'a, T>

source§

impl<T> NoDrop for BumpBox<'_, T>
where T: NoDrop,

source§

impl<'a, T: ?Sized + Send> Send for BumpBox<'a, T>

source§

impl<'a, T: ?Sized + Sync> Sync for BumpBox<'a, T>

source§

impl<'a, T: ?Sized> Unpin for BumpBox<'a, T>

Auto Trait Implementations§

§

impl<'a, T> Freeze for BumpBox<'a, T>
where T: ?Sized,

§

impl<'a, T> RefUnwindSafe for BumpBox<'a, T>
where T: RefUnwindSafe + ?Sized,

§

impl<'a, T> UnwindSafe for BumpBox<'a, T>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.