swift-bridge icon indicating copy to clipboard operation
swift-bridge copied to clipboard

Add RustVec.intoArray()

Open amsam0 opened this issue 1 year ago • 1 comments

Hi,

I think it would be quite useful if RustVec had a builtin intoArray method. For example, I had issues using a RustVec in SwiftUI's List (I needed to use the List constructor that takes a children key path).

I was able to fix my issues with this simple extension:

extension RustVec {
    func intoArray() -> [T] {
        var array: [T] = []
        for _ in 0..<self.len() {
            array.append(self.pop()!)
        }
        return array.reversed()
    }
}

It should probably return nil if the RustVec isn't owned.

amsam0 avatar Aug 18 '23 01:08 amsam0

Good idea.

It should probably return nil if the RustVec isn't owned.

It isn't possible to borrow a RustVec today.

In the future when we supported borrowing we would have RustVecRef and RustVecRefMut. Similar to https://github.com/chinedufn/swift-bridge/blob/af962ca051ba15b81794575a0837f1e2abde9984/book/src/bridge-module/opaque-types/README.md?plain=1#L52-L133

RustVecRef and RustVecRefMut wouldn't have the intoArray method so it wouldn't be possible to call it on a borrowed Rust vec.


If you're interested I'd be happy to merge a PR that adds this intoArray implementation.

Would just leave a TODO to enforce ownership (as in intoArray invalidates the RustVec) after https://github.com/chinedufn/swift-bridge/issues/155 lands

chinedufn avatar Aug 21 '23 22:08 chinedufn