use std::alloc::{GlobalAlloc, Layout};
use crate::raw;
fn allocation_free_panic(message: &'static str) -> ! {
use std::os::unix::io::AsRawFd;
let _ = nix::unistd::write(std::io::stderr().as_raw_fd(), message.as_bytes());
std::process::abort();
}
const VALKEY_ALLOCATOR_NOT_AVAILABLE_MESSAGE: &str =
"Critical error: the Valkey Allocator isn't available.\n";
#[derive(Copy, Clone)]
pub struct ValkeyAlloc;
unsafe impl GlobalAlloc for ValkeyAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if cfg!(feature = "enable-system-alloc") {
return std::alloc::System.alloc(layout);
}
let size = (layout.size() + layout.align() - 1) & (!(layout.align() - 1));
match raw::RedisModule_Alloc {
Some(alloc) => alloc(size).cast(),
None => allocation_free_panic(VALKEY_ALLOCATOR_NOT_AVAILABLE_MESSAGE),
}
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
if cfg!(feature = "enable-system-alloc") {
return std::alloc::System.alloc_zeroed(layout);
}
let size = (layout.size() + layout.align() - 1) & (!(layout.align() - 1));
let num_elements = size / layout.align();
match raw::RedisModule_Calloc {
Some(calloc) => calloc(num_elements, layout.align()).cast(),
None => allocation_free_panic(VALKEY_ALLOCATOR_NOT_AVAILABLE_MESSAGE),
}
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if cfg!(feature = "enable-system-alloc") {
return std::alloc::System.dealloc(ptr, layout);
}
match raw::RedisModule_Free {
Some(f) => f(ptr.cast()),
None => allocation_free_panic(VALKEY_ALLOCATOR_NOT_AVAILABLE_MESSAGE),
};
}
}