In typed array specification there is a constructor that allows to take an existing ArrayBuffer and treat is as another array type. It is interesting that offset parameter must be a multiple of the underlying type of the constructed array. What was the reason for this limitation?
For background - I am trying to encode a binary buffer to be sent over WebSocket. The buffer contains various variables of different size. Originally I wanted to use the following code:
var buffer = new ArrayBuffer(10);
new Uint32Array(buffer, 0, 1)[0] = 234;
new Int16Array(buffer, 4, 1)[0] = -23;
new Uint32Array(buffer, 6, 1)[0] = 6000; // Exception is raised here,
// because 6 is not multiple of 4
To make this work I would need to rewrite last line as following:
var tempArray = new Uint32Array(1); // Create 32-bit array
tempArray[0] = 6000; // Write 32-bit number
var u8Src = new Uint8Array(tempArray, 0); // Create 8-bit view of the array
var u8Dest = new Uint8Array(buffer, 6, 4); // Create 8-bit view of the buffer
u8Dest.set(u8Src); // Copy bytes one by one
This is too much code for such a simple operation.