Skip to content

Commit

Permalink
Implement simple allocator using enif_{alloc,free}
Browse files Browse the repository at this point in the history
  • Loading branch information
filmor committed Jan 5, 2024
1 parent 6e803c0 commit 86bb26f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
3 changes: 2 additions & 1 deletion rustler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ readme = "../README.md"
edition = "2021"

[features]
default = ["derive", "nif_version_2_15"]
default = ["derive", "nif_version_2_15", "allocator"]
derive = ["rustler_codegen"]
alternative_nif_init_name = []
allocator = []
nif_version_2_14 = ["rustler_sys/nif_version_2_14"]
nif_version_2_15 = ["nif_version_2_14", "rustler_sys/nif_version_2_15"]
nif_version_2_16 = ["nif_version_2_15", "rustler_sys/nif_version_2_16"]
Expand Down
16 changes: 16 additions & 0 deletions rustler/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use std::alloc::{GlobalAlloc, Layout};

/// Allocator implementation that forwards all allocation calls to Erlang's allocator. Allows the
/// memory usage to be tracked by the BEAM.
pub struct EnifAllocator;

unsafe impl GlobalAlloc for EnifAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
// TODO: Check the requested alignment.
rustler_sys::enif_alloc(layout.size()) as *mut u8
}

unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
rustler_sys::enif_free(ptr as *mut rustler_sys::c_void);
}
}
7 changes: 7 additions & 0 deletions rustler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ pub mod wrapper;
#[doc(hidden)]
pub mod codegen_runtime;

mod alloc;
pub use alloc::EnifAllocator;

#[cfg(feature = "allocator")]
#[global_allocator]
static ALLOCATOR: EnifAllocator = EnifAllocator;

pub use lazy_static;

#[macro_use]
Expand Down

0 comments on commit 86bb26f

Please sign in to comment.