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 /// Formerly returned when the input `ndarray` shape contained a
19 /// zero-length axis. Core `matten` now accepts zero-sized dimensions
20 /// (RFC-111), so `from_arrayd` no longer rejects one — this variant is
21 /// never constructed. Kept, rather than removed, because the enum is
22 /// `#[non_exhaustive]` but a *removed* variant still breaks anyone
23 /// matching on it.
24 #[deprecated(
25 note = "from_arrayd accepts a zero-length axis since RFC-111; this variant is never constructed"
26 )]
27 ZeroSizedAxis(Vec<usize>),
28 /// `ndarray` could not construct the target array (e.g. a shape/length
29 /// mismatch).
30 NdarrayShape(ndarray::ShapeError),
31 /// Core `matten` rejected the conversion (e.g. the rank exceeds `MAX_NDIM`).
32 Matten(matten::MattenError),
33}
34
35impl fmt::Display for MattenNdarrayError {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 match self {
38 MattenNdarrayError::DynamicTensor => write!(
39 f,
40 "matten-ndarray error: dynamic tensors cannot be converted; call \
41 try_numeric() to convert to a numeric tensor first"
42 ),
43 #[allow(deprecated)]
44 MattenNdarrayError::ZeroSizedAxis(shape) => write!(
45 f,
46 "matten-ndarray error: ndarray shape {shape:?} contains a zero-length \
47 axis (unreachable: from_arrayd has accepted these since RFC-111)"
48 ),
49 MattenNdarrayError::NdarrayShape(e) => {
50 write!(
51 f,
52 "matten-ndarray error: ndarray could not build the array: {e}"
53 )
54 }
55 MattenNdarrayError::Matten(e) => {
56 write!(
57 f,
58 "matten-ndarray error: matten rejected the conversion: {e}"
59 )
60 }
61 }
62 }
63}
64
65impl std::error::Error for MattenNdarrayError {
66 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
67 match self {
68 MattenNdarrayError::NdarrayShape(e) => Some(e),
69 MattenNdarrayError::Matten(e) => Some(e),
70 _ => None,
71 }
72 }
73}