javascript / expert
Snippet
Zero-Copy Binary Parsing using TypedArray Views and Array Buffer Slicing
DataView and TypedArray views allow high-performance binary protocol parsing directly on existing ArrayBuffer memory without allocating intermediate copied arrays.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { Buffer } from 'node:buffer';function parseBinaryFrame(rawBuffer) {const view = new DataView(rawBuffer.buffer, rawBuffer.byteOffset, rawBuffer.byteLength);const magicHeader = view.getUint32(0, false);const payloadLength = view.getUint16(4, false);const payloadBytes = new Uint8Array(rawBuffer.buffer, rawBuffer.byteOffset + 6, payloadLength);return { magicHeader, payloadLength, payloadBytes };}const frame = Buffer.from([0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x04, 0x48, 0x45, 0x4C, 0x4F]);const parsed = parseBinaryFrame(frame);
nodejs
Breakdown
1
import { Buffer } from 'node:buffer';
Imports the native Node.js Buffer module using node: protocol syntax.
2
function parseBinaryFrame(rawBuffer) {
Declares the parser function accepting a Node.js Buffer or Uint8Array.
3
const view = new DataView(rawBuffer.buffer, rawBuffer.byteOffset, rawBuffer.byteLength);
Constructs a DataView over the precise underlying ArrayBuffer memory slice.
4
const magicHeader = view.getUint32(0, false);
Reads a 32-bit big-endian unsigned integer header from offset 0.
5
const payloadLength = view.getUint16(4, false);
Reads a 16-bit big-endian payload size from offset 4.
6
const payloadBytes = new Uint8Array(rawBuffer.buffer, rawBuffer.byteOffset + 6, payloadLength);
Creates a zero-copy Uint8Array view covering payload bytes without cloning memory.
7
return { magicHeader, payloadLength, payloadBytes };
Returns the parsed binary data fields.
8
const frame = Buffer.from([0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x04, 0x48, 0x45, 0x4C, 0x4F]);
Allocates a sample binary protocol packet buffer.
9
const parsed = parseBinaryFrame(frame);
Executes zero-copy parsing over the packet buffer.