Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SwiftData struct for translating Swift's Data class #240

Open
naturecodevoid opened this issue Aug 20, 2023 · 1 comment
Open

SwiftData struct for translating Swift's Data class #240

naturecodevoid opened this issue Aug 20, 2023 · 1 comment

Comments

@naturecodevoid
Copy link
Contributor

Passing raw bytes from Swift to Rust or Rust to Swift is currently pretty annoying and safety is not guaranteed.

As a solution, I propose a SwiftData(pub Vec<u8>) struct to be added to the swift_bridge crate. It would translate to the Swift Data class. Rust functions should both be able to take it as an argument and return it.

As a solution to this problem in the past, I made some helper types here: https://github.com/SideStore/minimuxer/blob/master/generated/minimuxer-helpers.swift

The code from these helper types might be useful for converting Data into Vec<u8>.

@gabbifish
Copy link
Contributor

gabbifish commented Feb 1, 2024

Another workaround heavily borrowed from https://chinedufn.github.io/swift-bridge/built-in/vec/index.html: we converted a Data object into an array of bytes via

extension Data {
    var bytes: [UInt8] {
        return [UInt8](self)
    }
}

and exposed a function in rust:

fn make_rust_vec_with_initial_contents(initial: &[u8]) -> Vec<u8> {
    initial.to_vec()
}

so we could initialize a rust Vec from swift by calling the following:

// Assume data is a Swift Data instance
let data_byte_array = data.bytes
data_byte_array.withUnsafeBufferPointer({ initialPtr in
    let data_vec = make_rust_vec_with_initial_contents(initialPtr)
})

This works in the meantime, but I agree, native Data support would be nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants