Module part2_fundamental_concepts

Source
Expand description

§Part 2: Fundamental Concepts

A thorough understanding of these core types is essential for the effective utilization of [ocaml-interop].

§2.1 Representing OCaml Values within Rust

  • OCaml<'gc, T>: This type serves as the primary wrapper for an OCaml value within Rust code.

    • 'gc: Represents a lifetime parameter associated with an active OCaml runtime scope. This signifies that the OCaml Garbage Collector (GC) may relocate or deallocate the value if it is not “rooted.”
    • T: Denotes the Rust type corresponding to the OCaml value (e.g., OCamlInt, String, OCamlList<OCamlFloat>).
    • Instances of this type are generally ephemeral and should be regarded as potentially invalid subsequent to any invocation into the OCaml runtime, unless explicitly rooted.
  • BoxRoot<T>: A smart pointer that “roots” an OCaml value, thereby ensuring that the OCaml GC does not deallocate or move it while the BoxRoot<T> instance persists.

    • It adheres to the RAII (Resource Acquisition Is Initialization) principle: the OCaml value is automatically unrooted when the BoxRoot<T> instance is dropped.
    • This mechanism is crucial for safely retaining OCaml values across multiple operations or Rust scopes.
    • Instances are created by:
      • Calling .to_boxroot(cr) on a Rust value (e.g., rust_value.to_boxroot(cr)), which converts it to an OCaml value and roots it.
      • Calling .root() on an existing OCaml<T> value (e.g., ocaml_val.root()).
      • Using BoxRoot::new(ocaml_val) with an existing OCaml<T> value. Note that BoxRoot::new() will panic if the underlying boxroot allocation fails.
    • BoxRoot<T> is !Send and !Sync due to its direct interaction with OCaml’s domain-specific GC state and memory management, meaning it cannot be safely transferred across threads or shared concurrently between threads.
  • RawOCaml: An unsafe, raw pointer-sized type representing an OCaml value. Direct interaction with this type is infrequent, as OCaml<T> and BoxRoot<T> provide safe abstractions.

§2.2 Converting Data Between Rust and OCaml

The traits ToOCaml<T> and FromOCaml<T> are provided to facilitate data conversions.

Common Type Mappings:

  • Rust i64 corresponds to OCaml int (represented as OCamlInt).
  • Rust f64 corresponds to OCaml float (represented as OCamlFloat).
  • Rust String/&str corresponds to OCaml string.
  • Rust Vec<T> corresponds to OCaml list or array (e.g., OCamlList<T>, OCamlUniformArray<T>).
  • Rust Option<T> corresponds to OCaml option.
  • Rust Result<T, E> corresponds to OCaml result (often with OCaml<String> for error types).