Skip to content

Commit fd1f0bc

Browse files
authored
Merge pull request #66 from kngwyu/error-rename
Rename ArrayCastError to ErrorKind
2 parents ee70d9b + dc1cc3c commit fd1f0bc

File tree

2 files changed

+55
-47
lines changed

2 files changed

+55
-47
lines changed

src/array.rs

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::marker::PhantomData;
77
use std::os::raw::c_void;
88
use std::ptr::null_mut;
99

10-
use super::error::ArrayCastError;
10+
use super::error::ErrorKind;
1111
use super::*;
1212

1313
/// Interface for [NumPy ndarray](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html).
@@ -239,10 +239,13 @@ impl<T: TypeNum> PyArray<T> {
239239
/// assert!(PyArray::from_vec2(gil.python(), &vec![vec![1], vec![2, 3]]).is_err());
240240
/// # }
241241
/// ```
242-
pub fn from_vec2<'py>(py: Python<'py>, v: &Vec<Vec<T>>) -> Result<&'py Self, ArrayCastError> {
242+
pub fn from_vec2<'py>(py: Python<'py>, v: &Vec<Vec<T>>) -> Result<&'py Self, ErrorKind> {
243243
let last_len = v.last().map_or(0, |v| v.len());
244244
if v.iter().any(|v| v.len() != last_len) {
245-
return Err(ArrayCastError::FromVec);
245+
return Err(ErrorKind::FromVec {
246+
dim1: v.len(),
247+
dim2: last_len,
248+
});
246249
}
247250
let dims = [v.len(), last_len];
248251
let flattend: Vec<_> = v.iter().cloned().flatten().collect();
@@ -274,14 +277,20 @@ impl<T: TypeNum> PyArray<T> {
274277
pub fn from_vec3<'py>(
275278
py: Python<'py>,
276279
v: &Vec<Vec<Vec<T>>>,
277-
) -> Result<&'py PyArray<T>, ArrayCastError> {
280+
) -> Result<&'py PyArray<T>, ErrorKind> {
278281
let dim2 = v.last().map_or(0, |v| v.len());
279282
if v.iter().any(|v| v.len() != dim2) {
280-
return Err(ArrayCastError::FromVec);
283+
return Err(ErrorKind::FromVec {
284+
dim1: v.len(),
285+
dim2,
286+
});
281287
}
282288
let dim3 = v.last().map_or(0, |v| v.last().map_or(0, |v| v.len()));
283289
if v.iter().any(|v| v.iter().any(|v| v.len() != dim3)) {
284-
return Err(ArrayCastError::FromVec);
290+
return Err(ErrorKind::FromVec {
291+
dim1: v.len(),
292+
dim2: dim3,
293+
});
285294
}
286295
let dims = [v.len(), dim2, dim3];
287296
let flattend: Vec<_> = v.iter().flat_map(|v| v.iter().cloned().flatten()).collect();
@@ -338,23 +347,23 @@ impl<T: TypeNum> PyArray<T> {
338347
NpyDataType::from_i32(self.typenum())
339348
}
340349

341-
fn type_check(&self) -> Result<(), ArrayCastError> {
350+
fn type_check(&self) -> Result<(), ErrorKind> {
342351
let truth = self.typenum();
343352
if T::is_same_type(truth) {
344353
Ok(())
345354
} else {
346-
Err(ArrayCastError::to_rust(truth, T::npy_data_type()))
355+
Err(ErrorKind::to_rust(truth, T::npy_data_type()))
347356
}
348357
}
349358

350359
/// Get data as a ndarray::ArrayView
351-
pub fn as_array(&self) -> Result<ArrayViewD<T>, ArrayCastError> {
360+
pub fn as_array(&self) -> Result<ArrayViewD<T>, ErrorKind> {
352361
self.type_check()?;
353362
unsafe { Ok(ArrayView::from_shape_ptr(self.ndarray_shape(), self.data())) }
354363
}
355364

356365
/// Get data as a ndarray::ArrayViewMut
357-
pub fn as_array_mut(&self) -> Result<ArrayViewMutD<T>, ArrayCastError> {
366+
pub fn as_array_mut(&self) -> Result<ArrayViewMutD<T>, ErrorKind> {
358367
self.type_check()?;
359368
unsafe {
360369
Ok(ArrayViewMut::from_shape_ptr(
@@ -365,13 +374,13 @@ impl<T: TypeNum> PyArray<T> {
365374
}
366375

367376
/// Get data as a Rust immutable slice
368-
pub fn as_slice(&self) -> Result<&[T], ArrayCastError> {
377+
pub fn as_slice(&self) -> Result<&[T], ErrorKind> {
369378
self.type_check()?;
370379
unsafe { Ok(::std::slice::from_raw_parts(self.data(), self.len())) }
371380
}
372381

373382
/// Get data as a Rust mutable slice
374-
pub fn as_slice_mut(&self) -> Result<&mut [T], ArrayCastError> {
383+
pub fn as_slice_mut(&self) -> Result<&mut [T], ErrorKind> {
375384
self.type_check()?;
376385
unsafe { Ok(::std::slice::from_raw_parts_mut(self.data(), self.len())) }
377386
}
@@ -476,12 +485,12 @@ impl<T: TypeNum> PyArray<T> {
476485
/// assert!(pyarray_f.copy_to(pyarray_i).is_ok());
477486
/// assert_eq!(pyarray_i.as_slice().unwrap(), &[2, 3, 4]);
478487
/// # }
479-
pub fn copy_to<U: TypeNum>(&self, other: &PyArray<U>) -> Result<(), ArrayCastError> {
488+
pub fn copy_to<U: TypeNum>(&self, other: &PyArray<U>) -> Result<(), ErrorKind> {
480489
let self_ptr = self.as_array_ptr();
481490
let other_ptr = other.as_array_ptr();
482491
let result = unsafe { PY_ARRAY_API.PyArray_CopyInto(other_ptr, self_ptr) };
483492
if result == -1 {
484-
Err(ArrayCastError::dtype_cast(self, U::npy_data_type()))
493+
Err(ErrorKind::dtype_cast(self, U::npy_data_type()))
485494
} else {
486495
Ok(())
487496
}
@@ -498,12 +507,12 @@ impl<T: TypeNum> PyArray<T> {
498507
/// assert!(pyarray_f.move_to(pyarray_i).is_ok());
499508
/// assert_eq!(pyarray_i.as_slice().unwrap(), &[2, 3, 4]);
500509
/// # }
501-
pub fn move_to<U: TypeNum>(&self, other: &PyArray<U>) -> Result<(), ArrayCastError> {
510+
pub fn move_to<U: TypeNum>(&self, other: &PyArray<U>) -> Result<(), ErrorKind> {
502511
let self_ptr = self.as_array_ptr();
503512
let other_ptr = other.as_array_ptr();
504513
let result = unsafe { PY_ARRAY_API.PyArray_MoveInto(other_ptr, self_ptr) };
505514
if result == -1 {
506-
Err(ArrayCastError::dtype_cast(self, U::npy_data_type()))
515+
Err(ErrorKind::dtype_cast(self, U::npy_data_type()))
507516
} else {
508517
Ok(())
509518
}
@@ -522,7 +531,7 @@ impl<T: TypeNum> PyArray<T> {
522531
pub fn cast<'py, U: TypeNum>(
523532
&'py self,
524533
is_fortran: bool,
525-
) -> Result<&'py PyArray<U>, ArrayCastError> {
534+
) -> Result<&'py PyArray<U>, ErrorKind> {
526535
let ptr = unsafe {
527536
let descr = PY_ARRAY_API.PyArray_DescrFromType(U::typenum_default());
528537
PY_ARRAY_API.PyArray_CastToType(
@@ -532,7 +541,7 @@ impl<T: TypeNum> PyArray<T> {
532541
)
533542
};
534543
if ptr.is_null() {
535-
Err(ArrayCastError::dtype_cast(self, U::npy_data_type()))
544+
Err(ErrorKind::dtype_cast(self, U::npy_data_type()))
536545
} else {
537546
Ok(unsafe { PyArray::<U>::from_owned_ptr(self.py(), ptr) })
538547
}
@@ -557,7 +566,7 @@ impl<T: TypeNum> PyArray<T> {
557566
/// # }
558567
/// ```
559568
#[inline(always)]
560-
pub fn reshape<'py, D: ToNpyDims>(&'py self, dims: D) -> Result<&Self, ArrayCastError> {
569+
pub fn reshape<'py, D: ToNpyDims>(&'py self, dims: D) -> Result<&Self, ErrorKind> {
561570
self.reshape_with_order(dims, NPY_ORDER::NPY_ANYORDER)
562571
}
563572

@@ -566,7 +575,7 @@ impl<T: TypeNum> PyArray<T> {
566575
&'py self,
567576
dims: D,
568577
order: NPY_ORDER,
569-
) -> Result<&Self, ArrayCastError> {
578+
) -> Result<&Self, ErrorKind> {
570579
let mut np_dims = dims.to_npy_dims();
571580
let ptr = unsafe {
572581
PY_ARRAY_API.PyArray_Newshape(
@@ -576,7 +585,7 @@ impl<T: TypeNum> PyArray<T> {
576585
)
577586
};
578587
if ptr.is_null() {
579-
Err(ArrayCastError::dims_cast(self, dims))
588+
Err(ErrorKind::dims_cast(self, dims))
580589
} else {
581590
Ok(unsafe { PyArray::<T>::from_owned_ptr(self.py(), ptr) })
582591
}

src/error.rs

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ impl<T, E: IntoPyErr> IntoPyResult for Result<T, E> {
2424
}
2525

2626
/// Represents a shape and format of numpy array.
27+
///
28+
/// Only for error formatting.
2729
#[derive(Debug)]
2830
pub struct ArrayFormat {
2931
pub dims: Box<[usize]>,
@@ -38,18 +40,18 @@ impl fmt::Display for ArrayFormat {
3840

3941
/// Represents a casting error between rust types and numpy array.
4042
#[derive(Debug)]
41-
pub enum ArrayCastError {
43+
pub enum ErrorKind {
4244
/// Error for casting `PyArray` into `ArrayView` or `ArrayViewMut`
43-
ToRust { from: NpyDataType, to: NpyDataType },
45+
PyToRust { from: NpyDataType, to: NpyDataType },
4446
/// Error for casting rust's `Vec` into numpy array.
45-
FromVec,
47+
FromVec { dim1: usize, dim2: usize },
4648
/// Error in numpy -> numpy data conversion
47-
Numpy(Box<(ArrayFormat, ArrayFormat)>),
49+
PyToPy(Box<(ArrayFormat, ArrayFormat)>),
4850
}
4951

50-
impl ArrayCastError {
52+
impl ErrorKind {
5153
pub(crate) fn to_rust(from: i32, to: NpyDataType) -> Self {
52-
ArrayCastError::ToRust {
54+
ErrorKind::PyToRust {
5355
from: NpyDataType::from_i32(from),
5456
to,
5557
}
@@ -66,7 +68,7 @@ impl ArrayCastError {
6668
dtype: T::npy_data_type(),
6769
};
6870
let to = ArrayFormat { dims, dtype: to };
69-
ArrayCastError::Numpy(Box::new((from, to)))
71+
ErrorKind::PyToPy(Box::new((from, to)))
7072
}
7173
pub(crate) fn dims_cast<T: TypeNum>(from: &PyArray<T>, to_dim: impl ToNpyDims) -> Self {
7274
let dims_from = from
@@ -89,18 +91,22 @@ impl ArrayCastError {
8991
dims: dims_to,
9092
dtype: T::npy_data_type(),
9193
};
92-
ArrayCastError::Numpy(Box::new((from, to)))
94+
ErrorKind::PyToPy(Box::new((from, to)))
9395
}
9496
}
9597

96-
impl fmt::Display for ArrayCastError {
98+
impl fmt::Display for ErrorKind {
9799
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98100
match self {
99-
ArrayCastError::ToRust { from, to } => {
101+
ErrorKind::PyToRust { from, to } => {
100102
write!(f, "Cast failed: from={:?}, to={:?}", from, to)
101103
}
102-
ArrayCastError::FromVec => write!(f, "Cast failed: FromVec (maybe invalid dimension)"),
103-
ArrayCastError::Numpy(e) => write!(
104+
ErrorKind::FromVec { dim1, dim2 } => write!(
105+
f,
106+
"Cast failed: Vec To PyArray: expect all dim {} but {} was found",
107+
dim1, dim2
108+
),
109+
ErrorKind::PyToPy(e) => write!(
104110
f,
105111
"Cast failed: from=ndarray({:?}), to=ndarray(dtype={:?})",
106112
e.0, e.1,
@@ -109,21 +115,14 @@ impl fmt::Display for ArrayCastError {
109115
}
110116
}
111117

112-
impl error::Error for ArrayCastError {}
118+
impl error::Error for ErrorKind {}
113119

114-
impl IntoPyErr for ArrayCastError {
120+
impl IntoPyErr for ErrorKind {
115121
fn into_pyerr(self, msg: &str) -> PyErr {
116-
let msg = match self {
117-
ArrayCastError::ToRust { from, to } => format!(
118-
"ArrayCastError::ToRust: from: {:?}, to: {:?}, msg: {}",
119-
from, to, msg
120-
),
121-
ArrayCastError::FromVec => format!("ArrayCastError::FromVec: {}", msg),
122-
ArrayCastError::Numpy(e) => format!(
123-
"ArrayCastError::Numpy: from: {:?}, to: {:?}, msg: {}",
124-
e.0, e.1, msg
125-
),
126-
};
127-
PyErr::new::<exc::TypeError, _>(msg)
122+
match self {
123+
ErrorKind::PyToRust { .. } | ErrorKind::FromVec { .. } | ErrorKind::PyToPy(_) => {
124+
PyErr::new::<exc::TypeError, _>(format!("{}, msg: {}", self, msg))
125+
}
126+
}
128127
}
129128
}

0 commit comments

Comments
 (0)