From 4437e8f61637b30bfa0205ea4738f2029989305a Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Thu, 1 Feb 2024 09:07:36 +0000 Subject: [PATCH] add `Py::as_any` and `Py::into_any` --- newsfragments/3785.added.md | 1 + src/instance.rs | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 newsfragments/3785.added.md diff --git a/newsfragments/3785.added.md b/newsfragments/3785.added.md new file mode 100644 index 00000000..6af3bb99 --- /dev/null +++ b/newsfragments/3785.added.md @@ -0,0 +1 @@ +Add `Py::as_any` and `Py::into_any`. diff --git a/src/instance.rs b/src/instance.rs index b388fb9d..87880e09 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -199,10 +199,7 @@ impl<'py, T> Bound<'py, T> { /// Helper to cast to `Bound<'py, PyAny>`, transferring ownership. pub fn into_any(self) -> Bound<'py, PyAny> { // Safety: all Bound are valid Bound - Bound( - self.0, - ManuallyDrop::new(unsafe { Py::from_non_null(self.into_non_null()) }), - ) + Bound(self.0, ManuallyDrop::new(self.unbind().into_any())) } /// Casts this `Bound` to a `Borrowed` smart pointer. @@ -721,6 +718,19 @@ impl Py { std::mem::forget(self); ptr } + + /// Helper to cast to `Py`. + pub fn as_any(&self) -> &Py { + // Safety: all Py have the same memory layout, and all Py are valid + // Py, so pointer casting is valid. + unsafe { &*(self as *const Self).cast::>() } + } + + /// Helper to cast to `Py`, transferring ownership. + pub fn into_any(self) -> Py { + // Safety: all Py are valid Py + unsafe { Py::from_non_null(self.into_non_null()) } + } } impl Py