Skip to content

Commit

Permalink
add wgpu.BytesToJS helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
kkoreilly committed Sep 5, 2024
1 parent ca2e8ad commit ec49236
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions wgpu/adapt_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ func ensureBufferSize(size int) {
uint8Array = js.Global().Get("Uint8Array").New(arrayBuffer)
}

// BytesToJS converts the given bytes to a js Uint8Array
// by using the global wasm memory bytes. This avoids the
// copying present in [js.CopyBytesToJS].
func BytesToJS(b []byte) js.Value {
ptr := uintptr(unsafe.Pointer(&b[0]))
memoryBytes := js.Global().Get("Uint8Array").New(js.Global().Get("wasm").Get("instance").Get("exports").Get("mem").Get("buffer"))
// using subarray instead of slice gives a 5x performance improvement due to no copying
return memoryBytes.Call("subarray", ptr, ptr+uintptr(len(b)))
}

// DataTypes represents allowed data slice types.
type DataTypes interface {
~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~float32 | ~float64
Expand Down

0 comments on commit ec49236

Please sign in to comment.