# HG changeset patch # User Georges Racinet # Date 2024-12-09 08:38:57 # Node ID 1dd673c1ab3b43d52cc04111c314ccbea57f4ff4 # Parent 64a618048ba857cb462eb066dc68bc28582640fc rust-pyo3: getting rust-cpython GIL handle from various PyO3 objects Depending on the caller context, we might have a `Python<'py>` around or any of the smart pointers that bear the GIL lifetime. Of course, all of these can give back a `Python<'py>` but it is worthwile to reduce the needed boilerplate. The trait just expresses that a lifetime is assumed to be outlived by the PyO3 GIL lifetime. It is marked as unsafe because that is just trusting the implementor. A first version of this was made of a safe trait with a `get_py()` method and the corresponding trivial implementations. We found it finally to be even more artificial, as it boils down to coding 4 functions doing and returning no real data, that we hope the compiler will optimize away. diff --git a/rust/hg-pyo3/src/convert_cpython.rs b/rust/hg-pyo3/src/convert_cpython.rs --- a/rust/hg-pyo3/src/convert_cpython.rs +++ b/rust/hg-pyo3/src/convert_cpython.rs @@ -11,6 +11,7 @@ //! the arguments side of function signatures when they are not simply elided. use pyo3::exceptions::PyTypeError; use pyo3::prelude::*; +use pyo3::{pyclass::boolean_struct::False, PyClass}; use cpython::ObjectProtocol; use cpython::PythonObject; @@ -19,6 +20,23 @@ use lazy_static::lazy_static; use hg::revlog::index::Index as CoreIndex; use rusthg::revlog::{InnerRevlog, PySharedIndex}; +/// Marker trait for PyO3 objects with a lifetime representing the acquired GIL +/// +/// # Safety +/// +/// This trait must not be implemented for objects with lifetimes that +/// do not imply in PyO3 that the GIL is acquired during the whole lifetime. +pub unsafe trait WithGIL<'py> {} + +// Safety: the lifetime on these PyO3 objects all represent the acquired GIL +unsafe impl<'py> WithGIL<'py> for Python<'py> {} +unsafe impl<'py, T> WithGIL<'py> for Bound<'py, T> {} +unsafe impl<'py, T: PyClass> WithGIL<'py> for PyRef<'py, T> {} +unsafe impl<'py, T: PyClass> WithGIL<'py> + for PyRefMut<'py, T> +{ +} + /// Force cpython's GIL handle with the appropriate lifetime /// /// In `pyo3`, the fact that we have the GIL is expressed by the lifetime of @@ -31,10 +49,11 @@ use rusthg::revlog::{InnerRevlog, PyShar /// already has it works) *as long as it is properly released* /// reference: /// -pub(crate) fn cpython_handle<'py, T>( - _bound: &Bound<'py, T>, +pub(crate) fn cpython_handle<'py, T: WithGIL<'py>>( + _with_gil: &T, ) -> cpython::Python<'py> { - // safety: this is safe because the returned object has the 'py lifetime + // safety: this is safe because the returned object has the same lifetime + // as the incoming object. unsafe { cpython::Python::assume_gil_acquired() } }