Skip to main content

numpy/
error.rs

1//! Defines error types.
2
3use std::error::Error;
4use std::fmt;
5
6use pyo3::{
7    Bound, Py, PyAny, PyErr, PyErrArguments, Python, conversion::IntoPyObject,
8    exceptions::PyTypeError,
9};
10
11use crate::dtype::PyArrayDescr;
12
13/// Array dimensionality should be limited by [`NPY_MAXDIMS`][NPY_MAXDIMS] which is currently 32.ยด
14///
15/// [NPY_MAXDIMS]: https://github.com/numpy/numpy/blob/4c60b3263ac50e5e72f6a909e156314fc3c9cba0/numpy/core/include/numpy/ndarraytypes.h#L40
16pub(crate) const MAX_DIMENSIONALITY_ERR: &str = "unexpected dimensionality: NumPy is expected to limit arrays to 32 or fewer dimensions.\nPlease report a bug against the `rust-numpy` crate.";
17pub(crate) const UNSUPPORTED_STRIDES_ERR: &str =
18    "arrays with strides that are not a multiple of the element size are currently unsupported.";
19
20pub(crate) const DIMENSIONALITY_MISMATCH_ERR: &str = "inconsistent dimensionalities: The dimensionality expected by `PyArray` does not match that given by NumPy.\nPlease report a bug against the `rust-numpy` crate.";
21
22macro_rules! impl_pyerr {
23    ($err_type:ty) => {
24        impl Error for $err_type {}
25
26        impl PyErrArguments for $err_type {
27            fn arguments<'py>(self, py: Python<'py>) -> Py<PyAny> {
28                self.to_string()
29                    .into_pyobject(py)
30                    .unwrap()
31                    .into_any()
32                    .unbind()
33            }
34        }
35
36        impl From<$err_type> for PyErr {
37            fn from(err: $err_type) -> PyErr {
38                PyTypeError::new_err(err)
39            }
40        }
41    };
42}
43
44/// Represents that dimensionalities of the given arrays do not match.
45#[derive(Debug)]
46pub struct DimensionalityError {
47    from: usize,
48    to: usize,
49}
50
51impl DimensionalityError {
52    pub(crate) fn new(from: usize, to: usize) -> Self {
53        Self { from, to }
54    }
55}
56
57impl fmt::Display for DimensionalityError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(
60            f,
61            "dimensionality mismatch:\n from={}, to={}",
62            self.from, self.to
63        )
64    }
65}
66
67impl_pyerr!(DimensionalityError);
68
69/// Represents that types of the given arrays do not match.
70#[derive(Debug)]
71pub struct TypeError<'py> {
72    from: Bound<'py, PyArrayDescr>,
73    to: Bound<'py, PyArrayDescr>,
74}
75
76impl<'py> TypeError<'py> {
77    pub(crate) fn new(from: Bound<'py, PyArrayDescr>, to: Bound<'py, PyArrayDescr>) -> Self {
78        Self { from, to }
79    }
80}
81
82impl fmt::Display for TypeError<'_> {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "type mismatch:\n from={}, to={}", self.from, self.to)
85    }
86}
87
88impl Error for TypeError<'_> {}
89
90struct TypeErrorArguments {
91    from: Py<PyArrayDescr>,
92    to: Py<PyArrayDescr>,
93}
94
95impl PyErrArguments for TypeErrorArguments {
96    fn arguments<'py>(self, py: Python<'py>) -> Py<PyAny> {
97        let err = TypeError {
98            from: self.from.into_bound(py),
99            to: self.to.into_bound(py),
100        };
101
102        err.to_string()
103            .into_pyobject(py)
104            .unwrap()
105            .into_any()
106            .unbind()
107    }
108}
109
110impl From<TypeError<'_>> for PyErr {
111    fn from(err: TypeError<'_>) -> PyErr {
112        let args = TypeErrorArguments {
113            from: err.from.into(),
114            to: err.to.into(),
115        };
116
117        PyTypeError::new_err(args)
118    }
119}
120
121/// Represents that given `Vec` cannot be treated as an array.
122#[derive(Debug)]
123pub struct FromVecError {
124    len: usize,
125    exp_len: usize,
126}
127
128impl FromVecError {
129    pub(crate) fn new(len: usize, exp_len: usize) -> Self {
130        Self { len, exp_len }
131    }
132}
133
134impl fmt::Display for FromVecError {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        write!(
137            f,
138            "invalid length: {}, but expected {}",
139            self.len, self.exp_len
140        )
141    }
142}
143
144impl_pyerr!(FromVecError);
145
146/// Represents that the given array is not compatible with viewing as a Rust slice.
147#[derive(Debug)]
148pub struct AsSliceError;
149impl fmt::Display for AsSliceError {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        write!(f, "The given array is not contiguous or is misaligned.")
152    }
153}
154impl_pyerr!(AsSliceError);
155
156/// Indicates why borrowing an array failed.
157#[derive(Debug)]
158#[non_exhaustive]
159pub enum BorrowError {
160    /// The given array is already borrowed
161    AlreadyBorrowed,
162    /// The given array is not writeable
163    NotWriteable,
164}
165
166impl fmt::Display for BorrowError {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::AlreadyBorrowed => write!(f, "The given array is already borrowed"),
170            Self::NotWriteable => write!(f, "The given array is not writeable"),
171        }
172    }
173}
174
175impl_pyerr!(BorrowError);
176
177/// An internal type used to ignore certain error conditions
178///
179/// This is beneficial when those errors will never reach a public API anyway
180/// but dropping them will improve performance.
181pub(crate) struct IgnoreError;
182
183impl<E> From<E> for IgnoreError
184where
185    PyErr: From<E>,
186{
187    fn from(_err: E) -> Self {
188        Self
189    }
190}