cairo/
user_data.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::marker::PhantomData;
4
5use crate::ffi;
6
7pub struct UserDataKey<T> {
8    pub(crate) ffi: ffi::cairo_user_data_key_t,
9    marker: PhantomData<*const T>,
10}
11
12unsafe impl<T> Sync for UserDataKey<T> {}
13
14impl<T> UserDataKey<T> {
15    pub const fn new() -> Self {
16        Self {
17            ffi: ffi::cairo_user_data_key_t { unused: 0 },
18            marker: PhantomData,
19        }
20    }
21}
22
23impl<T> Default for UserDataKey<T> {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29// In a safe API for user data we can’t make `get_user_data`
30// transfer full ownership of the value to the caller (e.g. by returning `Box<T>`)
31// because `self` still has a pointer to that value
32// and `get_user_data` could be called again with the same key.
33//
34// We also can’t return a `&T` reference that borrows from `self`
35// because the value could be removed with `remove_user_data` or replaced with `set_user_data`
36// while the borrow still needs to be valid.
37// (Borrowing with `&mut self` would not help as `Self` can be itself reference-counted.)
38//
39// Therefore, the value must be reference-counted.
40//
41// We use `Rc` over `Arc` because the types implementing these methods are `!Send` and `!Sync`.
42// See <https://github.com/gtk-rs/cairo/issues/256>
43
44macro_rules! user_data_methods {
45    ($ffi_get_user_data: path, $ffi_set_user_data: path,) => {
46        /// Attach user data to `self` for the given `key`.
47        pub fn set_user_data<T: 'static>(
48            &self,
49            key: &'static crate::UserDataKey<T>,
50            value: std::rc::Rc<T>,
51        ) -> Result<(), crate::Error> {
52            unsafe extern "C" fn destructor<T>(ptr: *mut libc::c_void) {
53                let ptr: *const T = ptr as _;
54                drop(std::rc::Rc::from_raw(ptr))
55            }
56            // Safety:
57            //
58            // The destructor’s cast and `from_raw` are symmetric
59            // with the `into_raw` and cast below.
60            // They both transfer ownership of one strong reference:
61            // neither of them touches the reference count.
62            let ptr: *const T = std::rc::Rc::into_raw(value);
63            let ptr = ptr as *mut T as *mut libc::c_void;
64            let status = crate::utils::status_to_result(unsafe {
65                $ffi_set_user_data(self.to_raw_none(), &key.ffi, ptr, Some(destructor::<T>))
66            });
67
68            if status.is_err() {
69                // Safety:
70                //
71                // On errors the user data is leaked by cairo and needs to be freed here.
72                unsafe {
73                    destructor::<T>(ptr);
74                }
75            }
76
77            status
78        }
79
80        /// Return the user data previously attached to `self` with the given `key`, if any.
81        pub fn user_data<T: 'static>(
82            &self,
83            key: &'static crate::UserDataKey<T>,
84        ) -> Option<std::rc::Rc<T>> {
85            let ptr = self.user_data_ptr(key)?.as_ptr();
86
87            // Safety:
88            //
89            // `Rc::from_raw` would normally take ownership of a strong reference for this pointer.
90            // But `self` still has a copy of that pointer and `get_user_data` can be called again
91            // with the same key.
92            // We use `ManuallyDrop` to avoid running the destructor of that first `Rc`,
93            // and return a cloned one (which increments the reference count).
94            unsafe {
95                let rc = std::mem::ManuallyDrop::new(std::rc::Rc::from_raw(ptr));
96                Some(std::rc::Rc::clone(&rc))
97            }
98        }
99
100        /// Return the user data previously attached to `self` with the given `key`, if any,
101        /// without incrementing the reference count.
102        ///
103        /// The pointer is valid when it is returned from this method,
104        /// until the cairo object that `self` represents is destroyed
105        /// or `remove_user_data` or `set_user_data` is called with the same key.
106        pub fn user_data_ptr<T: 'static>(
107            &self,
108            key: &'static crate::UserDataKey<T>,
109        ) -> Option<std::ptr::NonNull<T>> {
110            // Safety:
111            //
112            // If `ffi_get_user_data` returns a non-null pointer,
113            // there was a previous call to `ffi_set_user_data` with a key with the same address.
114            // Either:
115            //
116            // * This was a call to a Rust `Self::set_user_data` method.
117            //   Because that method takes a `&'static` reference,
118            //   the key used then must live at that address until the end of the process.
119            //   Because `UserDataKey<T>` has a non-zero size regardless of `T`,
120            //   no other `UserDataKey<U>` value can have the same address.
121            //   Therefore, the `T` type was the same then at it is now and `cast` is type-safe.
122            //
123            // * Or, it is technically possible that the `set` call was to the C function directly,
124            //   with a `cairo_user_data_key_t` in heap-allocated memory that was then freed,
125            //   then `Box::new(UserDataKey::new()).leak()` was used to create a `&'static`
126            //   that happens to have the same address because the allocator for `Box`
127            //   reused that memory region.
128            //   Since this involves a C (or FFI) call *and* is so far out of “typical” use
129            //   of the user data functionality, we consider this a misuse of an unsafe API.
130            unsafe {
131                let ptr = $ffi_get_user_data(self.to_raw_none(), &key.ffi);
132                Some(std::ptr::NonNull::new(ptr)?.cast())
133            }
134        }
135
136        /// Unattached from `self` the user data associated with `key`, if any.
137        /// If there is no other `Rc` strong reference, the data is destroyed.
138        pub fn remove_user_data<T: 'static>(
139            &self,
140            key: &'static crate::UserDataKey<T>,
141        ) -> Result<(), crate::Error> {
142            let status = unsafe {
143                $ffi_set_user_data(self.to_raw_none(), &key.ffi, std::ptr::null_mut(), None)
144            };
145            crate::utils::status_to_result(status)
146        }
147    };
148}