#![deny(missing_docs)]
#![deny(clippy::missing_errors_doc)]
#![deny(clippy::missing_panics_doc)]
#[doc(hidden)]
#[path = "entrypoint.rs"]
pub mod __private;
mod array;
mod error;
#[allow(dead_code, missing_docs)]
mod ffi;
#[allow(dead_code)]
mod runtime;
pub use array::{
ArrayMut, ArrayRef, Class, Complex, Numeric, OwnedArray, PersistentArray, PlainArrayRef,
SparseIndices, SparseNumeric, UninitNumeric,
};
pub use error::{Error, ErrorId, ErrorKind, MatError, MatlabErrorInfo, Result, ResultExt};
#[doc = include_str!("../docs/API_COVERAGE.md")]
pub mod api_coverage {}
#[doc = include_str!("../docs/ERROR_HANDLING.md")]
pub mod error_handling {}
use std::{
ffi::{c_char, c_void, CStr, CString},
marker::PhantomData,
path::Path,
ptr::NonNull,
rc::Rc,
};
pub fn eps() -> f64 {
unsafe { ffi::matrust_eps() }
}
pub fn inf() -> f64 {
unsafe { ffi::matrust_inf() }
}
pub fn nan() -> f64 {
unsafe { ffi::matrust_nan() }
}
pub fn is_finite(value: f64) -> bool {
unsafe { ffi::matrust_is_finite(value) != 0 }
}
pub fn is_inf(value: f64) -> bool {
unsafe { ffi::matrust_is_inf(value) != 0 }
}
pub fn is_nan(value: f64) -> bool {
unsafe { ffi::matrust_is_nan(value) != 0 }
}
pub struct MxBuffer<'mex> {
raw: NonNull<u8>,
len: usize,
_brand: PhantomData<fn(&'mex mut ()) -> &'mex mut ()>,
_thread: PhantomData<Rc<()>>,
}
impl MxBuffer<'_> {
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn as_bytes(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.raw.as_ptr(), self.len) }
}
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.raw.as_ptr(), self.len) }
}
pub fn resize(&mut self, len: usize) -> Result<()> {
if len > isize::MAX as usize {
return Err(Error::new(
ErrorKind::Bounds,
"resize MATLAB buffer",
"buffer is too large for a Rust slice",
));
}
let raw = unsafe { ffi::matrust_realloc(self.raw.as_ptr().cast(), len.max(1)) };
let raw: NonNull<u8> = NonNull::new(raw.cast())
.ok_or_else(|| Error::allocation("reallocate MATLAB buffer"))?;
if len > self.len {
unsafe { raw.as_ptr().add(self.len).write_bytes(0, len - self.len) };
}
self.raw = raw;
self.len = len;
Ok(())
}
}
impl Drop for MxBuffer<'_> {
fn drop(&mut self) {
unsafe { ffi::matrust_free(self.raw.as_ptr().cast()) }
}
}
pub struct Matlab<'mex> {
_brand: PhantomData<fn(&'mex mut ()) -> &'mex mut ()>,
_thread: PhantomData<Rc<()>>,
}
#[must_use = "dropping the module lock immediately unlocks the MEX module"]
pub struct ModuleLock {
active: bool,
_thread: PhantomData<Rc<()>>,
}
impl ModuleLock {
pub fn release(mut self) {
unsafe { ffi::matrust_unlock() };
self.active = false;
}
}
impl Drop for ModuleLock {
fn drop(&mut self) {
if self.active {
unsafe { ffi::matrust_unlock() };
}
}
}
impl<'mex> Matlab<'mex> {
pub(crate) fn new() -> Self {
Self {
_brand: PhantomData,
_thread: PhantomData,
}
}
pub unsafe fn attach() -> Self {
Self::new()
}
pub fn duplicate(&self, value: ArrayRef<'_>) -> Result<OwnedArray<'mex>> {
let raw = unsafe { ffi::matrust_array_duplicate(value.as_ptr()) };
let raw = NonNull::new(raw).ok_or_else(|| Error::allocation("duplicate array"))?;
Ok(unsafe { OwnedArray::from_raw(raw) })
}
pub fn property(
&self,
object: ArrayRef<'_>,
index: usize,
name: &CStr,
) -> Result<OwnedArray<'mex>> {
runtime::require_unborrowed("get property")?;
if index >= object.numel() {
return Err(Error::bounds("get property", index, object.numel()));
}
let raw = unsafe { ffi::matrust_property_get(object.as_ptr(), index, name.as_ptr()) };
NonNull::new(raw)
.map(|raw| unsafe { OwnedArray::from_raw(raw) })
.ok_or_else(|| Error::new(ErrorKind::Native, "get property", format!("{name:?}")))
}
pub fn with_property(
&mut self,
object: ArrayRef<'_>,
index: usize,
name: &CStr,
value: ArrayRef<'_>,
) -> Result<OwnedArray<'mex>> {
runtime::require_unborrowed("set property")?;
if index >= object.numel() {
return Err(Error::bounds("set property", index, object.numel()));
}
let name = name.to_str().map_err(|_| {
Error::new(ErrorKind::InvalidInput, "set property", "name is not UTF-8")
})?;
let dot = self.char_row(".")?;
let property = self.char_row(name)?;
let subscript = if object.numel() == 1 {
let [subscript] = self.call_array(c"substruct", &[dot.as_ref(), property.as_ref()])?;
subscript
} else {
let paren = self.char_row("()")?;
let mut indices = self.cell(&[1, 1])?;
let index = u64::try_from(index + 1)
.map_err(|_| Error::new(ErrorKind::Bounds, "set property", "index is too large"))?;
drop(
indices
.as_mut()
.replace_cell(0, Some(self.scalar(index)?))?,
);
let [subscript] = self.call_array(
c"substruct",
&[
paren.as_ref(),
indices.as_ref(),
dot.as_ref(),
property.as_ref(),
],
)?;
subscript
};
let [updated] = self
.call_array(c"subsasgn", &[object, subscript.as_ref(), value])
.map_err(|error| error.context("set property"))?;
Ok(updated)
}
pub fn function_name(&self) -> &CStr {
unsafe { CStr::from_ptr(ffi::matrust_function_name()) }
}
pub fn printf(&mut self, text: &str) -> Result<()> {
let text = CString::new(text)
.map_err(|_| Error::new(ErrorKind::InvalidInput, "printf", "text contains NUL"))?;
let status = unsafe { ffi::matrust_printf(text.as_ptr()) };
(status >= 0)
.then_some(())
.ok_or_else(|| Error::from_native_status("printf", status))
}
pub fn warning(&mut self, id: &CStr, text: &str) -> Result<()> {
let text = CString::new(text)
.map_err(|_| Error::new(ErrorKind::InvalidInput, "warning", "text contains NUL"))?;
unsafe { ffi::matrust_warning(id.as_ptr(), text.as_ptr()) };
Ok(())
}
pub fn calloc(&self, len: usize) -> Result<MxBuffer<'mex>> {
if len > isize::MAX as usize {
return Err(Error::new(
ErrorKind::Bounds,
"allocate MATLAB buffer",
"buffer is too large for a Rust slice",
));
}
let bytes = if len == 0 { 1 } else { len };
let raw = unsafe { ffi::matrust_calloc(1, bytes) };
let raw =
NonNull::new(raw.cast()).ok_or_else(|| Error::allocation("allocate MATLAB buffer"))?;
Ok(MxBuffer {
raw,
len,
_brand: PhantomData,
_thread: PhantomData,
})
}
pub fn lock(&mut self) -> ModuleLock {
unsafe { ffi::matrust_lock() };
ModuleLock {
active: true,
_thread: PhantomData,
}
}
pub fn is_locked(&self) -> bool {
unsafe { ffi::matrust_is_locked() != 0 }
}
pub fn workspace_get(&mut self, space: Workspace, name: &CStr) -> Result<OwnedArray<'mex>> {
let raw = unsafe { ffi::matrust_workspace_get(space.as_ptr(), name.as_ptr()) };
NonNull::new(raw)
.map(|raw| unsafe { OwnedArray::from_raw(raw) })
.ok_or_else(|| {
Error::new(
ErrorKind::Workspace,
"get workspace variable",
format!("{name:?}"),
)
})
}
pub fn workspace_scope(&self, space: Workspace) -> WorkspaceScope<'_, 'mex> {
WorkspaceScope {
space,
_context: self,
}
}
pub fn workspace_put(
&mut self,
space: Workspace,
name: &CStr,
value: ArrayRef<'_>,
) -> Result<()> {
runtime::require_unborrowed("put workspace variable")?;
let status =
unsafe { ffi::matrust_workspace_put(space.as_ptr(), name.as_ptr(), value.as_ptr()) };
if status == 0 {
Ok(())
} else {
Err(Error::from_native_status("put workspace variable", status))
}
}
pub fn call(
&mut self,
name: &CStr,
inputs: &[ArrayRef<'_>],
output_count: usize,
) -> Result<Vec<OwnedArray<'mex>>> {
runtime::require_unborrowed("call MATLAB")?;
call_raw(
name,
inputs.iter().map(|v| v.as_ptr().cast_mut()).collect(),
output_count,
)
}
pub fn call_array<const N: usize>(
&mut self,
name: &CStr,
inputs: &[ArrayRef<'_>],
) -> Result<[OwnedArray<'mex>; N]> {
self.call(name, inputs, N)?
.try_into()
.map_err(|_| Error::new(ErrorKind::Native, "call MATLAB", "unexpected output count"))
}
pub fn eval(&mut self, command: &str) -> Result<()> {
runtime::require_unborrowed("evaluate MATLAB")?;
let command = CString::new(command).map_err(|_| {
Error::new(
ErrorKind::InvalidInput,
"evaluate MATLAB",
"command contains NUL",
)
})?;
let trap = unsafe { ffi::matrust_eval_with_trap(command.as_ptr()) };
if let Some(trap) = NonNull::new(trap) {
Err(callback_error(
trap,
"evaluate MATLAB",
"command failed without exception details".to_owned(),
))
} else {
Ok(())
}
}
}
fn call_raw<'mex>(
name: &CStr,
mut raw_inputs: Vec<*mut ffi::RawArray>,
output_count: usize,
) -> Result<Vec<OwnedArray<'mex>>> {
if output_count > 50 || raw_inputs.len() > 50 {
return Err(Error::new(
ErrorKind::InvalidInput,
"call MATLAB",
"MATLAB callbacks support at most 50 inputs and 50 outputs",
));
}
let count = i32::try_from(output_count)
.map_err(|_| Error::new(ErrorKind::InvalidInput, "call MATLAB", "too many outputs"))?;
let mut outputs = vec![std::ptr::null_mut(); output_count];
let input_count = i32::try_from(raw_inputs.len())
.map_err(|_| Error::new(ErrorKind::InvalidInput, "call MATLAB", "too many inputs"))?;
let outputs_ptr = if outputs.is_empty() {
std::ptr::null_mut()
} else {
outputs.as_mut_ptr()
};
let inputs_ptr = if raw_inputs.is_empty() {
std::ptr::null_mut()
} else {
raw_inputs.as_mut_ptr()
};
let trap = unsafe {
ffi::matrust_call_with_trap(count, outputs_ptr, input_count, inputs_ptr, name.as_ptr())
};
if let Some(trap) = NonNull::new(trap) {
for raw in outputs {
if !raw.is_null() {
unsafe { runtime::destroy_or_defer(NonNull::new_unchecked(raw)) }
}
}
return Err(callback_error(
trap,
"call MATLAB",
format!("{name:?} failed without exception details"),
));
}
if outputs.iter().any(|raw| raw.is_null()) {
for raw in outputs {
if !raw.is_null() {
unsafe { runtime::destroy_or_defer(NonNull::new_unchecked(raw)) }
}
}
return Err(Error::new(
ErrorKind::Callback,
"call MATLAB",
"MATLAB returned a null output",
));
}
let mut result = Vec::with_capacity(output_count);
for raw in outputs {
let raw = NonNull::new(raw).ok_or_else(|| {
Error::new(
ErrorKind::Callback,
"call MATLAB",
"MATLAB returned a null output",
)
})?;
result.push(unsafe { OwnedArray::from_raw(raw) });
}
Ok(result)
}
fn callback_error(raw: NonNull<ffi::RawArray>, operation: &'static str, fallback: String) -> Error {
let trap = unsafe { OwnedArray::from_raw(raw) };
let identifier = trap
.property(0, c"identifier")
.and_then(|value| value.as_ref().to_utf8())
.ok();
let message = trap
.property(0, c"message")
.and_then(|value| value.as_ref().to_utf8())
.ok();
let detail = match (identifier.as_deref(), message.as_deref()) {
(Some(identifier), Some(message)) if !identifier.is_empty() => {
format!("{identifier}: {message}")
}
(_, Some(message)) => message.to_owned(),
(Some(identifier), None) if !identifier.is_empty() => {
format!("{identifier}: {fallback}")
}
_ => fallback,
};
Error::new(ErrorKind::Callback, operation, detail)
.with_matlab_error(MatlabErrorInfo::new(identifier, message))
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Workspace {
Caller,
Global,
Base,
}
impl Workspace {
fn as_ptr(self) -> *const c_char {
match self {
Self::Caller => c"caller".as_ptr(),
Self::Global => c"global".as_ptr(),
Self::Base => c"base".as_ptr(),
}
}
}
pub struct WorkspaceScope<'a, 'mex> {
space: Workspace,
_context: &'a Matlab<'mex>,
}
impl<'a, 'mex> WorkspaceScope<'a, 'mex> {
pub fn get(&self, name: &CStr) -> Result<WorkspaceValue<'a>> {
let raw = unsafe { ffi::matrust_workspace_borrow(self.space.as_ptr(), name.as_ptr()) };
let raw = NonNull::new(raw.cast_mut()).ok_or_else(|| {
Error::new(
ErrorKind::Workspace,
"borrow workspace variable",
format!("{name:?}"),
)
})?;
Ok(WorkspaceValue {
raw,
_guard: runtime::begin_external_borrow(),
_context: PhantomData,
})
}
pub fn call(
self,
name: &CStr,
inputs: impl IntoIterator<Item = CallInput<'a>>,
output_count: usize,
) -> Result<Vec<OwnedArray<'mex>>> {
let _handoff = runtime::begin_callback_handoff();
let inputs: Vec<_> = inputs.into_iter().collect();
let raw = inputs.iter().map(CallInput::as_ptr).collect();
drop(inputs);
runtime::require_unborrowed("call MATLAB")?;
call_raw(name, raw, output_count)
}
pub fn call_array<const N: usize>(
self,
name: &CStr,
inputs: impl IntoIterator<Item = CallInput<'a>>,
) -> Result<[OwnedArray<'mex>; N]> {
self.call(name, inputs, N)?
.try_into()
.map_err(|_| Error::new(ErrorKind::Native, "call MATLAB", "unexpected output count"))
}
}
pub struct WorkspaceValue<'a> {
raw: NonNull<ffi::RawArray>,
_guard: runtime::ExternalBorrowGuard,
_context: PhantomData<&'a Matlab<'a>>,
}
impl WorkspaceValue<'_> {
pub fn as_ref(&self) -> ArrayRef<'_> {
unsafe { ArrayRef::from_raw(self.raw) }
}
pub fn is_plain(&self) -> bool {
self.as_ref().is_plain()
}
pub fn plain(&self) -> Result<PlainArrayRef<'_>> {
self.as_ref().try_into()
}
}
pub enum CallInput<'a> {
Borrowed(ArrayRef<'a>),
Workspace(WorkspaceValue<'a>),
}
impl<'a> From<ArrayRef<'a>> for CallInput<'a> {
fn from(value: ArrayRef<'a>) -> Self {
Self::Borrowed(value)
}
}
impl<'a> From<WorkspaceValue<'a>> for CallInput<'a> {
fn from(value: WorkspaceValue<'a>) -> Self {
Self::Workspace(value)
}
}
impl CallInput<'_> {
fn as_ptr(&self) -> *mut ffi::RawArray {
match self {
Self::Borrowed(value) => value.as_ptr().cast_mut(),
Self::Workspace(value) => value.raw.as_ptr(),
}
}
}
pub struct Inputs<'mex, const N: usize> {
values: [ArrayRef<'mex>; N],
}
impl<'mex, const N: usize> Inputs<'mex, N> {
fn new(values: [ArrayRef<'mex>; N]) -> Self {
Self { values }
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn get(&self, index: usize) -> Option<ArrayRef<'mex>> {
self.values.get(index).copied()
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = ArrayRef<'mex>> + '_ {
self.values.iter().copied()
}
pub fn require<const M: usize>(&self) -> Result<[ArrayRef<'mex>; M]> {
if self.len() != M {
return Err(Error::new(
ErrorKind::InvalidInput,
"MEX inputs",
format!("expected {M} inputs, got {}", self.len()),
));
}
Ok(std::array::from_fn(|index| self.values[index]))
}
pub fn into_array(self) -> [ArrayRef<'mex>; N] {
self.values
}
}
pub struct DynInputs<'mex> {
values: Vec<ArrayRef<'mex>>,
}
impl<'mex> DynInputs<'mex> {
fn new(values: Vec<ArrayRef<'mex>>) -> Self {
Self { values }
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn get(&self, index: usize) -> Option<ArrayRef<'mex>> {
self.values.get(index).copied()
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = ArrayRef<'mex>> + '_ {
self.values.iter().copied()
}
pub fn require<const N: usize>(&self) -> Result<[ArrayRef<'mex>; N]> {
if self.len() != N {
return Err(Error::new(
ErrorKind::InvalidInput,
"MEX inputs",
format!("expected {N} inputs, got {}", self.len()),
));
}
Ok(std::array::from_fn(|index| self.values[index]))
}
}
pub struct Outputs<'mex, const N: usize = { usize::MAX }> {
requested: usize,
values: Vec<Option<OwnedArray<'mex>>>,
}
impl<'mex, const N: usize> Outputs<'mex, N> {
fn new(count: usize) -> Self {
Self {
requested: count,
values: (0..count.max(1)).map(|_| None).collect(),
}
}
pub fn len(&self) -> usize {
self.requested
}
pub fn requested(&self) -> usize {
self.requested
}
pub fn is_empty(&self) -> bool {
self.requested == 0
}
pub fn require_len(&self, count: usize) -> Result<()> {
if self.len() != count {
return Err(Error::new(
ErrorKind::InvalidInput,
"MEX outputs",
format!("expected {count} outputs, got {}", self.len()),
));
}
Ok(())
}
pub fn require_range(&self, range: impl std::ops::RangeBounds<usize>) -> Result<()> {
if !range.contains(&self.requested) {
return Err(Error::new(
ErrorKind::InvalidInput,
"MEX outputs",
format!("unsupported output count: {}", self.requested),
));
}
Ok(())
}
pub fn set(&mut self, index: usize, value: OwnedArray<'mex>) -> Result<()> {
if index >= self.requested {
return Err(Error::bounds("set output", index, self.requested));
}
self.set_slot(index, value)
}
pub fn set_first(&mut self, value: OwnedArray<'mex>) -> Result<()> {
self.set_slot(0, value)
}
fn set_slot(&mut self, index: usize, value: OwnedArray<'mex>) -> Result<()> {
let slot = self
.values
.get_mut(index)
.expect("first or requested output slot");
if slot.is_some() {
return Err(Error::new(
ErrorKind::InvalidInput,
"set output",
"output slot already set",
));
}
*slot = Some(value);
Ok(())
}
pub fn take(&mut self, index: usize) -> Result<Option<OwnedArray<'mex>>> {
if index >= self.requested {
return Err(Error::bounds("take output", index, self.requested));
}
self.values
.get_mut(index)
.ok_or_else(|| Error::bounds("take output", index, self.requested))
.map(Option::take)
}
fn validate(&self) -> Result<()> {
if let Some(index) = self.values[..self.requested]
.iter()
.position(Option::is_none)
{
return Err(Error::new(
ErrorKind::InvalidInput,
"MEX outputs",
format!("requested output {index} was not set"),
));
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MatVersion {
Default,
V4,
V6,
V7,
V73,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum OpenMode {
Read,
Update,
Write(MatVersion),
}
impl OpenMode {
fn as_cstr(self) -> &'static CStr {
match self {
Self::Read => c"r",
Self::Update => c"u",
Self::Write(MatVersion::Default) => c"w",
Self::Write(MatVersion::V4) => c"w4",
Self::Write(MatVersion::V6) => c"w6",
Self::Write(MatVersion::V7) => c"w7",
Self::Write(MatVersion::V73) => c"w7.3",
}
}
}
pub struct MatFile<'mex> {
raw: Option<NonNull<ffi::RawFile>>,
mode: OpenMode,
_brand: PhantomData<fn(&'mex mut ()) -> &'mex mut ()>,
_thread: PhantomData<Rc<()>>,
}
impl<'mex> MatFile<'mex> {
pub fn open(_context: &Matlab<'mex>, path: impl AsRef<Path>, mode: OpenMode) -> Result<Self> {
let path = path_cstring(path.as_ref())?;
let raw = unsafe { ffi::matrust_mat_open(path.as_ptr(), mode.as_cstr().as_ptr()) };
NonNull::new(raw)
.map(|raw| Self {
raw: Some(raw),
mode,
_brand: PhantomData,
_thread: PhantomData,
})
.ok_or_else(|| Error::new(ErrorKind::Open, "open MAT-file", format!("{path:?}")))
}
pub fn create(context: &Matlab<'mex>, path: impl AsRef<Path>) -> Result<Self> {
Self::open(context, path, OpenMode::Write(MatVersion::V7))
}
pub fn create_with_format(
context: &Matlab<'mex>,
path: impl AsRef<Path>,
version: MatVersion,
) -> Result<Self> {
Self::open(context, path, OpenMode::Write(version))
}
fn ptr(&self) -> *mut ffi::RawFile {
self.raw.expect("live MAT-file").as_ptr()
}
fn require_read(&self) -> Result<()> {
if matches!(self.mode, OpenMode::Write(_)) {
Err(Error::new(
ErrorKind::InvalidMode,
"read MAT-file",
"file is write-only",
))
} else {
Ok(())
}
}
fn require_write(&self) -> Result<()> {
if self.mode == OpenMode::Read {
Err(Error::new(
ErrorKind::InvalidMode,
"write MAT-file",
"file is read-only",
))
} else {
Ok(())
}
}
pub fn put(&mut self, name: &CStr, value: ArrayRef<'_>) -> Result<()> {
runtime::require_unborrowed("put MAT variable")?;
self.require_write()?;
validate_name(name)?;
let mut code = 0;
let status = unsafe {
ffi::matrust_mat_put(self.ptr(), name.as_ptr(), value.as_ptr(), 0, &mut code)
};
if status == 0 {
Ok(())
} else {
Err(Error::native(
ErrorKind::Write,
"put MAT variable",
format!("{name:?}"),
status,
code,
))
}
}
pub fn put_global(&mut self, name: &CStr, value: ArrayRef<'_>) -> Result<()> {
runtime::require_unborrowed("put global MAT variable")?;
self.require_write()?;
validate_name(name)?;
let mut code = 0;
let status = unsafe {
ffi::matrust_mat_put(self.ptr(), name.as_ptr(), value.as_ptr(), 1, &mut code)
};
if status == 0 {
Ok(())
} else {
Err(Error::native(
ErrorKind::Write,
"put global MAT variable",
format!("{name:?}"),
status,
code,
))
}
}
pub fn put_plain(&mut self, name: &CStr, value: PlainArrayRef<'_>) -> Result<()> {
self.require_write()?;
validate_name(name)?;
let mut code = 0;
let status = unsafe {
ffi::matrust_mat_put(
self.ptr(),
name.as_ptr(),
value.as_ref().as_ptr(),
0,
&mut code,
)
};
if status == 0 {
Ok(())
} else {
Err(Error::native(
ErrorKind::Write,
"put plain MAT variable",
format!("{name:?}"),
status,
code,
))
}
}
pub fn get(&mut self, name: &CStr) -> Result<OwnedArray<'mex>> {
runtime::require_unborrowed("get MAT variable")?;
self.require_read()?;
validate_name(name)?;
let mut code = 0;
let raw = unsafe { ffi::matrust_mat_get(self.ptr(), name.as_ptr(), 0, &mut code) };
NonNull::new(raw)
.map(|raw| unsafe { OwnedArray::from_raw(raw) })
.ok_or_else(|| {
Error::native(
ErrorKind::Read,
"get MAT variable",
format!("{name:?}"),
-1,
code,
)
})
}
pub fn info(&mut self, name: &CStr) -> Result<ArrayInfo<'mex>> {
self.require_read()?;
validate_name(name)?;
let mut code = 0;
let raw = unsafe { ffi::matrust_mat_get(self.ptr(), name.as_ptr(), 1, &mut code) };
NonNull::new(raw)
.map(|raw| ArrayInfo {
raw,
context: PhantomData,
})
.ok_or_else(|| {
Error::native(
ErrorKind::Read,
"get MAT header",
format!("{name:?}"),
-1,
code,
)
})
}
pub fn delete(&mut self, name: &CStr) -> Result<()> {
self.require_write()?;
validate_name(name)?;
let mut code = 0;
let status = unsafe { ffi::matrust_mat_delete(self.ptr(), name.as_ptr(), &mut code) };
if status == 0 {
Ok(())
} else {
Err(Error::native(
ErrorKind::Write,
"delete MAT variable",
format!("{name:?}"),
status,
code,
))
}
}
pub fn variables(&mut self) -> Result<Vec<CString>> {
self.require_read()?;
let (mut count, mut code) = (0, 0);
let ptr = unsafe { ffi::matrust_mat_directory(self.ptr(), &mut count, &mut code) };
if count < 0 || (count > 0 && ptr.is_null()) {
return Err(Error::native(
ErrorKind::Read,
"MAT directory",
"invalid directory",
count,
code,
));
}
struct Dir(*mut *mut c_char);
impl Drop for Dir {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { ffi::matrust_free(self.0.cast()) }
}
}
}
let names = Dir(ptr);
(0..count as usize)
.map(|i| {
let p = unsafe { *names.0.add(i) };
if p.is_null() {
Err(Error::new(ErrorKind::Native, "MAT directory", "null name"))
} else {
Ok(unsafe { CStr::from_ptr(p) }.to_owned())
}
})
.collect()
}
pub fn last_error(&mut self) -> MatError {
MatError(unsafe { ffi::matrust_mat_error(self.ptr()) })
}
pub fn stream(&mut self) -> Option<FileStream<'_>> {
NonNull::new(unsafe { ffi::matrust_mat_stream(self.ptr()) }).map(|raw| FileStream {
raw,
_borrow: PhantomData,
_thread: PhantomData,
})
}
pub fn close(mut self) -> Result<()> {
let raw = self.raw.take().ok_or_else(|| {
Error::new(
ErrorKind::Close,
"close MAT-file",
"file handle was already closed",
)
})?;
let status = unsafe { ffi::matrust_mat_close(raw.as_ptr()) };
if status == 0 {
Ok(())
} else {
Err(Error::native_status_kind(
ErrorKind::Close,
"close MAT-file",
status,
))
}
}
}
impl Drop for MatFile<'_> {
fn drop(&mut self) {
if let Some(raw) = self.raw.take() {
unsafe {
ffi::matrust_mat_close(raw.as_ptr());
}
}
}
}
pub struct FileStream<'a> {
raw: NonNull<c_void>,
_borrow: PhantomData<&'a mut ()>,
_thread: PhantomData<Rc<()>>,
}
impl FileStream<'_> {
pub fn is_eof(&self) -> bool {
unsafe { ffi::matrust_stream_eof(self.raw.as_ptr()) != 0 }
}
pub fn has_error(&self) -> bool {
unsafe { ffi::matrust_stream_error(self.raw.as_ptr()) != 0 }
}
pub fn clear_error(&mut self) {
unsafe { ffi::matrust_stream_clear(self.raw.as_ptr()) }
}
pub fn position(&self) -> Result<u64> {
u64::try_from(unsafe { ffi::matrust_stream_position(self.raw.as_ptr()) }).map_err(|_| {
Error::new(
ErrorKind::Native,
"stream position",
"native stream returned a negative position",
)
})
}
}
pub struct ArrayInfo<'mex> {
raw: NonNull<ffi::RawArray>,
context: PhantomData<&'mex Matlab<'mex>>,
}
impl ArrayInfo<'_> {
fn view(&self) -> ArrayRef<'_> {
unsafe { ArrayRef::from_raw(self.raw) }
}
pub fn dimensions(&self) -> &[usize] {
self.view().dimensions()
}
pub fn numel(&self) -> usize {
self.view().numel()
}
pub fn class(&self) -> Option<Class> {
self.view().class()
}
pub fn class_name(&self) -> &CStr {
self.view().class_name()
}
pub fn is_sparse(&self) -> bool {
self.view().is_sparse()
}
pub fn is_complex(&self) -> bool {
self.view().is_complex()
}
pub fn is_global(&self) -> bool {
self.view().is_from_global_workspace()
}
}
impl Drop for ArrayInfo<'_> {
fn drop(&mut self) {
unsafe { runtime::destroy_or_defer(self.raw) }
}
}
pub struct Named<T> {
pub name: CString,
pub value: T,
}
pub struct Variables<'mex> {
file: MatFile<'mex>,
remaining: usize,
done: bool,
}
impl<'mex> Variables<'mex> {
pub fn open(context: &Matlab<'mex>, path: impl AsRef<Path>) -> Result<Self> {
let mut directory = MatFile::open(context, &path, OpenMode::Read)?;
let remaining = directory.variables()?.len();
directory.close()?;
Ok(Self {
file: MatFile::open(context, path, OpenMode::Read)?,
remaining,
done: false,
})
}
pub fn close(self) -> Result<()> {
self.file.close()
}
}
impl<'mex> Iterator for Variables<'mex> {
type Item = Result<Named<OwnedArray<'mex>>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done || self.remaining == 0 {
self.done = true;
return None;
}
if let Err(error) = runtime::require_unborrowed("next MAT variable") {
return Some(Err(error));
}
let mut name: *const c_char = std::ptr::null();
let mut code = 0;
let raw = unsafe { ffi::matrust_mat_next(self.file.ptr(), &mut name, 0, &mut code) };
let raw = match NonNull::new(raw) {
Some(raw) => raw,
None => {
self.done = true;
return Some(Err(Error::native(
ErrorKind::UnexpectedEnd,
"next MAT variable",
"native reader ended early",
-1,
code,
)));
}
};
if name.is_null() {
self.done = true;
unsafe { runtime::destroy_or_defer(raw) };
return Some(Err(Error::new(
ErrorKind::Native,
"next MAT variable",
"null variable name",
)));
}
let name = unsafe { CStr::from_ptr(name) }.to_owned();
self.remaining -= 1;
let value = unsafe { OwnedArray::from_raw(raw) };
Some(Ok(Named { name, value }))
}
}
pub struct VariableInfos<'mex> {
file: MatFile<'mex>,
remaining: usize,
done: bool,
}
impl<'mex> VariableInfos<'mex> {
pub fn open(context: &Matlab<'mex>, path: impl AsRef<Path>) -> Result<Self> {
let mut directory = MatFile::open(context, &path, OpenMode::Read)?;
let remaining = directory.variables()?.len();
directory.close()?;
Ok(Self {
file: MatFile::open(context, path, OpenMode::Read)?,
remaining,
done: false,
})
}
pub fn close(self) -> Result<()> {
self.file.close()
}
}
impl<'mex> Iterator for VariableInfos<'mex> {
type Item = Result<Named<ArrayInfo<'mex>>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done || self.remaining == 0 {
self.done = true;
return None;
}
let mut name: *const c_char = std::ptr::null();
let mut code = 0;
let raw = unsafe { ffi::matrust_mat_next(self.file.ptr(), &mut name, 1, &mut code) };
let raw = match NonNull::new(raw) {
Some(raw) => raw,
None => {
self.done = true;
return Some(Err(Error::native(
ErrorKind::UnexpectedEnd,
"next MAT header",
"native reader ended early",
-1,
code,
)));
}
};
if name.is_null() {
self.done = true;
unsafe { runtime::destroy_or_defer(raw) };
return Some(Err(Error::new(
ErrorKind::Native,
"next MAT header",
"null variable name",
)));
}
let name = unsafe { CStr::from_ptr(name) }.to_owned();
self.remaining -= 1;
let value = ArrayInfo {
raw,
context: PhantomData,
};
Some(Ok(Named { name, value }))
}
}
fn validate_name(name: &CStr) -> Result<()> {
if name.to_bytes().is_empty() {
Err(Error::new(
ErrorKind::InvalidInput,
"variable name",
"empty name",
))
} else {
Ok(())
}
}
fn path_cstring(path: &Path) -> Result<CString> {
let text = path
.to_str()
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, "path", "path is not valid Unicode"))?;
CString::new(text).map_err(|_| Error::new(ErrorKind::InvalidInput, "path", "path contains NUL"))
}
#[macro_export]
macro_rules! mex_entrypoint {
($handler:path) => {
$crate::mex_entrypoint!(@dispatch $handler, dispatch);
};
($handler:path, dynamic) => {
$crate::mex_entrypoint!(@dispatch $handler, dispatch_dynamic);
};
(@dispatch $handler:path, $dispatch:ident) => {
#[used]
#[no_mangle]
pub static matrust_mex_link: unsafe extern "C" fn() = $crate::__private::matrust_mex_anchor;
#[no_mangle]
pub unsafe extern "C" fn matrust_mex_dispatch(
nlhs: i32,
plhs: *mut *mut $crate::__private::RawArray,
nrhs: i32,
prhs: *const *const $crate::__private::RawArray,
id: *mut std::ffi::c_char,
id_len: usize,
message: *mut std::ffi::c_char,
message_len: usize,
) -> i32 {
unsafe {
$crate::__private::$dispatch(
$handler,
nlhs,
plhs,
nrhs,
prhs,
id,
id_len,
message,
message_len,
)
}
}
};
}
#[doc(hidden)]
pub use ffi::RawArray;
#[allow(missing_docs)]
pub mod raw {
pub use crate::ffi::*;
}