use std::fmt;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct MatError(pub i32);
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidInput,
Type,
Bounds,
Allocation,
Callback,
Workspace,
Busy,
InvalidMode,
Open,
Read,
Write,
Close,
UnexpectedEnd,
Native,
}
#[derive(Debug)]
pub struct Error {
identifier: Option<String>,
pub kind: ErrorKind,
pub operation: &'static str,
pub detail: String,
pub status: Option<i32>,
pub mat_error: Option<MatError>,
}
impl Error {
pub fn new(kind: ErrorKind, operation: &'static str, detail: impl Into<String>) -> Self {
Self {
identifier: None,
kind,
operation,
detail: detail.into(),
status: None,
mat_error: None,
}
}
pub(crate) fn native(
kind: ErrorKind,
operation: &'static str,
detail: impl Into<String>,
status: i32,
code: i32,
) -> Self {
Self {
identifier: None,
kind,
operation,
detail: detail.into(),
status: Some(status),
mat_error: Some(MatError(code)),
}
}
pub(crate) fn allocation(operation: &'static str) -> Self {
Self::new(
ErrorKind::Allocation,
operation,
"MATLAB returned a null allocation",
)
}
pub(crate) fn native_status(operation: &'static str, status: i32) -> Self {
let mut error = Self::new(ErrorKind::Native, operation, "native operation failed");
error.status = Some(status);
error
}
pub(crate) fn bounds(operation: &'static str, index: usize, length: usize) -> Self {
Self::new(
ErrorKind::Bounds,
operation,
format!("index {index} is outside length {length}"),
)
}
pub(crate) fn type_mismatch(
operation: &'static str,
expected: &str,
actual: crate::ArrayRef<'_>,
) -> Self {
Self::new(
ErrorKind::Type,
operation,
format!("expected {expected}, got {:?}", actual.class_name()),
)
}
pub fn with_id(mut self, identifier: impl Into<String>) -> crate::Result<Self> {
let identifier = identifier.into();
if identifier.len() > 255
|| identifier.split(':').count() < 2
|| !identifier.split(':').all(|field| {
let mut bytes = field.bytes();
bytes.next().is_some_and(|b| b.is_ascii_alphabetic())
&& bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
})
{
return Err(Self::new(
ErrorKind::InvalidInput,
"error identifier",
"expected colon-separated ASCII identifiers of at most 255 bytes",
));
}
self.identifier = Some(identifier);
Ok(self)
}
pub fn id(&self) -> &str {
self.identifier.as_deref().unwrap_or(match self.kind {
ErrorKind::InvalidInput => "matlas:input:invalid",
ErrorKind::Type => "matlas:array:type",
ErrorKind::Bounds => "matlas:array:bounds",
ErrorKind::Allocation => "matlas:allocation",
ErrorKind::Callback => "matlas:callback",
ErrorKind::Workspace => "matlas:workspace",
ErrorKind::Busy => "matlas:runtime:busy",
ErrorKind::InvalidMode => "matlas:file:mode",
ErrorKind::Open => "matlas:file:open",
ErrorKind::Read | ErrorKind::UnexpectedEnd => "matlas:file:read",
ErrorKind::Write => "matlas:file:write",
ErrorKind::Close => "matlas:file:close",
ErrorKind::Native => "matlas:native",
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.operation, self.detail)?;
if let Some(status) = self.status {
write!(f, " (status {status})")?;
}
if let Some(MatError(code)) = self.mat_error {
write!(f, " (MAT error {code})")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn custom_identifier_is_validated() {
let error = Error::new(ErrorKind::Open, "open", "missing")
.with_id("store:MissingRecordFile")
.unwrap();
assert_eq!(error.id(), "store:MissingRecordFile");
assert_eq!(error.kind, ErrorKind::Open);
for id in ["one", "bad:", "0bad:Good", "good:bad-name", "good:日本語"] {
assert!(Error::new(ErrorKind::Open, "open", "missing")
.with_id(id)
.is_err());
}
assert!(Error::new(ErrorKind::Open, "open", "missing")
.with_id(format!("good:{}", "x".repeat(251)))
.is_err());
}
}