Skip to content

Commit 07a06f1

Browse files
Use UnsafeMutableBufferPointer.allocate instead of malloc directly
1 parent 31ae862 commit 07a06f1

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,16 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
7979
/// - Returns: The return value, if any, of the `body` closure parameter.
8080
public func withUnsafeBytes<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R {
8181
let bytesLength = lengthInBytes
82-
let rawBuffer = malloc(bytesLength)!
83-
defer { free(rawBuffer) }
84-
_load_typed_array(jsObject.id, rawBuffer.assumingMemoryBound(to: UInt8.self))
82+
let rawBuffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: bytesLength)
83+
defer { rawBuffer.deallocate() }
84+
let baseAddress = rawBuffer.baseAddress!
85+
_load_typed_array(jsObject.id, baseAddress)
8586
let length = bytesLength / MemoryLayout<Element>.size
86-
let boundPtr = rawBuffer.bindMemory(to: Element.self, capacity: length)
87-
let bufferPtr = UnsafeBufferPointer<Element>(start: boundPtr, count: length)
87+
let rawBaseAddress = UnsafeRawPointer(baseAddress)
88+
let bufferPtr = UnsafeBufferPointer<Element>(
89+
start: rawBaseAddress.assumingMemoryBound(to: Element.self),
90+
count: length
91+
)
8892
let result = try body(bufferPtr)
8993
return result
9094
}
@@ -106,12 +110,16 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
106110
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
107111
public func withUnsafeBytesAsync<R>(_ body: (UnsafeBufferPointer<Element>) async throws -> R) async rethrows -> R {
108112
let bytesLength = lengthInBytes
109-
let rawBuffer = malloc(bytesLength)!
110-
defer { free(rawBuffer) }
111-
_load_typed_array(jsObject.id, rawBuffer.assumingMemoryBound(to: UInt8.self))
113+
let rawBuffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: bytesLength)
114+
defer { rawBuffer.deallocate() }
115+
let baseAddress = rawBuffer.baseAddress!
116+
_load_typed_array(jsObject.id, baseAddress)
112117
let length = bytesLength / MemoryLayout<Element>.size
113-
let boundPtr = rawBuffer.bindMemory(to: Element.self, capacity: length)
114-
let bufferPtr = UnsafeBufferPointer<Element>(start: boundPtr, count: length)
118+
let rawBaseAddress = UnsafeRawPointer(baseAddress)
119+
let bufferPtr = UnsafeBufferPointer<Element>(
120+
start: rawBaseAddress.assumingMemoryBound(to: Element.self),
121+
count: length
122+
)
115123
let result = try await body(bufferPtr)
116124
return result
117125
}

0 commit comments

Comments
 (0)