class BufferUtils {

    public static ByteBuffer addCapacity(ByteBuffer buffer, int capacity) {
        int srcPos = buffer.position();
        int newCapacity = srcPos + capacity;
        ByteBuffer newBuffer;
        if (buffer.hasArray()) {
            newBuffer = ByteBuffer.wrap(Arrays.copyOfRange(buffer.array(), buffer.arrayOffset(), buffer.arrayOffset() + newCapacity));
            newBuffer.position(srcPos);
        } else {
            newBuffer = BufferUtils.allocateDirect(newCapacity);
            BufferUtils.flipToFill(newBuffer);
            BufferUtils.flipToFlush(buffer, 0);
            newBuffer.put(buffer);
        }
        return newBuffer;
    }

}