forked from GitHub/bdwgc-rust
Refactor lib.rs
This commit is contained in:
19
src/lib.rs
19
src/lib.rs
@@ -6,6 +6,7 @@ use libc::{c_int, c_void, size_t};
|
||||
use std::alloc::{GlobalAlloc, Layout};
|
||||
|
||||
const GC_SUCCESS: c_int = 0;
|
||||
const ALLOC_ALIGN: usize = 8;
|
||||
|
||||
#[repr(C)]
|
||||
struct GCStackBase {
|
||||
@@ -20,12 +21,10 @@ extern "C" {
|
||||
fn GC_get_stack_base(stack_base: *mut GCStackBase) -> c_int;
|
||||
fn GC_init() -> c_void;
|
||||
fn GC_malloc(size: size_t) -> *mut c_void;
|
||||
fn GC_malloc_uncollectable(size: size_t) -> *mut c_void;
|
||||
fn GC_register_my_thread(stack_base: *const GCStackBase) -> c_int;
|
||||
fn GC_unregister_my_thread();
|
||||
}
|
||||
|
||||
static mut GC_STARTED: bool = false;
|
||||
pub struct Allocator;
|
||||
|
||||
impl Allocator {
|
||||
@@ -34,10 +33,6 @@ impl Allocator {
|
||||
GC_allow_register_threads();
|
||||
}
|
||||
|
||||
pub unsafe fn start_gc() {
|
||||
GC_STARTED = true
|
||||
}
|
||||
|
||||
pub fn register_current_thread() -> Result<(), error::Error> {
|
||||
let mut base = GCStackBase {
|
||||
mem_base: std::ptr::null(),
|
||||
@@ -46,9 +41,7 @@ impl Allocator {
|
||||
|
||||
if unsafe { GC_get_stack_base(&mut base) } != GC_SUCCESS {
|
||||
return Err(error::Error::new("failed to get stack base"));
|
||||
}
|
||||
|
||||
if unsafe { GC_register_my_thread(&base) } != GC_SUCCESS {
|
||||
} else if unsafe { GC_register_my_thread(&base) } != GC_SUCCESS {
|
||||
return Err(error::Error::new("failed to register a thread for GC"));
|
||||
}
|
||||
|
||||
@@ -60,17 +53,13 @@ impl Allocator {
|
||||
}
|
||||
|
||||
pub fn alloc(size: usize) -> *mut u8 {
|
||||
unsafe { Allocator.alloc(Layout::from_size_align_unchecked(size, 8)) }
|
||||
unsafe { Allocator.alloc(Layout::from_size_align_unchecked(size, ALLOC_ALIGN)) }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for Allocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
return if GC_STARTED {
|
||||
GC_malloc(layout.size())
|
||||
} else {
|
||||
GC_malloc_uncollectable(layout.size())
|
||||
} as *mut u8;
|
||||
GC_malloc(layout.size()) as *mut u8
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
|
||||
|
||||
Reference in New Issue
Block a user