1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! Generate FFI glue between Swift and Rust code.

#![deny(missing_docs)]

pub use swift_bridge_macro::bridge;

mod std_bridge;

pub use self::std_bridge::{option, string};

#[doc(hidden)]
#[repr(C)]
pub struct FfiSlice<T> {
    pub start: *const T,
    pub len: usize,
}

// Unlike the Swift pointer wrapper types that we generate, this type does not implement drop.
// So we can freely construct it and pass it over the FFI boundary without worrying about drop
//
// It has the same layout as the __private__PointerToSwift C struct, so when we pass this to
// Swift it can receive it as a __private__PointerToSwift.
#[doc(hidden)]
#[repr(C)]
pub struct PointerToSwiftType(pub *mut std::ffi::c_void);

impl<T> FfiSlice<T> {
    /// Create an FfiSlice from a slice.
    pub fn from_slice(slice: &[T]) -> Self {
        FfiSlice {
            start: slice.as_ptr(),
            len: slice.len(),
        }
    }

    /// Get a reference to the slice that this FfiSlice points to.
    pub fn as_slice(&self) -> &'static [T] {
        unsafe { std::slice::from_raw_parts(self.start, self.len) }
    }
}

// The code generation automatically implements this for all shared structs.
// This trait is private and should not be used outside of swift-bridge.
#[doc(hidden)]
pub trait SharedStruct {
    /// The FFI friendly representation of this struct.
    ///
    /// ```
    /// struct MyStruct {
    ///     field: &'static str
    /// }
    /// // This is the auto generated ffi representation.
    /// #[repr(C)]
    /// struct __swift_bridge__MyStruct {
    ///     field: swift_bridge::string::RustStr
    /// }
    /// ```
    type FfiRepr;
}

#[no_mangle]
#[doc(hidden)]
pub extern "C" fn __swift_bridge__null_pointer() -> *const std::ffi::c_void {
    std::ptr::null()
}