• Stars
    star
    800
  • Rank 56,670 (Top 2 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created almost 3 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

swift-bridge facilitates Rust and Swift interop.

swift-bridge Actions Status docs crates.io

swift-bridge facilitates Rust and Swift interop.

swift-bridge makes it easy to pass and share high-level types between Rust and Swift, such as String, Option<T>, Result<T, E>, struct, class and more.

It also helps you bridge higher level language features, such as async functions and generics.

Using swift-bridge should be safer, more performant and more ergonomic than managing Rust and Swift FFI by hand.

Installation

# In your Cargo.toml

[build-dependencies]
swift-bridge-build = "0.1"

[dependencies]
swift-bridge = "0.1"

Book

You can find information about using Rust and Swift together in The swift-bridge Book.

Quick Peek

You use swift-bridge by declaring the types and functions that you want to import and export in a "bridge module", and then annotating that bridge module with the #[swift_bridge::bridge] macro.

Then, at build time, you use either the swift-bridge-build API or the swift-bridge-cli CLI to parse your annotated bridge modules and generate the Swift and C side of the FFI layer.

Here's a quick peek at how you might describe an FFI boundary between Swift and Rust using a bridge module.

// We use the `swift_bridge::bridge` macro to declare a bridge module.
// Then at build time the `swift-bridge-build` crate is used to generate
// the corresponding Swift and C FFI glue code.
#[swift_bridge::bridge]
mod ffi {
    // Create "transparent" structs where both Rust and Swift can directly access the fields.
    struct AppConfig {
        file_manager: CustomFileManager,
    }

    // Transparent enums are also supported.
    enum UserLookup {
        ById(UserId),
        ByName(String),
    }

    // Export opaque Rust types, functions and methods for Swift to use.
    extern "Rust" {
        type RustApp;

        #[swift_bridge(init)]
        fn new(config: AppConfig) -> RustApp;
        
        fn get_user(&self, lookup: UserLookup) -> Option<&User>;
    }

    extern "Rust" {
        type User;
        type MessageBoard;

        #[swift_bridge(get(&nickname))]
        fn informal_name(self: &User) -> &str;
    }

    // Import opaque Swift classes and functions for Rust to use.
    extern "Swift" {
        type CustomFileManager;
        fn save_file(&self, name: &str, contents: &[u8]);
    }
}

struct User {
    nickname: String
}

Quick Start

The swift-bridge repository contains example applications that you use to quickly try out the library, or as a starting point for your own Swift + Rust based application.

For example, here's how to run the codegen-visualizer example project locally.

git clone https://github.com/chinedufn/swift-bridge
cd swift-bridge/examples/codegen-visualizer

open CodegenVisualizer/CodegenVisualizer.xcodeproj
# *** Click the "Run" button at the top left of Xcode ***

You can find information about using Rust and Swift together in The swift-bridge Book.

Built-In Types

In addition to allowing you to share your own custom structs, enums and classes between Rust and Swift, swift-bridge comes with support for a number of Rust and Swift standard library types.

name in Rust name in Swift notes
u8, i8, u16, i16... etc UInt8, Int8, UInt16, Int16 ... etc
bool Bool
String, &String, &mut String RustString, RustStringRef, RustStringRefMut
&str RustStr
Vec<T> RustVec<T>
SwiftArray<T> Array<T> Not yet implemented
&[T] Not yet implemented
&mut [T] Not yet implemented
Box<T> Not yet implemented
Box<dyn FnOnce(A,B,C) -> D> (A, B, C) -> D Passing from Rust to Swift is supported, but Swift to Rust is not yet implemented.
Box<dyn Fn(A,B,C) -> D> (A, B, C) -> D Not yet implemented
Arc<T> Not yet implemented
[T; N] Not yet implemented
*const T UnsafePointer<T>
*mut T UnsafeMutablePointer<T>
Option<T> Optional<T>
fn x() -> Result<T, E> func x() throws -> T
fn x(arg: Result<T, E>) func x(arg: RustResult<T, E>)
(A, B, C, ...) (A, B, C, ...)
Have a Rust standard library type in mind?
Open an issue!
Have a Swift standard library type in mind?
Open an issue!

Performance

swift-bridge aims to be useful in performance critical environments.

None of its generated FFI code uses object serialization, cloning, synchronization or any other form of unnecessary overhead.

To Test

To run the test suite.

# Clone the repository
git clone [email protected]:chinedufn/swift-bridge.git
cd swift-bridge

# Run tests
cargo test --all && ./test-swift-rust-integration.sh && ./test-swift-packages.sh 

Contributing

If you're interesting in contributing to swift-bridge, check out the contributor's guide.

After getting familiar with the contribution process, try looking at some of the good first issues to see if any peak your interest.

These issues come with step-by-step instructions that should help guide you towards implementing your first patch.

Acknowledgements

  • cxx inspired the idea of using a bridge module to describe the FFI boundary.

License

Licensed under MIT or Apache-2.0.

More Repositories

1

percy

Build frontend browser apps with Rust + WebAssembly. Supports server side rendering.
Rust
2,260
star
2

webgl-water-tutorial

The source code for a tutorial on rendering water using WebGL + Rust + WebAssembly
Rust
477
star
3

psd

A Rust API for parsing and working with PSD files.
Rust
265
star
4

dipa

dipa makes it easy to efficiently delta encode large Rust data structures.
Rust
264
star
5

skeletal-animation-system

A standalone, stateless, dual quaternion based skeletal animation system built with interactive applications in mind
JavaScript
250
star
6

landon

A collection of tools, data structures and methods for exporting Blender data (such as meshes and armatures) and preparing it for your rendering pipeline.
Rust
147
star
7

collada-dae-parser

Parse collada .dae 3d animation files into a WebGL friendly JSON format
JavaScript
103
star
8

cross-compile-rust-from-mac-to-linux

An example of how to cross compile Rust from `macOS` to Linux `x86_64-unknown-linux-gnu`
Shell
95
star
9

rectangle-pack

A general purpose, deterministic bin packer designed to conform to any two or three dimensional use case.
Rust
72
star
10

blender-iks-to-fks

A Blender script that takes a mesh and armature that use IKs and other non-deformation bones and creates a new mesh and armature that uses only FK bones.
Python
44
star
11

hot-app-replacement

Like hot module replacement but... yeah you'll see
JavaScript
26
star
12

blender-webgl-hot-reload-experiment

An experiment in hot reloading 3d models from Blender into a WebGL scene
JavaScript
23
star
13

blender-actions-to-json

Write the joint data for all of a `.blend` file's actions to a JSON file
Python
17
star
14

webgl-particle-effect-tutorial

A tutorial for creating a WebGL fire particle effect using billboarded quads
JavaScript
17
star
15

wavefront-obj-parser

An api and cli for parsing wavefront .obj files into JSON
JavaScript
17
star
16

webgl-shadow-mapping-tutorial

A WebGL shadow mapping tutorial
JavaScript
16
star
17

mat4-to-dual-quat

Convert a 4x4 matrix into a dual quaternion. Useful for skeletal animation (dual quaternion linear blending)
JavaScript
14
star
18

virtual-progress-bar

virtual-dom progress bar component
JavaScript
11
star
19

virtual-loading-dots

virtual-dom loading dots component
JavaScript
9
star
20

webgl-skeletal-animation-tutorial

A quick tutorial on WebGL skeletal animation using small modules
JavaScript
9
star
21

watertight-ray-triangle-intersection

An implementation of the Watertight Ray/Triangle Intersection algorithm
JavaScript
9
star
22

solid-state

Trigger listener functions when your state changes
JavaScript
8
star
23

blender-webgl-skinned-hot-reload-experiment

An experiment in hot reloading skinned models from Blender to WebGL
JavaScript
7
star
24

dom-filenameify

Add filenames as attributes to your DOM elements to help locate them in code by inspect-elementing them in the browser
JavaScript
7
star
25

webgl-unit-test-tutorial

The source code for a tutorial on unit testing WebGL components
JavaScript
7
star
26

image-to-heightmap

Convert a JPG or PNG image into a heightmap array
JavaScript
7
star
27

webgl-wield-item-tutorial

A tutorial for positioning items on top of bones using WebGL and 3d math
JavaScript
6
star
28

create-keyframe

Create css keyframes using JSON
JavaScript
6
star
29

webgl-to-img-stream

Use a WebGL context to write the canvas's contents to a image file. Meant to be used in Node.js
JavaScript
5
star
30

load-collada-dae

Load the WebGL graphics buffer data from a collada .dae model and return a draw command that accepts options
JavaScript
5
star
31

app-world

A framework agnostic approach to managing frontend application state.
Rust
5
star
32

make-component

A code generator for virtual-dom component files
JavaScript
3
star
33

client-ketchup

A simple interface for keeping remote clients up to date with their authoritative state
JavaScript
3
star
34

neighborhood-pathfinder

An A* implementation that accepts a function to detect neighboring tiles
JavaScript
3
star
35

webgl-skeletal-animation-sound-tutorial

A tutorial for playing sound effects during skeletal animations
JavaScript
2
star
36

expand-vertex-data

Expand vertex, normal and uv indices into vertex normal and uv data that is ready for your array buffers
JavaScript
2
star
37

minimal-object-diff

Create and apply a tiny representation of diffs between two objects. Useful for sending diffs over a network
JavaScript
2
star
38

generate-keyframe-animation-tutorial

A tutorial on generating CSS keyframes during runtime
JavaScript
2
star
39

branching-dialogue

A stateless API for modeling branching dialogue in role-playing games
JavaScript
2
star
40

conformer

conformer helps you write and visualize conformance test suites.
Rust
2
star
41

create-hover-class

Turn a JSON object into :hover class to use with inline styled components
JavaScript
2
star
42

load-wavefront-obj

Load the graphics buffer data from a wavefront .obj model and return a draw command that accepts options
JavaScript
2
star
43

get-attributes-uniforms

Get the attributes and uniforms from a GLSL shader string
JavaScript
2
star
44

keyframes-to-dual-quats

Convert a set of keyframe matrices into dual quaternions
JavaScript
1
star
45

knowledge

Concepts, solutions and links that I want to remember
1
star
46

angular-video-time

AngularJS Filter for displaying a video's current time
JavaScript
1
star
47

create-shader-program

Compiles, links and returns a shader program from a give vertex and fragment shader
JavaScript
1
star
48

webgl-blend-map-tutorial

A tutorial on multitexturing a WebGL terrain using a blend map
JavaScript
1
star
49

epoch-to-timeago

Get a string representation of a time difference
JavaScript
1
star
50

create-orbit-camera

Create a camera that orbits a target
JavaScript
1
star
51

blender-rustlang-docker

Docker image with Blender 2.80 and Rust
Dockerfile
1
star
52

create-draw-function

Create a WebGL draw call based on user provided data
JavaScript
1
star
53

donutjs-skeletal-animation-slides

Skeletal Animation in Your Browser via WebGL - the accompanying slides for a talk at Portland's Donut.js meetup
JavaScript
1
star