chinedufn / swift-bridge

swift-bridge facilitates Rust and Swift interop.
https://chinedufn.github.io/swift-bridge
Apache License 2.0
842 stars 62 forks source link

Fix memory leak for `Option<SwiftType>` #273

Closed chinedufn closed 6 months ago

chinedufn commented 6 months ago

This commit fixes a memory leak when passing Option<SwiftType> to extern "Rust" functions.

For example, the following bridge module would lead to memory leaks:

#[swift_bridge::bridge]
mod ffi {
    extern "Swift" {
        type SomeSwiftType;
    }

    extern "Rust" {
        fn rust_fn_takes_swift_type(arg: Option<SomeSwiftType>);
    }
}

When the above rust_fn_takes_swift_type function was called the SomeSwiftType would be retained twice.

When the Rust side later freed SomeSwiftType the retain count would drop from 2 to 1.

Since there was still 1 retain, SomeSwiftType would never get freed.

Impact

Support for passing Option<SomeSwiftType> from Swift to Rust was introduced earlier today.

This functionality was released in swift-bridge = "0.1.54".

W will be deploying `swift-bridge = "0.1.55" today. "0.1.55" will contain a fix for the leak.

Because support for Option<SomeSwiftType> was released today, and the fix will be released today, it should be unlikely that anyone has experienced this leak.

We will yank "0.1.54" from "crates.io".

All users (probably zero) that are bridging Option<SomeSwiftType> should upgrade from "0.1.54" to "0.1.55" to.

Solution

This commit does the following:

With all of the above we should now be able to:

Before this commit, when passing an Option<SwiftType> it was: