Skip to main content

swift_runtime/
retain.rs

1//! Reference counting helpers.
2
3use core::ffi::c_void;
4
5/// A retained Swift heap object. Automatically releases on drop.
6pub struct Retained(*mut c_void);
7
8impl Retained {
9    /// Take ownership of a raw Swift object pointer.
10    ///
11    /// # Safety
12    /// The pointer must be a valid, retained Swift heap object.
13    pub unsafe fn from_raw(ptr: *mut c_void) -> Option<Self> {
14        if ptr.is_null() {
15            None
16        } else {
17            Some(Self(ptr))
18        }
19    }
20
21    /// Get the raw pointer without consuming.
22    pub fn as_raw(&self) -> *mut c_void {
23        self.0
24    }
25
26    /// Release ownership, returning the raw pointer.
27    /// Caller is responsible for releasing.
28    pub fn into_raw(self) -> *mut c_void {
29        let ptr = self.0;
30        core::mem::forget(self);
31        ptr
32    }
33}
34
35impl Clone for Retained {
36    fn clone(&self) -> Self {
37        unsafe {
38            swift_runtime_sys::RuntimeRaw::swift_retain(self.0);
39        }
40        Self(self.0)
41    }
42}
43
44impl Drop for Retained {
45    fn drop(&mut self) {
46        unsafe {
47            swift_runtime_sys::RuntimeRaw::swift_release(self.0);
48        }
49    }
50}
51
52impl std::fmt::Debug for Retained {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "Retained({:?})", self.0)
55    }
56}