From the node docs regarding the creation of typed arrays from Buffers:
The buffer's memory is interpreted as an array, not a byte array. That is,
new Uint32Array(new Buffer([1,2,3,4]))
creates a 4-elementUint32Array
with elements[1,2,3,4]
, not anUint32Array
with a single element[0x1020304]
or[0x4030201]
.
This contrasts to plain javascript, where creating a typed array view from an ArrayBuffer uses the ArrayBuffer's memory as bytes (like a reinterpret_cast
in C++). I need this behavior in node when operating on node Buffers.
I could convert the Buffer to an ArrayBuffer, but this is too slow for my application. (I've tried many methods -- but they're all O(n) time.) (Edit: the fastest method I've found is this, which is a single memmove op and pretty fast, but still has at least momentary 2x memory consumption until the reference to the original Buffer is released.)
Is there any (fast/O(1)) way to get a typed array from a Buffer, using the Buffer's contents as bytes instead of elements? (The needed typed array element size is >1 byte, needless to say.)