use std::{marker::PhantomData, ops::Deref};
use ocaml_boxroot_sys::{
boxroot_create, boxroot_delete, boxroot_error_string, boxroot_get, boxroot_get_ref,
boxroot_modify, BoxRoot as PrimitiveBoxRoot,
};
use crate::{memory::OCamlCell, OCaml, OCamlRef, OCamlRuntime};
pub struct BoxRoot<T: 'static> {
boxroot: PrimitiveBoxRoot,
_marker: PhantomData<T>,
}
fn boxroot_fail() -> ! {
let reason = unsafe { std::ffi::CStr::from_ptr(boxroot_error_string()) }.to_string_lossy();
panic!("Failed to allocate boxroot, boxroot_error_string() -> {reason}");
}
impl<T> BoxRoot<T> {
pub fn new(val: OCaml<T>) -> BoxRoot<T> {
if let Some(boxroot) = unsafe { boxroot_create(val.raw) } {
BoxRoot {
boxroot,
_marker: PhantomData,
}
} else {
boxroot_fail();
}
}
pub fn get<'a>(&self, cr: &'a OCamlRuntime) -> OCaml<'a, T> {
unsafe { OCaml::new(cr, boxroot_get(self.boxroot)) }
}
pub fn keep<'tmp>(&'tmp mut self, val: OCaml<T>) -> OCamlRef<'tmp, T> {
unsafe {
if !boxroot_modify(&mut self.boxroot, val.raw) {
boxroot_fail();
}
&*(boxroot_get_ref(self.boxroot) as *const OCamlCell<T>)
}
}
}
impl<T> Drop for BoxRoot<T> {
fn drop(&mut self) {
unsafe { boxroot_delete(self.boxroot) }
}
}
impl<T> Deref for BoxRoot<T> {
type Target = OCamlCell<T>;
fn deref(&self) -> OCamlRef<T> {
unsafe { &*(boxroot_get_ref(self.boxroot) as *const OCamlCell<T>) }
}
}
#[cfg(test)]
mod boxroot_assertions {
use super::*;
use static_assertions::assert_not_impl_any;
assert_not_impl_any!(BoxRoot<()>: Send, Sync);
assert_not_impl_any!(BoxRoot<i32>: Send, Sync);
}