use std::ffi::CStr;
use crate::{
mxArray,
MxArray,
};
use rustmex_core::shim::{
rustmex_put_variable as mexPutVariable,
rustmex_get_variable_ptr as mexGetVariablePtr,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WorkSpace {
Base,
Caller,
Global
}
impl WorkSpace {
const fn as_cstr(&self) -> &CStr {
use WorkSpace::*;
match self {
Base => unsafe { CStr::from_bytes_with_nul_unchecked(b"base\0") },
Caller => unsafe { CStr::from_bytes_with_nul_unchecked(b"caller\0") },
Global => unsafe { CStr::from_bytes_with_nul_unchecked(b"global\0") }
}
}
const fn as_ptr(&self) -> *const i8 {
self.as_cstr().as_ptr()
}
}
pub fn get_variable(ws: WorkSpace, name: &CStr) -> Option<MxArray> {
unsafe { get_variable_ref(ws, name) }.map(|x| x.duplicate())
}
pub unsafe fn get_variable_ref<'str, 'var>(ws: WorkSpace, name: &'str CStr) -> Option<&'var mxArray> {
let ptr = mexGetVariablePtr(ws.as_ptr(), name.as_ptr());
if ptr.is_null() {
None
} else {
Some(&*ptr)
}
}
pub fn put_variable(ws: WorkSpace, name: &CStr, var: MxArray) {
let ret = unsafe { mexPutVariable(ws.as_ptr(), name.as_ptr(),
MxArray::transfer_responsibility(var)) };
if ret != 0 {
panic!("There is no way to make an MxArray with a null pointer, yet MexPutVariable failed (per the docs: 'A possible cause of failure is that pm is NULL.')")
}
}