@@ -88,6 +88,34 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
8888 let result = try body ( bufferPtr)
8989 return result
9090 }
91+
92+ #if compiler(>=5.5)
93+ /// Calls the given async closure with a pointer to a copy of the underlying bytes of the
94+ /// array's storage.
95+ ///
96+ /// - Note: The pointer passed as an argument to `body` is valid only for the
97+ /// lifetime of the closure. Do not escape it from the async closure for later
98+ /// use.
99+ ///
100+ /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter
101+ /// that points to the contiguous storage for the array.
102+ /// If `body` has a return value, that value is also
103+ /// used as the return value for the `withUnsafeBytes(_:)` method. The
104+ /// argument is valid only for the duration of the closure's execution.
105+ /// - Returns: The return value, if any, of the `body`async closure parameter.
106+ @available ( macOS 10 . 15 , iOS 13 . 0 , watchOS 6 . 0 , tvOS 13 . 0 , * )
107+ public func withUnsafeBytesAsync< R> ( _ body: ( UnsafeBufferPointer < Element > ) async throws -> R ) async rethrows -> R {
108+ 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)
115+ let result = try await body ( bufferPtr)
116+ return result
117+ }
118+ #endif
91119}
92120
93121// MARK: - Int and UInt support
0 commit comments