Skip to content

Commit

Permalink
implement Copy for Py2Borrowed
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Dec 21, 2023
1 parent f3ae79d commit d38d162
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
10 changes: 10 additions & 0 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ unsafe impl<T> AsPyPointer for Py2<'_, T> {
///
/// The advantage of this over `&Py2` is that it avoids the need to have a pointer-to-pointer, as Py2
/// is already a pointer to an `ffi::PyObject``.
///
/// Similarly, this type is `Copy` and `Clone`, like any pointer.
#[repr(transparent)]
pub(crate) struct Py2Borrowed<'a, 'py, T>(
NonNull<ffi::PyObject>,
Expand Down Expand Up @@ -326,6 +328,14 @@ impl<'py, T> Deref for Py2Borrowed<'_, 'py, T> {
}
}

impl<T> Clone for Py2Borrowed<'_, '_, T> {
fn clone(&self) -> Self {
*self
}
}

impl<T> Copy for Py2Borrowed<'_, '_, T> {}

/// A GIL-independent reference to an object allocated on the Python heap.
///
/// This type does not auto-dereference to the inner object because you must prove you hold the GIL to access it.
Expand Down
8 changes: 4 additions & 4 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::PyMapping;
use crate::err::{self, PyErr, PyResult};
use crate::ffi::Py_ssize_t;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::Py2;
use crate::instance::{Py2, Py2Borrowed};
use crate::py_result_ext::PyResultExt;
use crate::types::any::PyAnyMethods;
use crate::types::{PyAny, PyList};
Expand Down Expand Up @@ -406,7 +406,7 @@ impl<'py> PyDictMethods<'py> for Py2<'py, PyDict> {
match unsafe {
ffi::PyDict_GetItemWithError(dict.as_ptr(), key.as_ptr())
.assume_borrowed_or_opt(py)
.map(|borrowed_any| borrowed_any.clone())
.map(Py2Borrowed::to_owned)
} {
some @ Some(_) => Ok(some),
None => PyErr::take(py).map(Err).transpose(),
Expand Down Expand Up @@ -595,8 +595,8 @@ impl<'py> Iterator for PyDictIterator2<'py> {
// - PyDict_Next returns borrowed values
// - we have already checked that `PyDict_Next` succeeded, so we can assume these to be non-null
Some((
unsafe { key.assume_borrowed_unchecked(py) }.clone(),
unsafe { value.assume_borrowed_unchecked(py) }.clone(),
unsafe { key.assume_borrowed_unchecked(py) }.to_owned(),
unsafe { value.assume_borrowed_unchecked(py) }.to_owned(),
))
} else {
None
Expand Down

0 comments on commit d38d162

Please sign in to comment.