@@ -79,12 +79,16 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
79
79
/// - Returns: The return value, if any, of the `body` closure parameter.
80
80
public func withUnsafeBytes< R> ( _ body: ( UnsafeBufferPointer < Element > ) throws -> R ) rethrows -> R {
81
81
let bytesLength = lengthInBytes
82
- let rawBuffer = malloc ( bytesLength) !
83
- defer { free ( rawBuffer) }
84
- _load_typed_array ( jsObject. id, rawBuffer. assumingMemoryBound ( to: UInt8 . self) )
85
- let length = lengthInBytes / MemoryLayout< Element> . size
86
- let boundPtr = rawBuffer. bindMemory ( to: Element . self, capacity: length)
87
- let bufferPtr = UnsafeBufferPointer < Element > ( start: boundPtr, count: length)
82
+ let rawBuffer = UnsafeMutableBufferPointer< UInt8> . allocate( capacity: bytesLength)
83
+ defer { rawBuffer. deallocate ( ) }
84
+ let baseAddress = rawBuffer. baseAddress!
85
+ _load_typed_array ( jsObject. id, baseAddress)
86
+ let length = bytesLength / MemoryLayout< Element> . size
87
+ let rawBaseAddress = UnsafeRawPointer ( baseAddress)
88
+ let bufferPtr = UnsafeBufferPointer < Element > (
89
+ start: rawBaseAddress. assumingMemoryBound ( to: Element . self) ,
90
+ count: length
91
+ )
88
92
let result = try body ( bufferPtr)
89
93
return result
90
94
}
@@ -106,12 +110,16 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
106
110
@available ( macOS 10 . 15 , iOS 13 . 0 , watchOS 6 . 0 , tvOS 13 . 0 , * )
107
111
public func withUnsafeBytesAsync< R> ( _ body: ( UnsafeBufferPointer < Element > ) async throws -> R ) async rethrows -> R {
108
112
let bytesLength = lengthInBytes
109
- let rawBuffer = malloc ( bytesLength) !
110
- defer { free ( rawBuffer) }
111
- _load_typed_array ( jsObject. id, rawBuffer. assumingMemoryBound ( to: UInt8 . self) )
112
- let length = lengthInBytes / MemoryLayout< Element> . size
113
- let boundPtr = rawBuffer. bindMemory ( to: Element . self, capacity: length)
114
- let bufferPtr = UnsafeBufferPointer < Element > ( start: boundPtr, count: length)
113
+ let rawBuffer = UnsafeMutableBufferPointer< UInt8> . allocate( capacity: bytesLength)
114
+ defer { rawBuffer. deallocate ( ) }
115
+ let baseAddress = rawBuffer. baseAddress!
116
+ _load_typed_array ( jsObject. id, baseAddress)
117
+ let length = bytesLength / MemoryLayout< Element> . size
118
+ let rawBaseAddress = UnsafeRawPointer ( baseAddress)
119
+ let bufferPtr = UnsafeBufferPointer < Element > (
120
+ start: rawBaseAddress. assumingMemoryBound ( to: Element . self) ,
121
+ count: length
122
+ )
115
123
let result = try await body ( bufferPtr)
116
124
return result
117
125
}
0 commit comments