sophus_pyo3/pyo3/
errors.rs

1use numpy::PyArray1;
2use numpy::PyArrayMethods;
3use numpy::PyUntypedArrayMethods;
4use pyo3::exceptions::PyOSError;
5use pyo3::Bound;
6use pyo3::PyErr;
7use std::fmt;
8
9/// Error for mismatched array dimensions
10#[derive(Debug)]
11pub struct PyArray1DimMismatch {
12    expected: usize,
13    actual: usize,
14    file: &'static str,
15    line: u32,
16}
17
18impl std::error::Error for PyArray1DimMismatch {}
19
20impl fmt::Display for PyArray1DimMismatch {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(
23            f,
24            "{}:{}   Expected array of dimension {}, got {}",
25            self.file, self.line, self.expected, self.actual
26        )
27    }
28}
29
30impl std::convert::From<PyArray1DimMismatch> for PyErr {
31    fn from(err: PyArray1DimMismatch) -> PyErr {
32        PyOSError::new_err(err.to_string())
33    }
34}
35
36/// Check if array has expected dimension
37pub fn check_array1_dim_impl(
38    array: &Bound<PyArray1<f64>>,
39    expected: usize,
40    file: &'static str,
41    line: u32,
42) -> Result<(), PyArray1DimMismatch> {
43    if array.readonly().len() == expected {
44        Ok(())
45    } else {
46        Err(PyArray1DimMismatch {
47            expected,
48            actual: array.len(),
49            file,
50            line,
51        })
52    }
53}