Struct const_alloc::ConstAlloc
source · [−]pub struct ConstAlloc<A>(_);
Expand description
A const
compatible wrapper over any Allocator type.
The wrapped Allocator doesn’t have to implement const Allocator
, only Allocator
.
This wrapper will forward any calls to allocate
at compile time to the const_allocate
intrinsic.
Likewise it will forward deallocate
calls at compile time to the const_deallocate
intrinsic.
Examples
const fn alloc_and_dealloc<A: ~const Allocator>(a: &A) {
let ptr = a.allocate(Layout::new::<[u8; 128]>());
if let Ok(ptr) = ptr {
unsafe { a.deallocate(ptr.cast(), Layout::new::<[u8; 128]>()) };
}
}
static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
struct CountingAlloc;
unsafe impl Allocator for CountingAlloc {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
System.allocate(layout)
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
System.deallocate(ptr, layout)
}
}
static A: ConstAlloc<CountingAlloc> = ConstAlloc(CountingAlloc);
#[used]
static CT: () = alloc_and_dealloc(&A);
alloc_and_dealloc(&A);
// CountingAlloc::allocate will only be called during the runtime call to alloc_and_dealloc
assert_eq!(ALLOC_COUNT.load(Ordering::SeqCst), 1);
assert_eq!(DEALLOC_COUNT.load(Ordering::SeqCst), 1);
Trait Implementations
🔬 This is a nightly-only experimental API. (
allocator_api
)Attempts to allocate a block of memory. Read more
🔬 This is a nightly-only experimental API. (
allocator_api
)Deallocates the memory referenced by ptr
. Read more
🔬 This is a nightly-only experimental API. (
allocator_api
)Behaves like allocate
, but also ensures that the returned memory is zero-initialized. Read more
🔬 This is a nightly-only experimental API. (
allocator_api
)Attempts to extend the memory block. Read more
🔬 This is a nightly-only experimental API. (
allocator_api
)Behaves like grow
, but also ensures that the new contents are set to zero before being
returned. Read more
🔬 This is a nightly-only experimental API. (
allocator_api
)Attempts to shrink the memory block. Read more