Skip to main content

nuvec_core/
error.rs

1//! The error type returned by fallible operations.
2
3use std::fmt;
4
5use crate::{DType, Device};
6
7/// Why an operation failed.
8#[derive(Debug, Clone, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum Error {
11    /// Operand shapes are incompatible.
12    ShapeMismatch {
13        /// The operation that rejected the shapes.
14        op: &'static str,
15        /// Shape of the left operand.
16        lhs: Vec<usize>,
17        /// Shape of the right operand.
18        rhs: Vec<usize>,
19    },
20    /// Operand element types are incompatible.
21    DTypeMismatch {
22        /// The operation that rejected the types.
23        op: &'static str,
24        /// Element type of the left operand (or of the array).
25        lhs: DType,
26        /// Element type of the right operand (or the requested type).
27        rhs: DType,
28    },
29    /// The number of host values does not match the shape.
30    SizeMismatch {
31        /// Element count implied by the shape.
32        expected: usize,
33        /// Number of values provided.
34        actual: usize,
35    },
36    /// The operation does not support this element type.
37    UnsupportedDType {
38        /// The operation that rejected the type.
39        op: &'static str,
40        /// The unsupported element type.
41        dtype: DType,
42    },
43    /// Memory for this many bytes could not be allocated (or exceeds the memory limit).
44    OutOfMemory(usize),
45    /// The device has no backend yet.
46    UnsupportedDevice(Device),
47    /// An argument is invalid for another reason.
48    InvalidArgument(String),
49}
50
51/// `Result` with [`Error`] as the error type.
52pub type Result<T> = std::result::Result<T, Error>;
53
54impl fmt::Display for Error {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Self::ShapeMismatch { op, lhs, rhs } => {
58                write!(f, "{op}: shape mismatch, {lhs:?} vs {rhs:?}")
59            }
60            Self::DTypeMismatch { op, lhs, rhs } => {
61                write!(f, "{op}: dtype mismatch, {lhs} vs {rhs}")
62            }
63            Self::SizeMismatch { expected, actual } => {
64                write!(
65                    f,
66                    "size mismatch: shape needs {expected} values, got {actual}"
67                )
68            }
69            Self::UnsupportedDType { op, dtype } => write!(f, "{op}: not supported for {dtype}"),
70            Self::OutOfMemory(n) => write!(f, "out of memory: cannot allocate {n} bytes"),
71            Self::UnsupportedDevice(device) => write!(f, "no backend for device {device} yet"),
72            Self::InvalidArgument(msg) => write!(f, "invalid argument: {msg}"),
73        }
74    }
75}
76
77impl std::error::Error for Error {}