-
Notifications
You must be signed in to change notification settings - Fork 155
Relative vs. absolute operations
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
By default (offset arguments to a method 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 in the performed read/write operation.
Simple example:
var source = ByteBuffer.fromHex("010203"); // offset=0, limit=3, <01 02 03>
source.readUint8(); // readUint8([offset])
// ^ This reads one byte from offset=0 and increases offset by 1, resulting in: source = 01<02 03>
Complex example:
var source = ByteBuffer.fromHex("010203"), // offset=0, limit=3, <01 02 03>
target = ByteBuffer.fromHex("000000"); // offset=0, limit=3, <00 00 00>
source.copy(target); // copy(target[, targetOffset, sourceOffset, sourceLimit])
// ^ This reads the bytes offset=0 to limit=3 from source, increasing its offset by 3,
// and writes these to target at offset=0, increasing also its offset by 3, resulting in:
// source = 01 02 03|, target = 01 02 03|
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.
Simple example:
var source = ByteBuffer.fromHex("010203"); // offset=0, limit=3, <01 02 03>
source.readUint8(0); // readUint8(offset)
// ^ This reads one byte from offset=0 and does not modify the offset, resulting in:
// source = <01 02 03>
Complex examples:
var source = ByteBuffer.fromHex("010203"), // offset=0, limit=3, <01 02 03>
target = ByteBuffer.fromHex("000000"); // offset=0, limit=3, <00 00 00>
source.copy(target, 0, 0, source.limit); // copy(target, targetOffset, sourceOffset, sourceLimit)
// ^ This reads bytes offset=0 to limit=3 from source, not modifying its offset,
// and writes these to the target at offset=0, also not modifying its offset,
// resulting in: source= <01 02 03>, target = <01 02 03>
source.copy(target, 0); // copy(target, targetOffset[, sourceOffset, sourceLimit])
// ^ This reads the bytes offset=0 to limit=3 from source, increasing the source's offset by 3,
// and writes these to target at the specified (!) offset=0, not modifying the target's offset,
// resulting in: source = 01 02 03|, target = <01 02 03>
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.