Skip to content

Commit

Permalink
alloc using PyMem functions
Browse files Browse the repository at this point in the history
  • Loading branch information
ijl committed Nov 12, 2024
1 parent 8ece0d4 commit 56fbd97
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

use std::alloc::{GlobalAlloc, Layout};
use std::ffi::c_void;

struct PyMemAllocator {}

#[global_allocator]
static ALLOCATOR: PyMemAllocator = PyMemAllocator {};

unsafe impl Sync for PyMemAllocator {}

unsafe impl GlobalAlloc for PyMemAllocator {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe { pyo3_ffi::PyMem_Malloc(layout.size()) as *mut u8 }
}

#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
unsafe { pyo3_ffi::PyMem_Free(ptr as *mut c_void) }
}

#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
unsafe {
let len = layout.size();
let ptr = pyo3_ffi::PyMem_Malloc(len) as *mut u8;
core::ptr::write_bytes(ptr, 0, len);
ptr
}
}

#[inline]
unsafe fn realloc(&self, ptr: *mut u8, _layout: Layout, new_size: usize) -> *mut u8 {
unsafe { pyo3_ffi::PyMem_Realloc(ptr as *mut c_void, new_size) as *mut u8 }
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ extern crate unwinding;
#[macro_use]
mod util;

mod alloc;
mod deserialize;
mod ffi;
mod opt;
Expand Down

0 comments on commit 56fbd97

Please sign in to comment.