Sub topic 2
Sharing a Buffer: byteOffset, length, and Alignment
This chapter assumes you already know how to create an ArrayBuffer and wrap it in a typed array, and that you know the element sizes (1, 2, 4, or 8 bytes).
Views Over Part of a Buffer
A typed array constructor accepts (buffer, byteOffset, length). byteOffset is where the view starts, in bytes. length counts elements, not bytes. The offset must be a multiple of the element size, or the constructor throws a RangeError.
const buf = new ArrayBuffer(8);
const ok = new Uint32Array(buf, 4, 1); // byteOffset 4 is a multiple of 4
console.log(ok.byteOffset, ok.length); // 4 1
try {
new Uint32Array(buf, 1);
} catch (e) {
console.log(e instanceof RangeError); // true
}subarray, slice, set, and from
People often confuse which methods share memory and which ones copy it. subarray returns a new view over the same bytes. slice copies the bytes into a new buffer.
const a = new Uint8Array([1, 2, 3, 4]);
a.subarray(1, 3)[0] = 99;
console.log(a[1]); // 99, shared memory
const copy = a.slice(1, 3);
copy[0] = 0;
console.log(a[1]); // still 99
a.set([7, 8], 2); // copy values in starting at index 2
console.log(a); // Uint8Array [1, 99, 7, 8]
console.log(Uint8Array.from([1, 2, 3], x => x * 2)); // Uint8Array [2, 4, 6]Byte Order
Byte order (endianness) is the order in which a multi-byte value's bytes sit in memory. Little-endian stores the least significant byte first. Typed arrays use the platform's byte order, and almost all hardware is little-endian.
const buf = new ArrayBuffer(4);
new Uint32Array(buf)[0] = 0x01020304;
console.log(new Uint8Array(buf)[0]); // 4 on little-endian platformsDataView for Explicit Order
A DataView reads and writes any type at any byte offset, so alignment does not matter. It uses big-endian order unless you pass true as the littleEndian argument. Use it for file formats and network protocols, because they fix their own byte order.
const dv = new DataView(new ArrayBuffer(6));
dv.setUint16(0, 0x1234); // big-endian
dv.setUint32(2, 0xdeadbeef, true); // little-endian, unaligned offset
console.log(dv.getUint8(0).toString(16)); // "12"
console.log(dv.getUint8(2).toString(16)); // "ef"
console.log(dv.getUint32(2, true).toString(16)); // "deadbeef"Exercise
What does new Uint16Array(new ArrayBuffer(8), 3) do, and how would you read a 16-bit value at byte offset 3 instead?
Show answer
It throws a RangeError, because offset 3 is not a multiple of 2. Use new DataView(buffer).getUint16(3, littleEndian) instead, since DataView permits unaligned access.