Skip to content

Commit

Permalink
feat: Add ArrayBuffer.copy(data:)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Jan 7, 2025
1 parent 1db6b22 commit 8c5bb98
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public extension ArrayBufferHolder {
}
return ArrayBufferHolder.makeBuffer(data, size, deleteFunc)
}

/**
* Copy the given `ArrayBufferHolder` into a new **owning** `ArrayBufferHolder`.
*/
Expand All @@ -60,4 +60,14 @@ public extension ArrayBufferHolder {
}
return ArrayBufferHolder.makeBuffer(data, other.size, deleteFunc)
}

/**
* Copy the given `Data` into a new **owning** `ArrayBufferHolder`.
*/
static func copy(data: Data) throws -> ArrayBufferHolder {
let pointer = try UnsafeMutablePointer<UInt8>.init(copyData: data)
return .wrap(dataWithoutCopy: pointer, size: data.count) {
pointer.deallocate()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// SwiftClosure.swift
// NitroModules
//
// Created by Marc Rousavy on 07.01.24.
//

import Foundation

public extension UnsafeMutablePointer<UInt8> {
/**
* Create a new `UnsafeMutablePointer<UInt8>` by copying
* the contents of the given `data`.
*/
init(copyData data: Data) throws {
let byteCount = data.count
let newPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)

try data.withUnsafeBytes { (rawBufferPointer) in
guard let baseAddress = rawBufferPointer.baseAddress else {
throw RuntimeError.error(withMessage: "Cannot get baseAddress of Data!")
}
memcpy(newPointer, baseAddress, byteCount)
}

self.init(newPointer)
}
}

0 comments on commit 8c5bb98

Please sign in to comment.