Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: use alloc zeroed to implement calloc #753

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions crates/hyperion/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
alloc::{Layout, alloc, dealloc, realloc},
alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc},
ptr::null_mut,
sync::OnceLock,
};
Expand All @@ -21,7 +21,7 @@ fn get_size_map() -> &'static papaya::HashMap<usize, usize> {
unsafe { ALLOC_SIZES.get().unwrap_unchecked() }
}

unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::c_void {
unsafe fn aligned_alloc(size: ecs_size_t, custom_alloc: fn(Layout) -> *mut u8) -> *mut core::ffi::c_void {
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
let size = size as usize;

Expand All @@ -30,7 +30,7 @@ unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::
return null_mut();
};

let ptr = unsafe { alloc(layout) };
let ptr = unsafe { custom_alloc(layout) };

if ptr.is_null() {
return null_mut();
Expand All @@ -42,17 +42,12 @@ unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::
ptr.cast::<core::ffi::c_void>()
}

unsafe extern "C-unwind" fn aligned_calloc(size: ecs_size_t) -> *mut core::ffi::c_void {
let ptr = unsafe { aligned_malloc(size) };
if !ptr.is_null() {
// Zero the entire allocation
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
unsafe {
std::ptr::write_bytes(ptr, 0, size as usize);
};
}
unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::c_void {
aligned_alloc(size, alloc)
}

ptr
unsafe extern "C-unwind" fn aligned_calloc(size: ecs_size_t) -> *mut core::ffi::c_void {
aligned_alloc(size, alloc_zeroed)
}

unsafe extern "C-unwind" fn aligned_realloc(
Expand Down
Loading