Skip to content
Daniel Wirtz edited this page Jan 5, 2014 · 12 revisions

Each ByteBuffer instance wrapps an ArrayBuffer in the browser or a Buffer under node.js and remembers the contents that we are interested in through its offset and limit properties, which are both absolute indexes on the underlying backing buffer.

Let's say that we want to gather some bytes received over the network one by one and that we expect to receive up to 5 bytes ...

var buffer = ByteBuffer.allocate(5); // offset=0, limit=0
// buffer = |00 00 00 00 00

...and that we want to reuse that exact ByteBuffer for each subsequent operation for performance reasons:

buffer.clear(); // offset=0, limit=0
buffer.writeUint8(0x01); // offset=1
buffer.writeUint8(0x02); // offset=2
buffer.writeUint8(0x03); // offset=3
buffer = buffer.flip(); // limit=offset=3, offset=0
// buffer = <01 02 03>00 00
buffer.clear(); // offset=0, limit=0
buffer.writeUint8(0x04); // offset=1
buffer.flip(); // limit=offset=1, offset=0
// buffer = <04>02 03 00 00

etc.

That's what offset and limit are for: Working with the same old buffer, operation by operation, all day long without the need to have extra variables to do this manually.

Next: Relative vs. absolute operations

Clone this wiki locally