Skip to content

Commit

Permalink
remove deprecation warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Icxolu committed Mar 4, 2024
1 parent 567be15 commit 3f6bd0b
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 36 deletions.
4 changes: 2 additions & 2 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ pub type PyArray6<T> = PyArray<T, Ix6>;
pub type PyArrayDyn<T> = PyArray<T, IxDyn>;

/// Returns a handle to NumPy's multiarray module.
pub fn get_array_module<'py>(py: Python<'py>) -> PyResult<&PyModule> {
PyModule::import(py, npyffi::array::MOD_NAME)
pub fn get_array_module<'py>(py: Python<'py>) -> PyResult<Bound<'_, PyModule>> {
PyModule::import_bound(py, npyffi::array::MOD_NAME)
}

impl<T, D> DerefToPyAny for PyArray<T, D> {}
Expand Down
1 change: 1 addition & 0 deletions src/array_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::marker::PhantomData;
use std::ops::Deref;

use ndarray::{Array1, Dimension, Ix0, Ix1, Ix2, Ix3, Ix4, Ix5, Ix6, IxDyn};
use pyo3::types::PyAnyMethods;
use pyo3::{intern, sync::GILOnceCell, types::PyDict, FromPyObject, Py, PyAny, PyResult};

use crate::sealed::Sealed;
Expand Down
21 changes: 11 additions & 10 deletions src/borrow/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ use std::os::raw::{c_char, c_int};
use std::slice::from_raw_parts;

use num_integer::gcd;
use pyo3::{
exceptions::PyTypeError, sync::GILOnceCell, types::PyCapsule, Py, PyResult, PyTryInto, Python,
};
use pyo3::types::{PyAnyMethods, PyCapsuleMethods};
use pyo3::{exceptions::PyTypeError, sync::GILOnceCell, types::PyCapsule, PyResult, Python};
use rustc_hash::FxHashMap;

use crate::array::get_array_module;
Expand Down Expand Up @@ -123,8 +122,8 @@ fn get_or_insert_shared<'py>(py: Python<'py>) -> PyResult<&'py Shared> {
fn insert_shared<'py>(py: Python<'py>) -> PyResult<*const Shared> {
let module = get_array_module(py)?;

let capsule: &PyCapsule = match module.getattr("_RUST_NUMPY_BORROW_CHECKING_API") {
Ok(capsule) => PyTryInto::try_into(capsule)?,
let capsule = match module.getattr("_RUST_NUMPY_BORROW_CHECKING_API") {
Ok(capsule) => capsule.downcast_into::<PyCapsule>()?,
Err(_err) => {
let flags: *mut BorrowFlags = Box::into_raw(Box::default());

Expand All @@ -137,7 +136,7 @@ fn insert_shared<'py>(py: Python<'py>) -> PyResult<*const Shared> {
release_mut: release_mut_shared,
};

let capsule = PyCapsule::new_with_destructor(
let capsule = PyCapsule::new_bound_with_destructor(
py,
shared,
Some(CString::new("_RUST_NUMPY_BORROW_CHECKING_API").unwrap()),
Expand All @@ -146,25 +145,27 @@ fn insert_shared<'py>(py: Python<'py>) -> PyResult<*const Shared> {
let _ = unsafe { Box::from_raw(shared.flags as *mut BorrowFlags) };
},
)?;
module.setattr("_RUST_NUMPY_BORROW_CHECKING_API", capsule)?;
module.setattr("_RUST_NUMPY_BORROW_CHECKING_API", &capsule)?;
capsule
}
};

// SAFETY: All versions of the shared borrow checking API start with a version field.
let version = unsafe { *(capsule.pointer() as *mut u64) };
let version = unsafe { *(capsule.pointer().cast::<u64>()) };
if version < 1 {
return Err(PyTypeError::new_err(format!(
"Version {} of borrow checking API is not supported by this version of rust-numpy",
version
)));
}

let ptr = capsule.pointer();

// Intentionally leak a reference to the capsule
// so we can safely cache a pointer into its interior.
forget(Py::<PyCapsule>::from(capsule));
forget(capsule);

Ok(capsule.pointer() as *const Shared)
Ok(ptr.cast())
}

// These entry points will be used to access the shared borrow checking API from this extension:
Expand Down
34 changes: 19 additions & 15 deletions src/dtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use pyo3::{
exceptions::{PyIndexError, PyValueError},
ffi::{self, PyTuple_Size},
pyobject_native_type_extract, pyobject_native_type_named,
types::{PyDict, PyTuple, PyType},
AsPyPointer, FromPyObject, FromPyPointer, PyAny, PyNativeType, PyObject, PyResult, PyTypeInfo,
Python, ToPyObject,
types::{PyAnyMethods, PyDict, PyDictMethods, PyTuple, PyType},
AsPyPointer, Borrowed, PyAny, PyNativeType, PyObject, PyResult, PyTypeInfo, Python, ToPyObject,
};
#[cfg(feature = "half")]
use pyo3::{sync::GILOnceCell, IntoPy, Py};
Expand Down Expand Up @@ -247,7 +246,9 @@ impl PyArrayDescr {
if !self.has_subarray() {
self
} else {
#[allow(deprecated)]
unsafe {
use pyo3::FromPyPointer;
Self::from_borrowed_ptr(self.py(), (*(*self.as_dtype_ptr()).subarray).base as _)
}
}
Expand All @@ -265,11 +266,9 @@ impl PyArrayDescr {
Vec::new()
} else {
// NumPy guarantees that shape is a tuple of non-negative integers so this should never panic.
unsafe {
PyTuple::from_borrowed_ptr(self.py(), (*(*self.as_dtype_ptr()).subarray).shape)
}
.extract()
.unwrap()
unsafe { Borrowed::from_ptr(self.py(), (*(*self.as_dtype_ptr()).subarray).shape) }
.extract()
.unwrap()
}
}

Expand Down Expand Up @@ -327,8 +326,8 @@ impl PyArrayDescr {
if !self.has_fields() {
return None;
}
let names = unsafe { PyTuple::from_borrowed_ptr(self.py(), (*self.as_dtype_ptr()).names) };
FromPyObject::extract(names).ok()
let names = unsafe { Borrowed::from_ptr(self.py(), (*self.as_dtype_ptr()).names) };
names.extract().ok()
}

/// Returns the type descriptor and offset of the field with the given name.
Expand All @@ -347,17 +346,22 @@ impl PyArrayDescr {
"cannot get field information: type descriptor has no fields",
));
}
let dict = unsafe { PyDict::from_borrowed_ptr(self.py(), (*self.as_dtype_ptr()).fields) };
let dict = unsafe { Borrowed::from_ptr(self.py(), (*self.as_dtype_ptr()).fields) };
let dict = unsafe { dict.downcast_unchecked::<PyDict>() };
// NumPy guarantees that fields are tuples of proper size and type, so this should never panic.
let tuple = dict
.get_item(name)?
.ok_or_else(|| PyIndexError::new_err(name.to_owned()))?
.downcast::<PyTuple>()
.downcast_into::<PyTuple>()
.unwrap();
// Note that we cannot just extract the entire tuple since the third element can be a title.
let dtype = FromPyObject::extract(tuple.as_ref().get_item(0).unwrap()).unwrap();
let offset = FromPyObject::extract(tuple.as_ref().get_item(1).unwrap()).unwrap();
Ok((dtype, offset))
let dtype = tuple
.get_item(0)
.unwrap()
.downcast_into::<PyArrayDescr>()
.unwrap();
let offset = tuple.get_item(1).unwrap().extract().unwrap();
Ok((dtype.into_gil_ref(), offset))
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/npyffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@ use std::mem::forget;
use std::os::raw::c_void;

use pyo3::{
types::{PyCapsule, PyModule},
Py, PyResult, PyTryInto, Python,
types::{PyAnyMethods, PyCapsule, PyCapsuleMethods, PyModule},
PyResult, Python,
};

fn get_numpy_api<'py>(
py: Python<'py>,
module: &str,
capsule: &str,
) -> PyResult<*const *const c_void> {
let module = PyModule::import(py, module)?;
let capsule: &PyCapsule = PyTryInto::try_into(module.getattr(capsule)?)?;
let module = PyModule::import_bound(py, module)?;
let capsule = module.getattr(capsule)?.downcast_into::<PyCapsule>()?;

let api = capsule.pointer() as *const *const c_void;

// Intentionally leak a reference to the capsule
// so we can safely cache a pointer into its interior.
forget(Py::<PyCapsule>::from(capsule));
forget(capsule);

Ok(api)
}
Expand Down
9 changes: 5 additions & 4 deletions src/sum_products.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::ffi::{CStr, CString};
use std::ptr::null_mut;

use ndarray::{Dimension, IxDyn};
use pyo3::{AsPyPointer, FromPyObject, FromPyPointer, PyAny, PyNativeType, PyResult};
use pyo3::types::PyAnyMethods;
use pyo3::{AsPyPointer, Bound, FromPyObject, PyNativeType, PyResult};

use crate::array::PyArray;
use crate::dtype::Element;
Expand Down Expand Up @@ -67,7 +68,7 @@ where
let py = array1.py();
let obj = unsafe {
let result = PY_ARRAY_API.PyArray_InnerProduct(py, array1.as_ptr(), array2.as_ptr());
PyAny::from_owned_ptr_or_err(py, result)?
Bound::from_owned_ptr_or_err(py, result)?
};
obj.extract()
}
Expand Down Expand Up @@ -125,7 +126,7 @@ where
let py = array1.py();
let obj = unsafe {
let result = PY_ARRAY_API.PyArray_MatrixProduct(py, array1.as_ptr(), array2.as_ptr());
PyAny::from_owned_ptr_or_err(py, result)?
Bound::from_owned_ptr_or_err(py, result)?
};
obj.extract()
}
Expand Down Expand Up @@ -155,7 +156,7 @@ where
NPY_CASTING::NPY_NO_CASTING,
null_mut(),
);
PyAny::from_owned_ptr_or_err(py, result)?
Bound::from_owned_ptr_or_err(py, result)?
};
obj.extract()
}
Expand Down

0 comments on commit 3f6bd0b

Please sign in to comment.