migueldeicaza / SwiftGodot

New Godot bindings for Swift
https://migueldeicaza.github.io/SwiftGodotDocs/tutorials/swiftgodot-tutorials/
MIT License
985 stars 55 forks source link

Expose packed_byte_array_operator_index_const. #456

Closed kevinw closed 2 months ago

kevinw commented 2 months ago

Zero-copy access to byte arrays across the gdextension interface is possible with packed_byte_array_operator_index_const, which compliments the version we already use in withUnsafeMutableAccessToData -- packed_byte_array_operator_index

// the new GDExtensionInterface method in this PR
let packed_byte_array_operator_index_const: GDExtensionInterfacePackedByteArrayOperatorIndexConst

It's useful with a Foundation-using helper method like

extension PackedByteArray {
    /// Returns a Data pointing directly at the data in this PackedByteArray
    public func asDataNoCopy() -> Data? {
        withUnsafeConstAccessToData { ptr, count in 
            Data(bytesNoCopy: .init(mutating: ptr), count: count, deallocator: .none)
        }
    }
}
migueldeicaza commented 2 months ago

This is lovely! Thank you for this contribution!

Did the other version make a copy of the data before giving us a pointer?

kevinw commented 2 months ago

Did the other version make a copy of the data before giving us a pointer?

Yes, if your array's reference count is > 1 --

packed_byte_array_operator_index ➡️ &self->ptrw()[p_index] ➡️ Vector::_cowdata.ptrw() ➡️ CowData::_copy_on_write

migueldeicaza commented 2 months ago

Thank you, I have updated the documentation