Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AsRefSource to PyNativeType. #3653

Merged
merged 1 commit into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading