err: tidy up some uses of PyErr::occurred

This commit is contained in:
David Hewitt 2021-11-12 21:13:28 +00:00
parent a978b0875a
commit 436b8b0b35
3 changed files with 21 additions and 23 deletions

View File

@ -52,11 +52,13 @@ impl<'source> FromPyObject<'source> for f64 {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let v = unsafe { ffi::PyFloat_AsDouble(obj.as_ptr()) };
if v == -1.0 && PyErr::occurred(obj.py()) {
Err(PyErr::fetch(obj.py()))
} else {
Ok(v)
if v == -1.0 {
if let Some(err) = PyErr::take(obj.py()) {
return Err(err);
}
}
Ok(v)
}
}

View File

@ -58,13 +58,7 @@ impl<'p> Iterator for &'p PyIterator {
match unsafe { py.from_owned_ptr_or_opt(ffi::PyIter_Next(self.0.as_ptr())) } {
Some(obj) => Some(Ok(obj)),
None => {
if PyErr::occurred(py) {
Some(Err(PyErr::fetch(py)))
} else {
None
}
}
None => PyErr::take(py).map(Err),
}
}
}

View File

@ -10,18 +10,6 @@ use std::convert::TryFrom;
use std::i64;
use std::os::raw::c_long;
fn err_if_invalid_value<T: PartialEq>(
py: Python,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value && PyErr::occurred(py) {
Err(PyErr::fetch(py))
} else {
Ok(actual_value)
}
}
macro_rules! int_fits_larger_int {
($rust_type:ty, $larger_type:ty) => {
impl ToPyObject for $rust_type {
@ -273,6 +261,20 @@ mod slow_128bit_int_conversion {
int_convert_128!(u128, u64);
}
fn err_if_invalid_value<T: PartialEq>(
py: Python,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value {
if let Some(err) = PyErr::take(py) {
return Err(err);
}
}
Ok(actual_value)
}
#[cfg(test)]
mod test_128bit_intergers {
use super::*;