Skip to content

Commit 0b79703

Browse files
committed
add Py2Borrowed::to_owned
1 parent 6625a2c commit 0b79703

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/instance.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,17 @@ pub(crate) struct Py2Borrowed<'a, 'py, T>(
228228
Python<'py>,
229229
);
230230

231+
impl<'py, T> Py2Borrowed<'_, 'py, T> {
232+
/// Creates a new owned `Py2` from this borrowed reference by increasing the reference count.
233+
pub(crate) fn to_owned(self) -> Py2<'py, T> {
234+
unsafe { ffi::Py_INCREF(self.as_ptr()) };
235+
Py2(
236+
self.py(),
237+
ManuallyDrop::new(unsafe { Py::from_non_null(self.0) }),
238+
)
239+
}
240+
}
241+
231242
impl<'a, 'py> Py2Borrowed<'a, 'py, PyAny> {
232243
/// # Safety
233244
/// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by

src/types/list.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::iter::FusedIterator;
44
use crate::err::{self, PyResult};
55
use crate::ffi::{self, Py_ssize_t};
66
use crate::ffi_ptr_ext::FfiPtrExt;
7+
use crate::instance::Py2Borrowed;
78
use crate::internal_tricks::get_ssize_index;
89
use crate::types::{PySequence, PyTuple};
910
use crate::{Py2, PyAny, PyObject, Python, ToPyObject};
@@ -391,7 +392,7 @@ impl<'py> PyListMethods<'py> for Py2<'py, PyList> {
391392
// PyList_GetItem return borrowed ptr; must make owned for safety (see #890).
392393
ffi::PyList_GetItem(self.as_ptr(), index as Py_ssize_t)
393394
.assume_borrowed_or_err(self.py())
394-
.map(|borrowed_any| borrowed_any.clone())
395+
.map(Py2Borrowed::to_owned)
395396
}
396397
}
397398

0 commit comments

Comments
 (0)