swift_bridge/lib.rs
1//! Generate FFI glue between Swift and Rust code.
2
3#![deny(missing_docs)]
4
5pub use swift_bridge_macro::bridge;
6
7mod std_bridge;
8
9pub use self::std_bridge::{option, result, string};
10
11#[doc(hidden)]
12#[cfg(feature = "async")]
13pub mod async_support;
14
15#[doc(hidden)]
16#[cfg(feature = "async")]
17pub mod async_swift_support;
18
19#[doc(hidden)]
20pub mod boxed_fn_support;
21
22#[doc(hidden)]
23pub mod copy_support;
24
25#[doc(hidden)]
26#[repr(C)]
27pub struct FfiSlice<T> {
28 pub start: *const T,
29 pub len: usize,
30}
31
32// Unlike the Swift pointer wrapper types that we generate, this type does not implement drop.
33// So we can freely construct it and pass it over the FFI boundary without worrying about drop
34//
35// It has the same layout as the __private__PointerToSwift C struct, so when we pass this to
36// Swift it can receive it as a __private__PointerToSwift.
37#[doc(hidden)]
38#[repr(C)]
39pub struct PointerToSwiftType(pub *mut std::ffi::c_void);
40
41impl<T> FfiSlice<T> {
42 /// Create an FfiSlice from a slice.
43 pub fn from_slice(slice: &[T]) -> Self {
44 FfiSlice {
45 start: slice.as_ptr(),
46 len: slice.len(),
47 }
48 }
49
50 /// Get a reference to the slice that this FfiSlice points to.
51 pub fn as_slice(&self) -> &'static [T] {
52 unsafe { std::slice::from_raw_parts(self.start, self.len) }
53 }
54}
55
56// The code generation automatically implements this for all shared structs.
57// This trait is private and should not be used outside of swift-bridge.
58//
59// The main use case is for structs that use the `#[swift_bridge(already_declared)]`
60// attribute, where we use `<SomeStruct as SharedStruct::FfiRepr>` to get the
61// struct's FFI representation.
62#[doc(hidden)]
63pub trait SharedStruct {
64 /// The FFI friendly representation of this struct.
65 ///
66 /// ```
67 /// struct MyStruct {
68 /// field: &'static str
69 /// }
70 /// // This is the auto generated ffi representation.
71 /// #[repr(C)]
72 /// struct __swift_bridge__MyStruct {
73 /// field: swift_bridge::string::RustStr
74 /// }
75 /// ```
76 type FfiRepr;
77}
78
79// The code generation automatically implements this for all shared enum.
80// This trait is private and should not be used outside of swift-bridge.
81//
82// The main use case is for enums that use the `#[swift_bridge(already_declared)]`
83// attribute, where we use `<SomeEnum as SharedEnum::FfiRepr>` to get the
84// enum's FFI representation.
85#[doc(hidden)]
86pub trait SharedEnum {
87 /// The FFI friendly representation of this enum.
88 ///
89 /// ```
90 /// enum MyEnum {
91 /// Variant1,
92 /// Variant2,
93 /// }
94 /// // This is the auto generated ffi representation.
95 /// #[repr(C)]
96 /// enum __swift_bridge__MyEnum {
97 /// Variant1,
98 /// Variant2,
99 /// }
100 /// ```
101 type FfiRepr;
102}
103
104#[no_mangle]
105#[doc(hidden)]
106pub extern "C" fn __swift_bridge__null_pointer() -> *const std::ffi::c_void {
107 std::ptr::null()
108}