Skip to main content

matten_ndarray/
error.rs

1//! Error type for `matten-ndarray` (RFC-025 §7, RFC-027 §5).
2//!
3//! The bridge defines its own error type rather than growing core
4//! [`matten::MattenError`] (RFC-022 §8). Conversions return `Result`; a dynamic
5//! tensor returns [`MattenNdarrayError::DynamicTensor`] rather than panicking.
6
7use std::fmt;
8
9/// Errors produced by the `matten` ↔ `ndarray` conversions.
10///
11/// `#[non_exhaustive]` so future variants are not a breaking change.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum MattenNdarrayError {
15    /// A dynamic (`Element`) tensor was passed to a conversion. Convert it to a
16    /// numeric tensor first with `Tensor::try_numeric()`.
17    DynamicTensor,
18    /// The input `ndarray` shape contained a zero-length axis, which core
19    /// `matten` does not support.
20    ZeroSizedAxis(Vec<usize>),
21    /// `ndarray` could not construct the target array (e.g. a shape/length
22    /// mismatch).
23    NdarrayShape(ndarray::ShapeError),
24    /// Core `matten` rejected the conversion (e.g. the rank exceeds `MAX_NDIM`).
25    Matten(matten::MattenError),
26}
27
28impl fmt::Display for MattenNdarrayError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            MattenNdarrayError::DynamicTensor => write!(
32                f,
33                "matten-ndarray error: dynamic tensors cannot be converted; call \
34                 try_numeric() to convert to a numeric tensor first"
35            ),
36            MattenNdarrayError::ZeroSizedAxis(shape) => write!(
37                f,
38                "matten-ndarray error: ndarray shape {shape:?} contains a zero-length \
39                 axis, which matten does not support"
40            ),
41            MattenNdarrayError::NdarrayShape(e) => {
42                write!(
43                    f,
44                    "matten-ndarray error: ndarray could not build the array: {e}"
45                )
46            }
47            MattenNdarrayError::Matten(e) => {
48                write!(
49                    f,
50                    "matten-ndarray error: matten rejected the conversion: {e}"
51                )
52            }
53        }
54    }
55}
56
57impl std::error::Error for MattenNdarrayError {
58    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59        match self {
60            MattenNdarrayError::NdarrayShape(e) => Some(e),
61            MattenNdarrayError::Matten(e) => Some(e),
62            _ => None,
63        }
64    }
65}