@@ -88,6 +88,31 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
88
88
let result = try body ( bufferPtr)
89
89
return result
90
90
}
91
+
92
+ /// Calls the given async closure with a pointer to a copy of the underlying bytes of the
93
+ /// array's storage.
94
+ ///
95
+ /// - Note: The pointer passed as an argument to `body` is valid only for the
96
+ /// lifetime of the closure. Do not escape it from the async closure for later
97
+ /// use.
98
+ ///
99
+ /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter
100
+ /// that points to the contiguous storage for the array.
101
+ /// If `body` has a return value, that value is also
102
+ /// used as the return value for the `withUnsafeBytes(_:)` method. The
103
+ /// argument is valid only for the duration of the closure's execution.
104
+ /// - Returns: The return value, if any, of the `body`async closure parameter.
105
+ public func withUnsafeBytesAsync< R> ( _ body: ( UnsafeBufferPointer < Element > ) async throws -> R ) async rethrows -> R {
106
+ let bytesLength = lengthInBytes
107
+ let rawBuffer = malloc ( bytesLength) !
108
+ defer { free ( rawBuffer) }
109
+ _load_typed_array ( jsObject. id, rawBuffer. assumingMemoryBound ( to: UInt8 . self) )
110
+ let length = lengthInBytes / MemoryLayout< Element> . size
111
+ let boundPtr = rawBuffer. bindMemory ( to: Element . self, capacity: length)
112
+ let bufferPtr = UnsafeBufferPointer < Element > ( start: boundPtr, count: length)
113
+ let result = try await body ( bufferPtr)
114
+ return result
115
+ }
91
116
}
92
117
93
118
// MARK: - Int and UInt support
0 commit comments