Skip to content
Austin Chamberlin edited this page Feb 19, 2018 · 12 revisions

This visualization may help you understand the API.

Each ByteBuffer instance wraps 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=5
// 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=5
// buffer = <00 00 00 00 00>
buffer.writeUint8(0x01); // offset=1
buffer.writeUint8(0x02); // offset=2
buffer.writeUint8(0x03); // offset=3
// buffer = 01 02 03<00 00>
buffer.flip(); // limit=offset=3, offset=0
// buffer = <01 02 03>00 00
buffer.clear(); // offset=0, limit=5
// buffer = <01 02 03 00 00>
buffer.writeUint8(0x04); // offset=1
// buffer = 04<02 03 00 00>
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.

Plus: We can also mark offsets to jump back to them:

buffer.clear(); // offset=0, limit=5
// buffer = <04 02 03 00 00>
buffer.writeUint8(0x05); // offset=1
// buffer = 05<02 03 00 00>
buffer.mark(); // markedOffset=offset=1
buffer.writeUint8(0x07); // offset=2
// buffer = 05 07<03 00 00> --- Oops, that was wrong, let's do that again:
buffer.reset(); // offset=markedOffset=1, markedOffset=-1
// buffer = 05<07 03 00 00>
buffer.writeUint8(0x06); // offset=2
// buffer = 05 06<03 00 00>
buffer.flip(); // limit=offset=2, offset=0
// buffer = <05 06>03 00 00

Next: Relative vs. absolute operations

Clone this wiki locally