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 30, 2024
1 parent 6040d93 commit 42db4af
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,13 @@ 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> {
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>
unsafe { std::mem::transmute(self) }
}

/// Helper to cast to Bound<'py, PyAny>
pub fn into_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) }
}
Expand Down Expand Up @@ -1724,6 +1730,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 42db4af

Please sign in to comment.