Search code examples
javascriptarraybuffertyped-arrays

"RangeError: Invalid typed array length" for seemingly-valid inputs


I have the following snippet:

new Uint16Array( arraybuffer, 0, 18108 );

I know that arraybuffer is an instance of ArrayBuffer, and that arraybuffer.byteLength is 31984. The content of the arraybuffer is a black box to me. Because the buffer's byteLength is > 18108, I expect this to just work. Instead, I get the following errors:

Chrome:

RangeError: Invalid typed array length

Firefox:

TypeError: invalid arguments

What might cause this to fail, or how can I inspect an ArrayBuffer I can't open?


Solution

  • Well, I misunderstood the TypedArray / Uint16Array constructor. The second argument is a byteOffset, but the third argument is not byte length: It is length in elements.

    From TypedArray docs:

    length

    When called with a length argument, an internal array buffer is created in memory of size length multiplied by BYTES_PER_ELEMENT bytes containing 0 value.

    Since Uint16Array.BYTES_PER_ELEMENT is 2, the arraybuffer would need to be at least 2 * 18108 bytes long, which it is not.