#![allow(clippy::incompatible_msrv, reason = "the allocator-api feature needs Rust 1.100")]
#[cfg(all(feature = "std", not(loom)))]
use crate::Bcmalloc;
use crate::Heap;
#[cfg(all(feature = "std", not(loom)))]
use core::alloc::GlobalAlloc;
use core::{
alloc::{AllocError, Allocator, Layout},
num::NonZero,
ptr::{self, NonNull},
};
trait Backend {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8;
unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8;
unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout);
unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8;
}
const fn empty(layout: Layout) -> NonNull<[u8]> {
let address = NonZero::new(layout.align()).expect("alignments are not zero");
NonNull::slice_from_raw_parts(NonNull::<u8>::without_provenance(address), 0)
}
fn block(ptr: *mut u8, size: usize) -> Result<NonNull<[u8]>, AllocError> {
NonNull::new(ptr).map(|ptr| NonNull::slice_from_raw_parts(ptr, size)).ok_or(AllocError)
}
fn allocate<A: Backend + ?Sized>(
backend: &A,
layout: Layout,
zeroed: bool,
) -> Result<NonNull<[u8]>, AllocError> {
if layout.size() == 0 {
return Ok(empty(layout));
}
let ptr = unsafe {
if zeroed { backend.allocate_zeroed_raw(layout) } else { backend.allocate_raw(layout) }
};
block(ptr, layout.size())
}
unsafe fn deallocate<A: Backend + ?Sized>(backend: &A, ptr: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
unsafe { backend.deallocate_raw(ptr, layout) };
}
}
unsafe fn resize<A: Backend + ?Sized>(
backend: &A,
ptr: NonNull<u8>,
old: Layout,
new: Layout,
zeroed: bool,
) -> Result<NonNull<[u8]>, AllocError> {
if old.size() == 0 {
return allocate(backend, new, zeroed);
}
if new.size() == 0 {
unsafe { backend.deallocate_raw(ptr, old) };
return Ok(empty(new));
}
let moved = if old.align() == new.align() {
unsafe { backend.resize_raw(ptr, old, new.size()) }
} else {
let moved = unsafe { backend.allocate_raw(new) };
if !moved.is_null() {
unsafe {
ptr::copy_nonoverlapping(ptr.as_ptr(), moved, old.size().min(new.size()));
backend.deallocate_raw(ptr, old);
}
}
moved
};
if zeroed && !moved.is_null() && new.size() > old.size() {
unsafe { moved.add(old.size()).write_bytes(0, new.size() - old.size()) };
}
block(moved, new.size())
}
macro_rules! allocator {
($($header:tt)*) => {
unsafe impl $($header)* {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
allocate(self, layout, false)
}
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
allocate(self, layout, true)
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { deallocate(self, ptr, layout) }
}
unsafe fn grow(
&self,
ptr: NonNull<u8>,
old: Layout,
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
unsafe { resize(self, ptr, old, new, false) }
}
unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old: Layout,
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
unsafe { resize(self, ptr, old, new, true) }
}
unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old: Layout,
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
unsafe { resize(self, ptr, old, new, false) }
}
}
};
}
impl Backend for Heap<'_> {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 {
self.alloc(layout).map_or(ptr::null_mut(), NonNull::as_ptr)
}
unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 {
self.alloc_zeroed(layout).map_or(ptr::null_mut(), NonNull::as_ptr)
}
unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { self.dealloc(ptr, layout) };
}
unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
unsafe { self.realloc(ptr, old, new_size) }.map_or(ptr::null_mut(), NonNull::as_ptr)
}
}
allocator!(Allocator for Heap<'_>);
#[cfg(all(feature = "std", not(loom)))]
impl Backend for Bcmalloc {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 {
unsafe { GlobalAlloc::alloc(self, layout) }
}
unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 {
unsafe { GlobalAlloc::alloc_zeroed(self, layout) }
}
unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) };
}
unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
unsafe { GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size) }
}
}
#[cfg(all(feature = "std", not(loom)))]
allocator!(Allocator for Bcmalloc);
#[cfg(all(test, not(loom)))]
mod test {
use super::*;
use crate::testing::{TestRegion, iterations};
use std::{boxed::Box, vec::Vec};
fn layout(size: usize, align: usize) -> Layout {
Layout::from_size_align(size, align).unwrap()
}
const fn bytes(block: NonNull<[u8]>) -> &'static [u8] {
unsafe { core::slice::from_raw_parts(block.as_ptr().cast::<u8>(), block.len()) }
}
#[test]
fn collections_allocate_from_a_heap() {
let test = TestRegion::new(160, 1);
let region = test.region();
let heap = region.heap().unwrap();
let mut numbers = Vec::new_in(&heap);
numbers.extend(0..iterations(50_000) as u64);
assert!(numbers.iter().enumerate().all(|(i, &n)| n == i as u64));
let boxed = Box::new_in([7_u8; 300], &heap);
assert_eq!(boxed[299], 7);
drop((numbers, boxed));
heap.validate();
}
#[test]
fn zero_sized_blocks_are_aligned_dangling_and_free_to_drop() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let before = region.stats();
let block = heap.allocate(layout(0, 64)).unwrap();
assert_eq!((block.len(), block.as_ptr().cast::<u8>().addr() % 64), (0, 0));
unsafe { heap.deallocate(block.cast(), layout(0, 64)) };
assert_eq!(region.stats(), before, "an empty block takes no memory");
}
#[test]
fn zeroed_requests_clear_memory_that_was_used_before() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(200, 8);
let dirty: Vec<_> = (0..300)
.map(|_| {
let block = heap.allocate(layout).unwrap();
unsafe { block.as_ptr().cast::<u8>().write_bytes(0xAA, 200) };
block
})
.collect();
for block in &dirty {
unsafe { heap.deallocate(block.cast(), layout) };
}
let per_slab = crate::size_class::Class::for_size(200).blocks_per_slab();
let clean: Vec<_> = (0..per_slab).map(|_| heap.allocate_zeroed(layout).unwrap()).collect();
assert!(clean.iter().all(|block| bytes(*block).iter().all(|&byte| byte == 0)));
assert!(
clean
.iter()
.any(|block| dirty.iter().any(|old| old.cast::<u8>() == block.cast::<u8>())),
"some of the memory was reused"
);
}
#[test]
fn growing_keeps_the_contents_and_zeroes_the_new_tail() {
let test = TestRegion::new(64, 1);
let region = test.region();
let heap = region.heap().unwrap();
let (old, new) = (layout(40, 8), layout(5000, 8));
let block = heap.allocate(old).unwrap();
unsafe { block.as_ptr().cast::<u8>().write_bytes(1, 40) };
let grown = unsafe { heap.grow_zeroed(block.cast(), old, new) }.unwrap();
assert_eq!(grown.len(), 5000);
assert!(bytes(grown)[..40].iter().all(|&byte| byte == 1));
assert!(bytes(grown)[40..].iter().all(|&byte| byte == 0));
}
#[test]
fn a_resize_within_a_size_class_keeps_the_block_in_place() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let block = heap.allocate(layout(20, 8)).unwrap();
let grown = unsafe { heap.grow(block.cast(), layout(20, 8), layout(24, 8)) }.unwrap();
assert_eq!(grown.cast::<u8>(), block.cast::<u8>());
let shrunk = unsafe { heap.shrink(grown.cast(), layout(24, 8), layout(18, 8)) }.unwrap();
assert_eq!(shrunk.cast::<u8>(), block.cast::<u8>());
}
#[test]
fn a_resize_that_changes_the_alignment_moves_the_block_and_keeps_the_contents() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let old = layout(100, 8);
let block = heap.allocate(old).unwrap();
unsafe { block.as_ptr().cast::<u8>().write_bytes(5, 100) };
let grown = unsafe { heap.grow(block.cast(), old, layout(300, 256)) }.unwrap();
assert_eq!(grown.cast::<u8>().as_ptr().addr() % 256, 0);
assert!(bytes(grown)[..100].iter().all(|&byte| byte == 5));
let shrunk =
unsafe { heap.shrink(grown.cast(), layout(300, 256), layout(50, 16)) }.unwrap();
assert_eq!(shrunk.cast::<u8>().as_ptr().addr() % 16, 0);
assert!(bytes(shrunk).iter().all(|&byte| byte == 5));
}
#[test]
fn shrinking_to_nothing_frees_the_block() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let block = heap.allocate(layout(5000, 8)).unwrap();
let empty = unsafe { heap.shrink(block.cast(), layout(5000, 8), layout(0, 8)) }.unwrap();
assert_eq!(empty.len(), 0);
heap.flush();
assert_eq!(region.stats().free, region.stats().capacity, "the block was freed");
}
#[test]
fn a_refused_grow_leaves_the_block_untouched() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let old = layout(64, 8);
let block = heap.allocate(old).unwrap();
unsafe { block.as_ptr().cast::<u8>().write_bytes(9, 64) };
let refused = unsafe { heap.grow(block.cast(), old, layout(16 << 20, 8)) };
assert!(refused.is_err());
assert!(bytes(block).iter().all(|&byte| byte == 9));
}
#[test]
fn an_unsupported_alignment_is_an_error_and_not_a_panic() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
assert!(heap.allocate(layout(8, 2 * crate::MAX_ALIGN)).is_err());
}
}