From b2b9e17d1449926802dd8f8b96d04f83c35aa282 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Mon, 9 Sep 2024 13:30:36 +0200 Subject: [PATCH] Use NonNull in as_ptr and into_raw --- src/lib.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3f08cdf..51c5465 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,8 +36,9 @@ //! RawWindowHandle::UiKit(handle) => unsafe { Layer::from_ui_view(handle.ui_view) }, //! _ => panic!("unsupported handle"), //! }; -//! let layer: *mut CAMetalLayer = layer.into_raw().cast(); -//! // SAFETY: The pointer is a valid `CAMetalLayer` with +1 retain count. +//! let layer: *mut CAMetalLayer = layer.into_raw().as_ptr().cast(); +//! // SAFETY: The pointer is a valid `CAMetalLayer`, and because we consumed `Layer` with +//! // `into_raw`, the pointer has +1 retain count. //! let layer = unsafe { Retained::from_raw(layer).unwrap() }; //! //! // Use `CAMetalLayer` here. @@ -212,16 +213,16 @@ impl Layer { /// let layer: Layer; /// # layer = unimplemented!(); /// - /// let layer: *mut CAMetalLayer = layer.as_ptr().cast(); /// // SAFETY: The pointer is a valid `CAMetalLayer`. - /// let layer: &CAMetalLayer = unsafe { &*layer }; + /// let layer: &CAMetalLayer = unsafe { layer.as_ptr().cast().as_ref() }; /// /// // Use the `CAMetalLayer` here. /// ``` #[inline] - pub fn as_ptr(&self) -> *mut c_void { + pub fn as_ptr(&self) -> NonNull { let ptr: *const CAMetalLayer = Retained::as_ptr(&self.layer); - ptr as *mut _ + // Unwrap is fine, `Retained` stores a non-null pointer + NonNull::new(ptr as *mut _).unwrap() } /// Consume the layer, and return a pointer with +1 retain count to the underlying @@ -243,15 +244,17 @@ impl Layer { /// let layer: Layer; /// # layer = unimplemented!(); /// - /// let layer: *mut CAMetalLayer = layer.into_raw().cast(); - /// // SAFETY: The pointer is a valid `CAMetalLayer` with +1 retain count. + /// let layer: *mut CAMetalLayer = layer.into_raw().as_ptr().cast(); + /// // SAFETY: The pointer is a valid `CAMetalLayer`, and because we consumed `Layer` with + /// // `into_raw`, the pointer has +1 retain count. /// let layer = unsafe { Retained::from_raw(layer).unwrap() }; /// /// // Use the `CAMetalLayer` here. /// ``` #[inline] - pub fn into_raw(self) -> *mut c_void { - Retained::into_raw(self.layer).cast() + pub fn into_raw(self) -> NonNull { + // Unwrap is fine, `Retained` stores a non-null pointer + NonNull::new(Retained::into_raw(self.layer).cast()).unwrap() } /// If `raw-window-metal` created a new [`CAMetalLayer`] for you, this returns `false`.