Typed Arrays byte offset

35 views Asked by At

Even though the byte offset is 12, and the underlying buffer size is of 12 bytes, how are we able to set the starting of int8Array beyond the underlying buffersize?

let buffer = new ArrayBuffer(12);
const intArray = new Int32Array(buffer);
console.log(intArray.buffer);
const int8Array = new Int8Array(buffer, 12);
int8Array[0] = 200;
console.log(intArray.buffer);

How is const int8Array = new Int8Array(buffer, 12) possible?

I was expecting a

RangeError: RangeError: Start offset 12 is outside the bounds of the buffer

1

There are 1 answers

2
BadPiggie On

The buffer which is an ArrayBuffer has size of 12 bytes. So the available index would be 1 to 11. Any index after 11 would be out of bounds.

When you create Int8Array with the offset of 12 bytes, It will skip 12 bytes from the buffer. But there is nothing after 11th index in the buffer, It will create an empty Int8Array with the length of 0.

Even though the size of Int8Array is 0, Still you can assign value by executing,

int8Array[0] = 200;