Skip to content

Commit 886919d

Browse files
committed
Add withUnsafeBytesAsync function
1 parent 59e7b65 commit 886919d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,31 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
8888
let result = try body(bufferPtr)
8989
return result
9090
}
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+
}
91116
}
92117

93118
// MARK: - Int and UInt support

0 commit comments

Comments
 (0)