use std::collections::BTreeMap;
use std::ffi::c_void;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use libloading::{Library, Symbol};
type StartFn = unsafe extern "C" fn() -> *mut c_void;
type OutputFn = unsafe extern "C" fn(
state: *mut c_void,
input: *const f64,
in_len: i32,
dt: f64,
output: *mut f64,
out_len: i32,
);
type FreeFn = unsafe extern "C" fn(state: *mut c_void);
type CloneFn = unsafe extern "C" fn(state: *mut c_void) -> *mut c_void;
type DerivativeFn = unsafe extern "C" fn(
state: *mut c_void,
input: *const f64,
in_len: i32,
xc: *const f64,
xc_len: i32,
xc_dot: *mut f64,
xc_dot_len: i32,
);
type OutputXcFn = unsafe extern "C" fn(
state: *mut c_void,
input: *const f64,
in_len: i32,
dt: f64,
xc: *const f64,
xc_len: i32,
output: *mut f64,
out_len: i32,
);
type UpdateFn = unsafe extern "C" fn(
state: *mut c_void,
input: *const f64,
in_len: i32,
dt: f64,
xc: *const f64,
xc_len: i32,
);
type NextSampleHitFn = unsafe extern "C" fn(
state: *mut c_void,
input: *const f64,
in_len: i32,
xc: *const f64,
xc_len: i32,
) -> f64;
type ArityFn = unsafe extern "C" fn(in_len: *mut i32, out_len: *mut i32) -> i32;
type StateSizeFn = unsafe extern "C" fn(state: *const c_void) -> usize;
type StateWriteFn = unsafe extern "C" fn(state: *const c_void, out: *mut u8);
type StateReadFn = unsafe extern "C" fn(input: *const u8, len: usize) -> *mut c_void;
#[derive(Clone, Copy)]
struct StateIo {
size: StateSizeFn,
write: StateWriteFn,
read: StateReadFn,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeclaredArity {
pub inputs: Option<usize>,
pub outputs: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CScriptError {
Load {
path: PathBuf,
message: String,
},
MissingSymbol {
path: PathBuf,
symbol: &'static str,
message: String,
},
StateContractNotExported {
path: PathBuf,
},
}
impl std::fmt::Display for CScriptError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CScriptError::Load { path, message } => {
write!(
f,
"failed to load C-script library {}: {message}",
path.display()
)
}
CScriptError::MissingSymbol {
path,
symbol,
message,
} => write!(
f,
"C-script library {} is missing required symbol `{symbol}`: {message}",
path.display()
),
CScriptError::StateContractNotExported { path } => write!(
f,
"C-script library {} does not export the checkpoint state contract \
(`cscript_state_size`/`cscript_state_write`/`cscript_state_read`)",
path.display()
),
}
}
}
impl std::error::Error for CScriptError {}
pub struct CScriptLibrary {
_library: Library,
start: StartFn,
output: Option<OutputFn>,
derivative: Option<DerivativeFn>,
output_xc: Option<OutputXcFn>,
update: Option<UpdateFn>,
next_sample_hit: Option<NextSampleHitFn>,
arity: Option<ArityFn>,
free: Option<FreeFn>,
clone_state: Option<CloneFn>,
state_io: Option<StateIo>,
path: PathBuf,
}
impl CScriptLibrary {
pub fn load(path: &Path) -> Result<Self, CScriptError> {
let library = unsafe { Library::new(path) }.map_err(|e| CScriptError::Load {
path: path.to_path_buf(),
message: e.to_string(),
})?;
let start: StartFn = unsafe {
let symbol: Symbol<StartFn> =
library
.get(b"cscript_start\0")
.map_err(|e| CScriptError::MissingSymbol {
path: path.to_path_buf(),
symbol: "cscript_start",
message: e.to_string(),
})?;
*symbol
};
let output: Option<OutputFn> = unsafe {
library
.get(b"cscript_output\0")
.ok()
.map(|symbol: Symbol<OutputFn>| *symbol)
};
let derivative: Option<DerivativeFn> = unsafe {
library
.get(b"cscript_derivative\0")
.ok()
.map(|symbol: Symbol<DerivativeFn>| *symbol)
};
let output_xc: Option<OutputXcFn> = unsafe {
library
.get(b"cscript_output_xc\0")
.ok()
.map(|symbol: Symbol<OutputXcFn>| *symbol)
};
let update: Option<UpdateFn> = unsafe {
library
.get(b"cscript_update\0")
.ok()
.map(|symbol: Symbol<UpdateFn>| *symbol)
};
let next_sample_hit: Option<NextSampleHitFn> = unsafe {
library
.get(b"cscript_next_sample_hit\0")
.ok()
.map(|symbol: Symbol<NextSampleHitFn>| *symbol)
};
let arity: Option<ArityFn> = unsafe {
library
.get(b"cscript_arity\0")
.ok()
.map(|symbol: Symbol<ArityFn>| *symbol)
};
let free: Option<FreeFn> = unsafe {
library
.get(b"cscript_free\0")
.ok()
.map(|symbol: Symbol<FreeFn>| *symbol)
};
let clone_state: Option<CloneFn> = unsafe {
library
.get(b"cscript_clone\0")
.ok()
.map(|symbol: Symbol<CloneFn>| *symbol)
};
let state_size: Option<StateSizeFn> = unsafe {
library
.get(b"cscript_state_size\0")
.ok()
.map(|symbol: Symbol<StateSizeFn>| *symbol)
};
let state_write: Option<StateWriteFn> = unsafe {
library
.get(b"cscript_state_write\0")
.ok()
.map(|symbol: Symbol<StateWriteFn>| *symbol)
};
let state_read: Option<StateReadFn> = unsafe {
library
.get(b"cscript_state_read\0")
.ok()
.map(|symbol: Symbol<StateReadFn>| *symbol)
};
let state_io = match (state_size, state_write, state_read) {
(None, None, None) => None,
(Some(size), Some(write), Some(read)) => Some(StateIo { size, write, read }),
(size, write, read) => {
let symbol = if size.is_none() {
"cscript_state_size"
} else if write.is_none() {
"cscript_state_write"
} else {
debug_assert!(read.is_none());
"cscript_state_read"
};
return Err(CScriptError::MissingSymbol {
path: path.to_path_buf(),
symbol,
message: "the checkpoint state contract is all-or-nothing: \
cscript_state_size, cscript_state_write and cscript_state_read \
must all be exported, or none of them"
.to_string(),
});
}
};
Ok(CScriptLibrary {
_library: library,
start,
output,
derivative,
output_xc,
update,
next_sample_hit,
arity,
free,
clone_state,
state_io,
path: path.to_path_buf(),
})
}
}
pub struct CScriptInstance {
library: Arc<CScriptLibrary>,
state: *mut c_void,
}
impl std::fmt::Debug for CScriptInstance {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CScriptInstance")
.field("state", &self.state)
.finish()
}
}
unsafe impl Send for CScriptInstance {}
impl CScriptInstance {
fn new(library: Arc<CScriptLibrary>) -> Self {
let state = unsafe { (library.start)() };
CScriptInstance { library, state }
}
pub fn call(&mut self, input: &[f64], dt: f64, out_len: usize) -> Vec<f64> {
let output_fn = self.library.output.unwrap_or_else(|| {
panic!(
"call requires a library loaded via CScriptRegistry::instantiate (which \
already requires cscript_output up front — this should be unreachable)"
)
});
let mut output = vec![0.0_f64; out_len];
unsafe {
output_fn(
self.state,
input.as_ptr(),
input.len() as i32,
dt,
output.as_mut_ptr(),
out_len as i32,
);
}
output
}
pub fn call_xc(&mut self, input: &[f64], dt: f64, xc: &[f64], out_len: usize) -> Vec<f64> {
let output_xc = self.library.output_xc.unwrap_or_else(|| {
panic!(
"call_xc requires a library loaded via CScriptRegistry::instantiate_xc (which \
already requires cscript_output_xc up front — this should be unreachable)"
)
});
let mut output = vec![0.0_f64; out_len];
unsafe {
output_xc(
self.state,
input.as_ptr(),
input.len() as i32,
dt,
xc.as_ptr(),
xc.len() as i32,
output.as_mut_ptr(),
out_len as i32,
);
}
output
}
pub fn update(&mut self, input: &[f64], dt: f64, xc: &[f64]) {
let Some(update_fn) = self.library.update else {
return;
};
unsafe {
update_fn(
self.state,
input.as_ptr(),
input.len() as i32,
dt,
xc.as_ptr(),
xc.len() as i32,
);
}
}
pub fn supports_next_sample_hit(&self) -> bool {
self.library.next_sample_hit.is_some()
}
pub fn declared_arity(&self) -> Option<DeclaredArity> {
let arity = self.library.arity?;
let mut in_len: i32 = -1;
let mut out_len: i32 = -1;
let status = unsafe { arity(&mut in_len, &mut out_len) };
if status != 0 {
return None;
}
Some(DeclaredArity {
inputs: usize::try_from(in_len).ok(),
outputs: usize::try_from(out_len).ok(),
})
}
pub fn next_sample_hit(&self, input: &[f64], xc: &[f64]) -> f64 {
let next_sample_hit_fn = self.library.next_sample_hit.unwrap_or_else(|| {
panic!(
"next_sample_hit requires a library that exports cscript_next_sample_hit \
(required for ts=variable — this should be unreachable, since that's checked \
up front)"
)
});
unsafe {
next_sample_hit_fn(
self.state,
input.as_ptr(),
input.len() as i32,
xc.as_ptr(),
xc.len() as i32,
)
}
}
pub fn derivative(&self, input: &[f64], xc: &[f64]) -> Vec<f64> {
let derivative_fn = self.library.derivative.unwrap_or_else(|| {
panic!(
"derivative requires a library loaded via CScriptRegistry::instantiate_xc \
(which already requires cscript_derivative up front — this should be \
unreachable)"
)
});
let mut xc_dot = vec![0.0_f64; xc.len()];
unsafe {
derivative_fn(
self.state,
input.as_ptr(),
input.len() as i32,
xc.as_ptr(),
xc.len() as i32,
xc_dot.as_mut_ptr(),
xc_dot.len() as i32,
);
}
xc_dot
}
pub fn rk4_step_xc(&self, xc: &[f64], input: &[f64], dt: f64) -> Vec<f64> {
let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
};
let k1 = self.derivative(input, xc);
let k2 = self.derivative(input, &add(xc, &k1, dt / 2.0));
let k3 = self.derivative(input, &add(xc, &k2, dt / 2.0));
let k4 = self.derivative(input, &add(xc, &k3, dt));
(0..xc.len())
.map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
.collect()
}
pub fn supports_clone(&self) -> bool {
self.library.clone_state.is_some()
}
pub fn try_clone(&self) -> Option<CScriptInstance> {
let clone_fn = self.library.clone_state?;
let state = unsafe { clone_fn(self.state) };
Some(CScriptInstance {
library: self.library.clone(),
state,
})
}
pub fn supports_state_io(&self) -> bool {
self.library.state_io.is_some()
}
pub fn state_bytes(&self) -> Result<Vec<u8>, CScriptError> {
let io = self
.library
.state_io
.ok_or_else(|| CScriptError::StateContractNotExported {
path: self.library.path.clone(),
})?;
let len = unsafe { (io.size)(self.state) };
let mut bytes = vec![0_u8; len];
if len > 0 {
unsafe { (io.write)(self.state, bytes.as_mut_ptr()) };
}
Ok(bytes)
}
pub fn restore_state(&mut self, bytes: &[u8]) -> Result<(), CScriptError> {
let io = self
.library
.state_io
.ok_or_else(|| CScriptError::StateContractNotExported {
path: self.library.path.clone(),
})?;
let new_state = unsafe { (io.read)(bytes.as_ptr(), bytes.len()) };
if let Some(free) = self.library.free {
if !self.state.is_null() {
unsafe { free(self.state) };
}
}
self.state = new_state;
Ok(())
}
}
impl Clone for CScriptInstance {
fn clone(&self) -> Self {
self.try_clone().unwrap_or_else(|| {
panic!(
"cannot clone a CScriptInstance whose library does not export cscript_clone \
(required for general-simulator's adaptive step-size control); either export \
cscript_clone from this library or run with a fixed --dt"
)
})
}
}
impl Drop for CScriptInstance {
fn drop(&mut self) {
if let Some(free) = self.library.free {
if !self.state.is_null() {
unsafe { free(self.state) };
}
}
}
}
#[derive(Default)]
pub struct CScriptRegistry {
libraries: BTreeMap<PathBuf, Arc<CScriptLibrary>>,
}
impl CScriptRegistry {
pub fn new() -> Self {
Self::default()
}
fn load_cached(&mut self, path: &Path) -> Result<Arc<CScriptLibrary>, CScriptError> {
if let Some(library) = self.libraries.get(path) {
Ok(library.clone())
} else {
let library = Arc::new(CScriptLibrary::load(path)?);
self.libraries.insert(path.to_path_buf(), library.clone());
Ok(library)
}
}
pub fn instantiate(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
let library = self.load_cached(path)?;
if library.output.is_none() {
return Err(CScriptError::MissingSymbol {
path: path.to_path_buf(),
symbol: "cscript_output",
message: "not found (or this library only implements the xc-owning contract \
— see CScriptRegistry::instantiate_xc)"
.to_string(),
});
}
Ok(CScriptInstance::new(library))
}
pub fn instantiate_xc(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
let library = self.load_cached(path)?;
if library.derivative.is_none() {
return Err(CScriptError::MissingSymbol {
path: path.to_path_buf(),
symbol: "cscript_derivative",
message: "required because this block declares xc_count > 0".to_string(),
});
}
if library.output_xc.is_none() {
return Err(CScriptError::MissingSymbol {
path: path.to_path_buf(),
symbol: "cscript_output_xc",
message: "required because this block declares xc_count > 0".to_string(),
});
}
Ok(CScriptInstance::new(library))
}
}