Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add withUnsafeBytesAsync function
  • Loading branch information
fjtrujy committed Mar 13, 2023
commit 886919dcb062fa9585f77a0e3bb1c8a139af92f2
25 changes: 25 additions & 0 deletions Sources/JavaScriptKit/BasicObjects/JSTypedArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,31 @@ public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral wh
let result = try body(bufferPtr)
return result
}

/// Calls the given async closure with a pointer to a copy of the underlying bytes of the
/// array's storage.
///
/// - Note: The pointer passed as an argument to `body` is valid only for the
/// lifetime of the closure. Do not escape it from the async closure for later
/// use.
///
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter
/// that points to the contiguous storage for the array.
/// If `body` has a return value, that value is also
/// used as the return value for the `withUnsafeBytes(_:)` method. The
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value, if any, of the `body`async closure parameter.
public func withUnsafeBytesAsync<R>(_ body: (UnsafeBufferPointer<Element>) async throws -> R) async rethrows -> R {
let bytesLength = lengthInBytes
let rawBuffer = malloc(bytesLength)!
defer { free(rawBuffer) }
_load_typed_array(jsObject.id, rawBuffer.assumingMemoryBound(to: UInt8.self))
let length = lengthInBytes / MemoryLayout<Element>.size
let boundPtr = rawBuffer.bindMemory(to: Element.self, capacity: length)
let bufferPtr = UnsafeBufferPointer<Element>(start: boundPtr, count: length)
let result = try await body(bufferPtr)
return result
}
}

// MARK: - Int and UInt support
Expand Down