Skip to main content

spicedb_embedded_sys/
instance.rs

1//! Safe wrappers for instance lifecycle: start and dispose.
2//!
3//! All FFI and unsafe code for these operations is contained here.
4
5use std::ffi::{CStr, CString};
6
7/// Starts a SpiceDB instance. Returns the JSON response string (caller parses).
8///
9/// # Errors
10///
11/// Returns an error string if the C library returns null or the operation fails.
12pub fn start(options_json: Option<&str>) -> Result<String, String> {
13    let ptr = match options_json {
14        Some(s) => {
15            let cstr = CString::new(s).map_err(|e| format!("options contain null byte: {e}"))?;
16            unsafe { crate::spicedb_start(cstr.as_ptr()) }
17        }
18        None => unsafe { crate::spicedb_start(std::ptr::null()) },
19    };
20    if ptr.is_null() {
21        return Err("null response from C library".to_string());
22    }
23    let s = unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() };
24    unsafe { crate::spicedb_free(ptr) };
25    Ok(s)
26}
27
28/// Disposes a SpiceDB instance. Returns the JSON response string (caller may ignore).
29///
30/// # Errors
31///
32/// Returns an error string if the C library returns null.
33pub fn dispose(handle: u64) -> Result<String, String> {
34    let ptr = unsafe { crate::spicedb_dispose(handle) };
35    if ptr.is_null() {
36        return Ok("{}".to_string());
37    }
38    let s = unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() };
39    unsafe { crate::spicedb_free(ptr) };
40    Ok(s)
41}