Debian Codegraph @

third_party/rust/uniffi_core/src/ffi/foreigncallbacks.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 //! This module contains code to handle foreign callbacks - C-ABI functions that are defined by a
6 //! foreign language, then registered with UniFFI. These callbacks are used to implement callback
7 //! interfaces, async scheduling etc. Foreign callbacks are registered at startup, when the foreign
8 //! code loads the exported library. For each callback type, we also define a "cell" type for
9 //! storing the callback.
10
11 use std::{
12 ptr::{null_mut, NonNull},
13 sync::atomic::{AtomicPtr, Ordering},
14 };
15
16 // Cell type that stores any NonNull<T>
17 #[doc(hidden)]
18 pub struct UniffiForeignPointerCell<T>(AtomicPtr<T>);
19
20 impl<T> UniffiForeignPointerCell<T> {
21 pub const fn new() -> Self {
22 Self(AtomicPtr::new(null_mut()))
23 }
24
25 pub fn set(&self, callback: NonNull<T>) {
26 self.0.store(callback.as_ptr(), Ordering::Relaxed);
27 }
28
29 pub fn get(&self) -> &T {
30 unsafe {
31 NonNull::new(self.0.load(Ordering::Relaxed))
32 .expect("Foreign pointer not set. This is likely a uniffi bug.")
33 .as_mut()
34 }
35 }
36 }
37
38 impl<T> Default for UniffiForeignPointerCell<T> {
39 fn default() -> Self {
40 Self::new()
41 }
42 }
43
44 unsafe impl<T> Send for UniffiForeignPointerCell<T> {}
45 unsafe impl<T> Sync for UniffiForeignPointerCell<T> {}