hunt.io.BufferUtils

Undocumented in source.

Members

Classes

BufferUtils
class BufferUtils

Buffer utility methods. <p> The standard JVM {@link ByteBuffer} can exist in two modes: In fill mode the valid data is between 0 and pos; In flush mode the valid data is between the pos and the limit. The various ByteBuffer methods assume a mode and some of them will switch or enforce a mode: Allocate and clear set fill mode; flip and compact switch modes; read and write assume fill and flush modes. This duality can result in confusing code such as: </p> <p> <pre> buffer.clear(); channel.write(buffer); </pre> <p> Which looks as if it should write no data, but in fact writes the buffer worth of garbage. </p> <p> The BufferUtils class provides a set of utilities that operate on the convention that ByteBuffers will always be left, passed in an API or returned from a method in the flush mode - ie with valid data between the pos and limit. This convention is adopted so as to avoid confusion as to what state a buffer is in and to avoid excessive copying of data that can result with the usage of compress. </p> <p> Thus this class provides alternate implementations of {@link #allocate(int)}, {@link #allocateDirect(int)} and {@link #clear(ByteBuffer)} that leave the buffer in flush mode. Thus the following tests will pass: </p> <p> <pre> ByteBuffer buffer = BufferUtils.allocate(1024); assert (buffer.remaining() == 0); BufferUtils.clear(buffer); assert (buffer.remaining() == 0); </pre> <p> If the BufferUtils methods {@link #fill(ByteBuffer, byte[], int, int)}, {@link #append(ByteBuffer, byte[], int, int)} or {@link #put(ByteBuffer, ByteBuffer)} are used, then the caller does not need to explicitly switch the buffer to fill mode. If the caller wishes to use other ByteBuffer bases libraries to fill a buffer, then they can use explicit calls of #flipToFill(ByteBuffer) and #flipToFlush(ByteBuffer, int) to change modes. Note because this convention attempts to avoid the copies of compact, the position is not set to zero on each fill cycle and so its value must be remembered: </p> <p> <pre> int pos = BufferUtils.flipToFill(buffer); try { buffer.put(data); } finally { flipToFlush(buffer, pos); } </pre> <p> The flipToFill method will effectively clear the buffer if it is empty and will compact the buffer if there is no space. </p>

Meta