ocaml_interop/
boxroot.rs

1// Copyright (c) Viable Systems and TezEdge Contributors
2// SPDX-License-Identifier: MIT
3
4use 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
13/// `BoxRoot<T>` is a container for a rooted [`OCaml`]`<T>` value.
14pub 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    /// Creates a new root from an [`OCaml`]`<T>` value.
26    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    /// Gets the value stored in this root as an [`OCaml`]`<T>`.
38    pub fn get<'a>(&self, cr: &'a OCamlRuntime) -> OCaml<'a, T> {
39        unsafe { OCaml::new(cr, boxroot_get(self.boxroot)) }
40    }
41
42    /// Roots the OCaml value `val`, returning an [`OCamlRef`]`<T>`.
43    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 that BoxRoot<T> does not implement Send or Sync for some concrete T.
73    // Using a simple type like () or i32 is sufficient.
74    assert_not_impl_any!(BoxRoot<()>: Send, Sync);
75    assert_not_impl_any!(BoxRoot<i32>: Send, Sync);
76}