Wednesday, September 3, 2014

Java - ByteBuffer



There are 2 states in a ByteBuffer object, read-mode and write-mode. There are 3 importantsvalues in a ByteBuffer:
position, limit and capacity.

Capacity: this gives us the maximum bytes a buffer can have, it's a buffer size.

Position: in write-mode it's the index of the next byte to write. If 4 bytes has been written into a ByteBuffer object, than the position is 4, which is the 5th element of a ByteBuffer's array. In read-mode it's the index of the next byte to read, the logic is the same as in write-mode.

Limit: is the space left to write or the amount of bytes yet to read, depending on the state.

Initial state of ByteBuffer is write-mode, why? Well, if you create a new buffer, the buffer is normally empty,
because you haven't filled it yet, so there's nothing to read also. So the first thing to do is to fill the buffer with data, that's why the first state of a ByteBuffer object is write-mode.

Write data to ByteBuffer:
byte[] data = new byte[48];
byteBuffer.put(data, 0, numBytes);

Remaining data means in this state (write-mode), how many bytes available in the buffer to write.
byteBuffer.remaining();

Switch from write-mode to read-mode
byteBuffer.flip();

Remaining data means in this state (=read-mode), how many bytes available left in the buffer to read.
byteBuffer.remaining();

Read data into the buffer:
byteBuffer.get(buffer);

This method means clear all the bytes, reset its states and switch to write-mode.
byteBuffer.clear();

This method means move the remaining bytes to the beginning of the buffer, update its states and switch to write-mode.
byteBuffer.compact();

This method resets its states after reading, so you can read again from the beginning.
byteBuffer.rewind();

mark its current states
byteBuffer.mark();
do some reading...
change it to its pervious states
byteBuffer.reset();

Source:
http://www.ibm.com/developerworks/java/tutorials/j-nio/j-nio.html
http://www.tech-recipes.com/rx/1438/java-working-with-buffers/
http://tutorials.jenkov.com/java-nio/buffers.html

NSNotification example