@@ -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) )
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+ )
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) )
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+ )
115123 let result = try await body ( bufferPtr)
116124 return result
117125 }
0 commit comments