Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 976
Don McCurdy Avatar asked Mar 08 '17 05:03

Don McCurdy


People also ask

How to fix ‘rangeerror invalid array length’?

To fix the ‘RangeError: invalid array length’ when we’re developing JavaScript apps, we should make sure the array length value that we call the Array and ArrayBuffer constructors are called with a valid value. Also, we should make sure we set the length property of an array to a non-negative integer.

What is the cause of arraybuffer length error?

Cause of the error: The length of an Array or an ArrayBuffer can only be represented by an unsigned 32-bit integer, which only stores values ranging from 0 to 2 32 -1. While creating an Array or an ArrayBuffer, if the array length is either negative or greater than or equal to 2 32 then this error occurs.

What is invalid array length in JavaScript?

The JavaScript exception "Invalid array length" occurs when creating an Array or an ArrayBuffer which has a length which is either negative or larger or equal to 2 32, or when setting the Array.length property to a value which is either negative or larger or equal to 2 32.

What is the length argument in typedarray/uint16array?

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. 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.


1 Answers

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.

like image 81
Don McCurdy Avatar answered Oct 04 '22 11:10

Don McCurdy