1use std::{marker::PhantomData, ops::Deref};
5
6use ocaml_boxroot_sys::{
7 boxroot_create, boxroot_delete, boxroot_error_string, boxroot_get, boxroot_get_ref,
8 boxroot_modify, BoxRoot as PrimitiveBoxRoot,
9};
10
11use crate::{memory::OCamlCell, OCaml, OCamlRef, OCamlRuntime};
12
13pub struct BoxRoot<T: 'static> {
15 boxroot: PrimitiveBoxRoot,
16 _marker: PhantomData<T>,
17}
18
19fn boxroot_fail() -> ! {
20 let reason = unsafe { std::ffi::CStr::from_ptr(boxroot_error_string()) }.to_string_lossy();
21 panic!("Failed to allocate boxroot, boxroot_error_string() -> {reason}");
22}
23
24impl<T> BoxRoot<T> {
25 pub fn new(val: OCaml<T>) -> BoxRoot<T> {
27 if let Some(boxroot) = unsafe { boxroot_create(val.raw) } {
28 BoxRoot {
29 boxroot,
30 _marker: PhantomData,
31 }
32 } else {
33 boxroot_fail();
34 }
35 }
36
37 pub fn get<'a>(&self, cr: &'a OCamlRuntime) -> OCaml<'a, T> {
39 unsafe { OCaml::new(cr, boxroot_get(self.boxroot)) }
40 }
41
42 pub fn keep<'tmp>(&'tmp mut self, val: OCaml<T>) -> OCamlRef<'tmp, T> {
44 unsafe {
45 if !boxroot_modify(&mut self.boxroot, val.raw) {
46 boxroot_fail();
47 }
48 &*(boxroot_get_ref(self.boxroot) as *const OCamlCell<T>)
49 }
50 }
51}
52
53impl<T> Drop for BoxRoot<T> {
54 fn drop(&mut self) {
55 unsafe { boxroot_delete(self.boxroot) }
56 }
57}
58
59impl<T> Deref for BoxRoot<T> {
60 type Target = OCamlCell<T>;
61
62 fn deref(&self) -> OCamlRef<T> {
63 unsafe { &*(boxroot_get_ref(self.boxroot) as *const OCamlCell<T>) }
64 }
65}
66
67#[cfg(test)]
68mod boxroot_assertions {
69 use super::*;
70 use static_assertions::assert_not_impl_any;
71
72 assert_not_impl_any!(BoxRoot<()>: Send, Sync);
75 assert_not_impl_any!(BoxRoot<i32>: Send, Sync);
76}