From f3ae79d86464d97f7c30e488d0894694d8bee94f Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Thu, 21 Dec 2023 08:58:42 +0000 Subject: [PATCH] add `Py2Borrowed::to_owned` --- src/instance.rs | 11 +++++++++++ src/types/list.rs | 5 +++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/instance.rs b/src/instance.rs index 14e6000caee..8b7490169d1 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -228,6 +228,17 @@ pub(crate) struct Py2Borrowed<'a, 'py, T>( Python<'py>, ); +impl<'py, T> Py2Borrowed<'_, 'py, T> { + /// Creates a new owned `Py2` from this borrowed reference by increasing the reference count. + pub(crate) fn to_owned(self) -> Py2<'py, T> { + unsafe { ffi::Py_INCREF(self.as_ptr()) }; + Py2( + self.py(), + ManuallyDrop::new(unsafe { Py::from_non_null(self.0) }), + ) + } +} + impl<'a, 'py> Py2Borrowed<'a, 'py, PyAny> { /// # Safety /// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by diff --git a/src/types/list.rs b/src/types/list.rs index 5b38db897b0..661034111fb 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -4,6 +4,7 @@ use std::iter::FusedIterator; use crate::err::{self, PyResult}; use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; +use crate::instance::Py2Borrowed; use crate::internal_tricks::get_ssize_index; use crate::types::{PySequence, PyTuple}; use crate::{Py2, PyAny, PyObject, Python, ToPyObject}; @@ -391,7 +392,7 @@ impl<'py> PyListMethods<'py> for Py2<'py, PyList> { // PyList_GetItem return borrowed ptr; must make owned for safety (see #890). ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t) .assume_borrowed_or_err(self.py()) - .map(|borrowed_any| borrowed_any.clone()) + .map(Py2Borrowed::to_owned) } } @@ -405,7 +406,7 @@ impl<'py> PyListMethods<'py> for Py2<'py, PyList> { // PyList_GET_ITEM return borrowed ptr; must make owned for safety (see #890). ffi::PyList_GET_ITEM(self.as_ptr(), index as Py_ssize_t) .assume_borrowed(self.py()) - .clone() + .to_owned() } /// Takes the slice `self[low:high]` and returns it as a new list.