Code example for ByteBuffer

Methods: asReadOnlyBuffer, get, getInt, limit, position, remaining

0
    this.numBytes = numBytes;
 
    bitsToShift = 32 - (numBytes << 3); // numBytes * 8
 
    int numBufferBytes = 4 - numBytes;
    size = (buffer.remaining() - numBufferBytes) / numBytes;
  } 
 
  @Override 
  public int size() 
  { 
    return size;
  } 
 
  @Override 
  public int get(int index)
  { 
    return buffer.getInt(buffer.position() + (index * numBytes)) >>> bitsToShift;
  } 
 
  public byte[] getBytesNoPadding() 
  { 
    int bytesToTake = buffer.remaining() - (4 - numBytes);
    byte[] bytes = new byte[bytesToTake];
    buffer.asReadOnlyBuffer().get(bytes);
    return bytes;
  } 
 
  public byte[] getBytes() 
  { 
    byte[] bytes = new byte[buffer.remaining()];
    buffer.asReadOnlyBuffer().get(bytes);
    return bytes;
  } 
 
  @Override 
  public int compareTo(VSizeIndexedInts o)
  { 
    int retVal = Ints.compare(numBytes, o.numBytes);
 
    if (retVal == 0) {
      retVal = buffer.compareTo(o.buffer);
    } 
     
    return retVal;    
  } 
 
  public int getNumBytes() 
  { 
    return numBytes;
  } 
 
  public int getSerializedSize() 
  { 
    return 1 + 1 + 4 + buffer.remaining();
  } 
 
  @Override 
  public Iterator<Integer> iterator()
  { 
    return new IndexedIntsIterator(this);
  } 
 
  public void writeToChannel(WritableByteChannel channel) throws IOException
  { 
    channel.write(ByteBuffer.wrap(new byte[]{version, (byte) numBytes}));
    channel.write(ByteBuffer.wrap(Ints.toByteArray(buffer.remaining())));
    channel.write(buffer.asReadOnlyBuffer());
  } 
 
  public static VSizeIndexedInts readFromByteBuffer(ByteBuffer buffer)
  { 
    byte versionFromBuffer = buffer.get();
 
    if (version == versionFromBuffer) {
      int numBytes = buffer.get();
      int size = buffer.getInt();
      ByteBuffer bufferToUse = buffer.asReadOnlyBuffer();
      bufferToUse.limit(bufferToUse.position() + size);
      buffer.position(bufferToUse.limit());
 
      return new VSizeIndexedInts( 
          bufferToUse,
          numBytes
      );