Skip to content

Relative vs. absolute operations

Daniel Wirtz edited this page Jan 5, 2014 · 18 revisions

ByteBuffer.js 3 utilizes exactly two different ways to manipulate a ByteBuffer's contents:

  • Relative read/write operations with offset arguments being omitted and
  • Absolute read/write operations with offset argument being specified

Relative operations

By default (offset arguments have been omitted), all read/write operations are relative. This means that the ByteBuffer's offset will be modified according to the number of bytes affected by the performed read/write operation.

Exampl 1e:

var source = ByteBuffer.fromHex("010203"); // offset=0, limit=3
// source = <01 02 03>
source.readUint8();
// source = 01<02 03>

This reads one byte from offset=source.offset (not specified) and increases offset by 1.

Example 2:

var source = ByteBuffer.fromHex("010203"), // offset=0, limit=3
    target = ByteBuffer.fromHex("000000"); // offset=0, limit=3
// source = <01 02 03>, target = <00 00 00>
source.copy(target);
// source = 01 02 03|, target = 01 02 03|

This reads the bytes offset=source.offset=0 to limit=source.limit=3 (both not specified) from source, increasing its offset by 3, and writes these to target at offset=target.offset=0 (also not specified), increasing also its offset by 3.

Absolute operations

If a method is called with offset arguments begin specified, the read/write operation is absolute. This means that the ByteBuffer's offset will not be modified.

Example 1:

var source = ByteBuffer.fromHex("010203"); // offset=0, limit=3
// source = <01 02 03>
source.readUint8(0);
// source = <01 02 03>

This reads one byte from offset=0 (specified) and does not modify the offset.

Example 2:

var source = ByteBuffer.fromHex("010203"), // offset=0, limit=3
    target = ByteBuffer.fromHex("000000"); // offset=0, limit=3
// source= <01 02 03>, target = <01 02 03>
source.copy(target, 0, 0, source.limit);
// source= <01 02 03>, target = <01 02 03>

This reads 3 bytes from offset=0 to limit=3 (both specified) from source, not modifying its offset, and writes these to the target at offset=0 (also specified), also not modifying its offset.

Example 3 (mixed):

// source= <01 02 03>, target = <01 02 03>
source.copy(target, 0);
// source = 01 02 03|, target = <01 02 03>

This reads the bytes offset=source.offset=0 to limit=source.limit=3 (not specified) from source, increasing the source's offset by 3, and writes these to target at offset=0 (which is specified), not modifying the target's offset.

Why is this useful?

With relative operations, you do not have to take care of offsets yourself, effecticely saving you one variable to manage and giving you a clean way to work with the contents step by step. This is especially useful when working with different string encodings or varints, as the resulting number of bytes read or written is variable.

Clone this wiki locally