Skip to content

Commit

Permalink
Add AsRefSource to PyNativeType.
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Dec 14, 2023
1 parent 763ecb3 commit ef8532b
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 79 deletions.
1 change: 1 addition & 0 deletions newsfragments/3653.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `AsRefSource` to `PyNativeType`.
7 changes: 5 additions & 2 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ use std::ptr::NonNull;
///
/// This trait must only be implemented for types which cannot be accessed without the GIL.
pub unsafe trait PyNativeType: Sized {
/// The form of this which is stored inside a `Py<T>` smart pointer.
type AsRefSource: HasPyGilRef<AsRefTarget = Self>;

/// Returns a GIL marker constrained to the lifetime of this type.
#[inline]
fn py(&self) -> Python<'_> {
Expand Down Expand Up @@ -172,9 +175,9 @@ impl<'py, T> Py2<'py, T> {
/// Internal helper to convert e.g. &'a &'py PyDict to &'a Py2<'py, PyDict> for
/// backwards-compatibility during migration to removal of pool.
#[doc(hidden)] // public and doc(hidden) to use in examples and tests for now
pub fn borrowed_from_gil_ref<'a>(gil_ref: &'a &'py T::AsRefTarget) -> &'a Self
pub fn borrowed_from_gil_ref<'a, U>(gil_ref: &'a &'py U) -> &'a Self
where
T: HasPyGilRef,
U: PyNativeType<AsRefSource = T>,
{
// Safety: &'py T::AsRefTarget is expected to be a Python pointer,
// so &'a &'py T::AsRefTarget has the same layout as &'a Py2<'py, T>
Expand Down
4 changes: 3 additions & 1 deletion src/pycell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,9 @@ pub(crate) struct PyCellContents<T: PyClassImpl> {
pub(crate) weakref: T::WeakRef,
}

unsafe impl<T: PyClass> PyNativeType for PyCell<T> {}
unsafe impl<T: PyClass> PyNativeType for PyCell<T> {
type AsRefSource = T;
}

impl<T: PyClass> PyCell<T> {
/// Makes a new `PyCell` on the Python heap and return the reference to it.
Expand Down
Loading

0 comments on commit ef8532b

Please sign in to comment.