wasm-arrays icon indicating copy to clipboard operation
wasm-arrays copied to clipboard

Improve bit shifting

Open edwinm opened this issue 5 years ago • 2 comments
trafficstars

I was reading your article https://becominghuman.ai/passing-and-returning-webassembly-array-parameters-a0f572c65d97

I noticed this code:

` const buf = Module._malloc(typedArray.length * typedArray.BYTES_PER_ELEMENT)

                switch (heapIn) {
                    case "HEAP8": case "HEAPU8":
                        Module[heapIn].set(typedArray, buf)
                        break
                    case "HEAP16": case "HEAPU16":
                        Module[heapIn].set(typedArray, buf >> 1)
                        break
                    case "HEAP32": case "HEAPU32": case "HEAPF32":
                        Module[heapIn].set(typedArray, buf >> 2)
                        break
                    case "HEAPF64":
                        Module[heapIn].set(typedArray, buf >> 3)
                        break
                }`

Can't this be simplified to:

` const buf = Module._malloc(typedArray.length * typedArray.BYTES_PER_ELEMENT)

                  Module[heapIn].set(typedArray, buf * typedArray.BYTES_PER_ELEMENT)`

Since it looks like the bit shifting is the same as multiplying with the number of bytes per element.

edwinm avatar Jul 07 '20 10:07 edwinm

Ah, interesting. Perhaps this would work! I haven't tested this however, have you, with success?

DanRuta avatar Jul 11 '20 13:07 DanRuta

No, I didn't compile your code, I was just delving into web assembly and stumbled upon your blog and code.

edwinm avatar Jul 11 '20 19:07 edwinm