Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ffi/src/util.rs3//! Description: String ownership, JSON answers and panic containment shared by the C ABI.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use std::ffi::{c_char, CStr, CString};9use std::panic::{catch_unwind, AssertUnwindSafe};1011pub const ABI_VERSION: u32 = 1;1213/// Hands a Rust string to C. Interior NULs (impossible in our JSON, which escapes them) are stripped.14pub fn give(s: String) -> *mut c_char {15 let bytes: Vec<u8> = s.into_bytes().into_iter().filter(|b| *b != 0).collect();16 // SAFETY of unwrap: NULs were removed above.17 CString::new(bytes).unwrap_or_default().into_raw()18}1920pub fn give_json(v: &serde_json::Value) -> *mut c_char {21 give(v.to_string())22}2324pub fn error_json(message: impl Into<String>) -> *mut c_char {25 give_json(&serde_json::json!({ "ok": false, "error": message.into() }))26}2728/// Borrows a C string as UTF-8 text. NULL and invalid UTF-8 give `None`.29///30/// # Safety31/// `p` must be NULL or point to a NUL-terminated string valid for the returned lifetime.32pub unsafe fn text<'a>(p: *const c_char) -> Option<&'a str> {33 if p.is_null() {34 return None;35 }36 CStr::from_ptr(p).to_str().ok()37}3839/// Runs `f`, turning a panic into the JSON error answer.40pub fn guard_json(f: impl FnOnce() -> *mut c_char) -> *mut c_char {41 match catch_unwind(AssertUnwindSafe(f)) {42 Ok(p) => p,43 Err(e) => {44 let what = e.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| e.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown".into());45 error_json(format!("internal error: {what}"))46 }47 }48}4950/// Runs `f`, returning `fallback` if it panics.51pub fn guard<T>(fallback: T, f: impl FnOnce() -> T) -> T {52 catch_unwind(AssertUnwindSafe(f)).unwrap_or(fallback)53}5455#[no_mangle]56pub extern "C" fn sonata_abi_version() -> u32 {57 ABI_VERSION58}5960#[no_mangle]61pub extern "C" fn sonata_version_json() -> *mut c_char {62 give_json(&serde_json::json!({63 "version": env!("CARGO_PKG_VERSION"),64 "language_version": sonata_ir::LANGUAGE_VERSION,65 "ir_version": sonata_ir::IR_VERSION,66 "build": if cfg!(debug_assertions) { "debug" } else { "release" },67 }))68}6970/// # Safety71/// `s` must be NULL or a pointer returned by this library and not yet freed.72#[no_mangle]73pub unsafe extern "C" fn sonata_string_free(s: *mut c_char) {74 if !s.is_null() {75 drop(CString::from_raw(s));76 }77}7879#[no_mangle]80pub extern "C" fn sonata_registry_json() -> *mut c_char {81 guard_json(|| give(serde_json::to_string(crate::compiler::registry()).unwrap_or_else(|_| "{}".into())))82}83