Skip to content

Commit

Permalink
feat: Add copyIfNeeded flag
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Jan 7, 2025
1 parent f9d01ca commit bd95643
Showing 1 changed file with 20 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,26 @@ public extension ArrayBufferHolder {
public extension ArrayBufferHolder {
/**
* Wrap this `ArrayBufferHolder` in a `Data` instance, without performing a copy.
* - `copyIfNeeded`: If this `ArrayBuffer` is **non-owning**, the foreign
* data may needs to be copied to be safely used outside of the scope of the caller function.
* This flag controls that.
*/
func toData() -> Data {
// 1. Get the std::shared_ptr<ArrayBuffer>
var sharedPointer = self.getArrayBuffer()
// 2. Create a Data object WRAPPING our pointer
return Data(bytesNoCopy: self.data, count: self.size, deallocator: .custom({ buffer, size in
// 3. Capture the std::shared_ptr<ArrayBuffer> in the deallocator lambda so it stays alive.
// As soon as this lambda gets called, the `sharedPointer` gets deleted causing the
// underlying `ArrayBuffer` to be freed.
sharedPointer.reset()
}))
func toData(copyIfNeeded: Bool) -> Data {
let shouldCopy = copyIfNeeded && !self.isOwner
if shouldCopy {
// COPY DATA
return Data.init(bytes: self.data, count: self.size)
} else {
// WRAP DATA
// 1. Get the std::shared_ptr<ArrayBuffer>
var sharedPointer = self.getArrayBuffer()
// 2. Create a Data object WRAPPING our pointer
return Data(bytesNoCopy: self.data, count: self.size, deallocator: .custom({ buffer, size in
// 3. Capture the std::shared_ptr<ArrayBuffer> in the deallocator lambda so it stays alive.
// As soon as this lambda gets called, the `sharedPointer` gets deleted causing the
// underlying `ArrayBuffer` to be freed.
sharedPointer.reset()
}))
}
}
}

0 comments on commit bd95643

Please sign in to comment.