Skip to content

Commit 7160959

Browse files
Add Borrowed::as_unbound
1 parent d0a5f45 commit 7160959

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

src/conversion.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ use crate::{
1515
};
1616
use std::convert::Infallible;
1717
use std::marker::PhantomData;
18-
use std::mem::transmute;
1918

2019
/// Defines a conversion from a Rust type to a Python object, which may fail.
2120
///
@@ -150,7 +149,7 @@ impl<'a, 'py, T: PyTypeCheck> IntoPyObject<'py> for &'a Bound<'_, T> {
150149
const OUTPUT_TYPE: PyStaticExpr = T::TYPE_HINT;
151150

152151
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
153-
Ok(self.as_unbound().bind_borrowed(py))
152+
Ok(self.as_unbound().bind_borrowed(py))
154153
}
155154
}
156155

@@ -162,8 +161,8 @@ impl<'a, 'py, T: PyTypeCheck> IntoPyObject<'py> for Borrowed<'a, '_, T> {
162161
#[cfg(feature = "experimental-inspect")]
163162
const OUTPUT_TYPE: PyStaticExpr = T::TYPE_HINT;
164163

165-
fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> {
166-
unsafe { Ok(transmute(self)) }
164+
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
165+
Ok(self.as_unbound().bind_borrowed(py))
167166
}
168167
}
169168

@@ -175,8 +174,8 @@ impl<'a, 'py, T: PyTypeCheck> IntoPyObject<'py> for &Borrowed<'a, '_, T> {
175174
#[cfg(feature = "experimental-inspect")]
176175
const OUTPUT_TYPE: PyStaticExpr = T::TYPE_HINT;
177176

178-
fn into_pyobject(self, _py: Python<'py>) -> Result<Self::Output, Self::Error> {
179-
unsafe { Ok(transmute(*self)) }
177+
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
178+
Ok(self.as_unbound().bind_borrowed(py))
180179
}
181180
}
182181

src/instance.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,6 +1075,14 @@ impl<'a, 'py, T> Borrowed<'a, 'py, T> {
10751075
pub unsafe fn cast_unchecked<U>(self) -> Borrowed<'a, 'py, U> {
10761076
Borrowed(self.0, PhantomData, self.2)
10771077
}
1078+
1079+
/// Removes the connection for this `Borrowed<T>` from the [`Python<'py>`] token,
1080+
/// allowing it to cross thread boundaries, without transferring ownership.
1081+
#[inline]
1082+
pub fn as_unbound(&self) -> &'a Py<T> {
1083+
// Safety: NonNull<ffi::PyObject> is layout-compatible with Py<T>
1084+
unsafe { NonNull::from(&self.0).cast().as_ref() }
1085+
}
10781086
}
10791087

10801088
impl<'a, T: PyClass> Borrowed<'a, '_, T> {

0 commit comments

Comments
 (0)