Debian Codegraph @

third_party/rust/uniffi_core/src/ffi/handle.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 /// Object handle
6 ///
7 /// Handles opaque `u64` values used to pass objects across the FFI, both for objects implemented in
8 /// Rust and ones implemented in the foreign language.
9 ///
10 /// Rust handles are generated by leaking a raw pointer
11 /// Foreign handles are generated with a handle map that only generates odd values.
12 /// For all currently supported architectures and hopefully any ones we add in the future:
13 /// * 0 is an invalid value.
14 /// * The lowest bit will always be set for foreign handles and never set for Rust ones (since the
15 /// leaked pointer will be aligned to `size_of::<Arc<T>>()` == `size_of::<*const T>()`).
16 ///
17 /// Rust handles are mainly managed is through the [crate::HandleAlloc] trait.
18 #[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
19 #[repr(transparent)]
20 pub struct Handle(u64);
21
22 impl Handle {
23 pub fn from_pointer<T>(ptr: *const T) -> Self {
24 Self(ptr as u64)
25 }
26
27 pub fn as_pointer<T>(&self) -> *const T {
28 self.0 as *const T
29 }
30
31 /// # Safety
32 /// The raw value must be a valid handle as described above.
33 pub unsafe fn from_raw(raw: u64) -> Option<Self> {
34 if raw == 0 {
35 None
36 } else {
37 Some(Self(raw))
38 }
39 }
40
41 pub fn from_raw_unchecked(raw: u64) -> Self {
42 Self(raw)
43 }
44
45 pub fn as_raw(&self) -> u64 {
46 self.0
47 }
48 }