Skip to content

Commit

Permalink
add Bound::as_any and Bound::into_any
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jan 31, 2024
1 parent 6040d93 commit 09224f5
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,20 @@ impl<'py> Bound<'py, PyAny> {
}

impl<'py, T> Bound<'py, T> {
/// Helper to cast to Bound<'py, PyAny>
pub(crate) fn as_any(&self) -> &Bound<'py, PyAny> {
// Safety: all Bound<T> have the same memory layout, and all Bound<T> are valid Bound<PyAny>
unsafe { std::mem::transmute(self) }
/// Helper to cast to `Bound<'py, PyAny>`.
pub fn as_any(&self) -> &Bound<'py, PyAny> {
// Safety: all Bound<T> have the same memory layout, and all Bound<T> are valid
// Bound<PyAny>, so pointer casting is valid.
unsafe { &*(self as *const Self).cast::<Bound<'py, PyAny>>() }
}

/// Helper to cast to `Bound<'py, PyAny>`, transferring ownership.
pub fn into_any(self) -> Bound<'py, PyAny> {
// Safety: all Bound<T> are valid Bound<PyAny>
Bound(
self.0,
ManuallyDrop::new(unsafe { Py::from_non_null(self.into_non_null()) }),
)
}
}

Expand Down Expand Up @@ -1292,7 +1302,7 @@ impl<T> IntoPy<PyObject> for Bound<'_, T> {
/// Consumes `self` without calling `Py_DECREF()`.
#[inline]
fn into_py(self, _py: Python<'_>) -> PyObject {
unsafe { PyObject::from_non_null(self.into_non_null()) }
self.into_any().unbind()
}
}

Expand Down Expand Up @@ -1724,6 +1734,24 @@ a = A()
});
}

#[test]
fn test_bound_as_any() {
Python::with_gil(|py| {
let obj = PyString::new_bound(py, "hello world");
let any = obj.as_any();
assert_eq!(any.as_ptr(), obj.as_ptr());
});
}

#[test]
fn test_bound_into_any() {
Python::with_gil(|py| {
let obj = PyString::new_bound(py, "hello world");
let any = obj.clone().into_any();
assert_eq!(any.as_ptr(), obj.as_ptr());
});
}

#[cfg(feature = "macros")]
mod using_macros {
use crate::PyCell;
Expand Down

0 comments on commit 09224f5

Please sign in to comment.