Skip to content

ByteBuf read/write pointers

In Netty's ByteBuf class, data storage and retrieval are managed through a pointer system rather than a single position marker^[600-developer__big-data__netty__netty-ByteBuf.md]. This system divides the buffer's capacity into three distinct segments: discardable bytes, readable bytes (CONTENT), and writable bytes^[600-developer__big-data__netty__netty-ByteBuf.md].

Structure

The layout of a ByteBuf is defined by two primary indices: readerIndex and writerIndex^[600-developer__big-data__netty__netty-ByteBuf.md]. These pointers adhere to the following invariant:

0 <= readerIndex <= writerIndex <= capacity^[600-developer__big-data__netty__netty-ByteBuf.md]

The three regions defined by these pointers are^[600-developer__big-data__netty__netty-ByteBuf.md]:

  • Discardable bytes: The space between index 0 and readerIndex. This section contains data that has already been read.
  • Readable bytes (CONTENT): The space between readerIndex and writerIndex. This is the active data pending consumption.
  • Writable bytes: The space between writerIndex and capacity. This section is available for writing new data.

Reading Data

ByteBuf supports two modes of accessing data: absolute and relative^[600-developer__big-data__netty__netty-ByteBuf.md].

  • Absolute access: Methods like getByte(i) read data at a specific index without modifying the readerIndex^[600-developer__big-data__netty__netty-ByteBuf.md].
  • Relative access: Methods like readByte() read data starting from the current readerIndex and increment the pointer forward as data is consumed^[600-developer__big-data__netty__netty-ByteBuf.md].

The readability of the buffer can be checked using buffer.isReadable()^[600-developer__big-data__netty__netty-ByteBuf.md].

Managing Pointers

Discarding Read Bytes

The discardReadBytes() method is used to reclaim space consumed by the read operations^[600-developer__big-data__netty__netty-ByteBuf.md]. This operation shifts the readable bytes to the beginning of the buffer, effectively setting readerIndex to 0 and increasing the writable space at the end^[600-developer__big-data__netty__netty-ByteBuf.md].

Clearing

The clear() method resets the buffer pointers without necessarily zeroing out the memory content^[600-developer__big-data__netty__netty-ByteBuf.md]. It sets both readerIndex and writerIndex to 0, effectively converting the entire buffer capacity into writable bytes^[600-developer__big-data__netty__netty-ByteBuf.md].

Sources

^[600-developer__big-data__netty__netty-ByteBuf.md]