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

SwiftData struct for translating Swift's Data class #240

Open amsam0 opened 1 year ago

amsam0 commented 1 year ago

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\.

gabbifish commented 9 months ago

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!