# Design
`matlas` makes MATLAB's ownership conventions visible in Rust's type system.
The C shim is private; safe callers never manipulate an `mxArray*` directly.
## Ownership categories
- `OwnedArray<'mex>` is the sole owner. Dropping it retires its `mxArray` for
destruction at a safe runtime boundary.
- `ArrayRef<'a>` is a read-only borrow from an input, owned array, cell, or
struct. It has no destructor and cannot be transferred to MATLAB.
- `ArrayMut<'a, 'mex>` is an exclusive borrow of an owned or persistent array.
Replacing a cell/field consumes an `OwnedArray`. When the view comes from
persistent storage, the displaced child is deep-copied before returning it;
the original is destroyed after detachment. Nested cell views retain this
distinction, so only temporary copies can become MEX outputs.
- `WorkspaceScope<'a, 'mex>` can coexist with MAT-file handles while multiple
`WorkspaceValue<'a>` pointers from `mexGetVariablePtr` are fetched. Each value
holds an external-borrow guard. Operations that can run MATLAB code, including
property accessors and generic MAT-file serialization, return `Busy` while a
value is live. Its consuming `call` accepts workspace values and ordinary
`ArrayRef` inputs in argument order. Workspace values are released immediately before
`mexCallMATLABWithTrap`; a live value omitted from the call is rejected by
the runtime guard. A handoff guard prevents retired arrays from being
destroyed between releasing the workspace guards and passing the pointers
to MATLAB. After the callback, old workspace pointers cannot be read.
- `PlainArrayRef<'a>` validates the native class ID before `MatFile::put_plain`
writes a borrowed array. Only numeric, logical, and character classes are
accepted, including numeric/logical sparse arrays. Cell, struct, string, and
object arrays cannot enter this path because their serialization can run
user-defined MATLAB code. Generic `put` and `put_global` remain available
when no workspace value is borrowed.
- `PersistentArray` owns a generation-checked persistent slot and may be stored
between MEX invocations. Reading, mutating, or explicitly removing it
requires the current invocation's `Matlab<'mex>` context. Dropping it
retires the MATLAB array even if a workspace value is borrowed; the MEX exit
hook is a final cleanup path. Borrowed children stay under the parent; use
`Matlab::duplicate` before passing one to a MEX output.
- `ArrayInfo<'mex>` owns metadata returned by `matGetVariableInfo` but exposes
no public conversion to `ArrayRef`, because MATLAB fills its data pointers
with non-dereferenceable sentinels.
The `Matlab<'mex>` brand is invariant and thread-bound. MEX entrypoints create
it internally; `Matlab::attach` is unsafe for standalone/manual integration.
`MatFile<'mex>` stores the invocation brand without borrowing the `Matlab`
variable, so a file may remain open across `Matlab::call`. Persistent read-only
views borrow their handle and the invocation lifetime, not the context
reference. Persistent mutable views retain their context borrow.
`Matlab::lock` returns a thread-bound `ModuleLock` guard whose destructor
balances exactly one `mexLock`; raw manual unlock remains outside the safe API.
Retired arrays are destroyed only when no workspace borrow or callback handoff
is active. Dropping a workspace borrow never destroys arrays. The runtime
releases its internal borrow before calling `mxDestroyArray`.
`Inputs<'mex, N>` contains exactly `N` validated input views. `DynInputs<'mex>`
keeps a variable count and offers `require::<N>()` for an explicit exact-count
check. `Outputs<'mex, N>` requires exactly `N` explicit outputs; a dynamic
`Outputs<'mex>` handler may accept a range. `requested()` excludes the optional
`ans` slot. `set_first()` can fill that slot when no output was requested.
All explicitly requested slots are checked before any output owner is passed
to MATLAB.
## Workspace-borrow callback audit
| `Matlab::call`, `eval`, `workspace_put` | `Busy`; also require `&mut Matlab` |
| `Matlab::property`, `OwnedArray::property`, `Matlab::with_property` | `Busy`; accessors can run MATLAB code |
| `MatFile::put`, `put_global`, `get`, `Variables::next` | `Busy`; object serialization/deserialization can run MATLAB code |
| `MatFile::put_plain` | Allowed for validated primitive arrays |
| Array inspection, constructors, duplication, MAT-file headers/directory/handle operations | Allowed; these do not invoke MATLAB user code |
Other safe context-mutating operations require `&mut Matlab` and are excluded
by the scope's shared borrow. Raw API calls are outside this guarantee.
## Calls and errors
`Matlab::call` and `eval` use MATLAB's trap APIs. A trapped exception becomes a
`Callback` error after all temporary outputs are destroyed. The entrypoint
converts Rust `Result` and panics to MATLAB errors only after Rust destructors
have run. Native aborts and MATLAB out-of-memory termination are outside any
Rust destructor guarantee because they do not unwind the Rust stack.
`MatFile` uses a separate owner for every file handle. `close(self)` reports
the final native status; `Drop` closes once when the caller does not inspect
that status. Returned arrays remain valid after the file is closed. Full-value
reads and sequential value iteration also require no active workspace borrow
because object deserialization can run `loadobj`. Header-only reads, directory
listing, and file-handle operations do not invoke MATLAB user code.