Skip to contentSkip to conversation

rust: kernel: types: Add `ARef::into_raw`

PATCH New Vincenzo Palazzo 1 participant 1 message Mar 24, 2024 Rust

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: kernel: types: Add `ARef::into_raw`

Add the function into_raw to ARef<T>. This method can be used to turn an ARef into a raw pointer.

---
 rust/kernel/types.rs | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
rust/kernel/types.rs +32 -0
index aa77bad9bce4..b2a243bb810e 100644
@@ -366,6 +366,38 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
             _p: PhantomData,
         }
     }
+
+    /// Deconstructs a [`ARef`] object into a raw pointer.
+    ///
+    /// It can be reconstructed once via [`ARef::from_raw`].
+    ///
+    /// Note: This function does not decrement the reference count.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use core::ptr::NonNull;
+    /// use kernel::AlwaysRefCounted;
+    ///
+    /// struct Empty {}
+    ///
+    /// unsafe impl AlwaysRefCounted for Empty {
+    ///     fn inc_ref(&self) {}
+    ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
+    /// }
+    ///
+    /// let mut data = Empty {};
+    /// let ptr = NonNull::<Empty>::new(&mut data as *mut _).unwrap();
+    /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
+    /// let raw_ptr: *mut Empty = ARef::into_raw(data_ref);
+    ///
+    /// assert_eq!(ptr.as_ptr(), raw_ptr);
+    /// ```
+    pub fn into_raw(obj: Self) -> *mut T {
+        let ptr = obj.ptr.as_ptr();
+        core::mem::forget(obj);
+        ptr
+    }
 }
 
 impl<T: AlwaysRefCounted> Clone for ARef<T> {
Signature · 1 line
2.44.0