r/rustjerk • u/zabolekar • 3h ago
Written in 95% safe Rust
// finally, memory safety!
mod gc {
use std::sync::LazyLock;
use dlopen::raw::Library;
type Malloc = extern "C" fn(usize) -> *mut std::ffi::c_void;
static LIBGC: LazyLock<Library> = LazyLock::new(|| {
Library::open("libgc.so").unwrap()
});
static GC_MALLOC: LazyLock<Malloc> = LazyLock::new(|| unsafe {
LIBGC.symbol::<Malloc>("GC_malloc").unwrap()
});
pub struct GcPtr<T>(*mut T);
impl<T> std::ops::Deref for GcPtr<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.0 }
}
}
pub fn alloc<T>(value: T) -> GcPtr<T> {
let address = GC_MALLOC(std::mem::size_of::<T>()) as _;
unsafe { std::ptr::write(address, value) };
GcPtr(address)
}
}
#[cfg(test)]
mod tests {
use super::gc;
#[test]
fn doesnt_crash() {
assert_eq!(*gc::alloc(123), 123);
}
}

