Skip to content

Relative vs. absolute operations

Daniel Wirtz edited this page Oct 25, 2015 · 18 revisions

Each ByteBuffer 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.

Example 1:

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=0 (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.copyTo(target);
// source = 01 02 03|, target = 01 02 03|

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

Absolute operations

If a method is called with offset arguments 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.copyTo(target, 0, 0, 3);
// source= <01 02 03>, target = <01 02 03>

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

Example 3 (mixed):

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

This reads the bytes sourceOffset=source.offset=0 to sourceLimit=source.limit=3 (not specified) from source, increasing the source's offset by 3, and writes these to target at targetOffset=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