diff --git a/src/instance.rs b/src/instance.rs index 90e672c4..e857efc9 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -197,6 +197,15 @@ impl<'py, T> Bound<'py, T> { self.into_non_null().as_ptr() } + /// Casts this `Bound` to a `Borrowed` smart pointer. + pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T> { + Borrowed( + unsafe { NonNull::new_unchecked(self.as_ptr()) }, + PhantomData, + self.py(), + ) + } + /// Casts this `Bound` as the corresponding "GIL Ref" type. /// /// This is a helper to be used for migration from the deprecated "GIL Refs" API. @@ -300,11 +309,7 @@ impl<'a, 'py> Borrowed<'a, 'py, PyAny> { impl<'a, 'py, T> From<&'a Bound<'py, T>> for Borrowed<'a, 'py, T> { /// Create borrow on a Bound fn from(instance: &'a Bound<'py, T>) -> Self { - Self( - unsafe { NonNull::new_unchecked(instance.as_ptr()) }, - PhantomData, - instance.py(), - ) + instance.as_borrowed() } } diff --git a/src/types/bytearray.rs b/src/types/bytearray.rs index f1b8050c..2514e987 100644 --- a/src/types/bytearray.rs +++ b/src/types/bytearray.rs @@ -400,16 +400,16 @@ impl<'py> PyByteArrayMethods<'py> for Bound<'py, PyByteArray> { } fn data(&self) -> *mut u8 { - Borrowed::from(self).data() + self.as_borrowed().data() } unsafe fn as_bytes(&self) -> &[u8] { - Borrowed::from(self).as_bytes() + self.as_borrowed().as_bytes() } #[allow(clippy::mut_from_ref)] unsafe fn as_bytes_mut(&self) -> &mut [u8] { - Borrowed::from(self).as_bytes_mut() + self.as_borrowed().as_bytes_mut() } fn to_vec(&self) -> Vec { diff --git a/src/types/bytes.rs b/src/types/bytes.rs index 5a7b174e..d9d22dbb 100644 --- a/src/types/bytes.rs +++ b/src/types/bytes.rs @@ -107,7 +107,7 @@ pub trait PyBytesMethods<'py> { impl<'py> PyBytesMethods<'py> for Bound<'py, PyBytes> { #[inline] fn as_bytes(&self) -> &[u8] { - Borrowed::from(self).as_bytes() + self.as_borrowed().as_bytes() } } diff --git a/src/types/string.rs b/src/types/string.rs index 111f3112..65f5a392 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -280,20 +280,20 @@ pub trait PyStringMethods<'py> { impl<'py> PyStringMethods<'py> for Bound<'py, PyString> { #[cfg(any(Py_3_10, not(Py_LIMITED_API)))] fn to_str(&self) -> PyResult<&str> { - Borrowed::from(self).to_str() + self.as_borrowed().to_str() } fn to_cow(&self) -> PyResult> { - Borrowed::from(self).to_cow() + self.as_borrowed().to_cow() } fn to_string_lossy(&self) -> Cow<'_, str> { - Borrowed::from(self).to_string_lossy() + self.as_borrowed().to_string_lossy() } #[cfg(not(Py_LIMITED_API))] unsafe fn data(&self) -> PyResult> { - Borrowed::from(self).data() + self.as_borrowed().data() } }