Skip to content

Commit

Permalink
add Py2Borrowed::to_owned
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Dec 21, 2023
1 parent 6625a2c commit 0b79703
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 0b79703

Please sign in to comment.