throw new IndexOutOfBoundsException("position=" + position + " limit=" + limit + "on " + toString());
if (buffersSize == 0 || (position == limit)) {
return Buffers.EMPTY_BYTE_BUFFER;
} else if (buffersSize == 1) {
final Buffer buffer = buffers[0];
final int bufferPos = buffer.position();
return buffer.toByteBuffer(bufferPos + position, bufferPos + limit);
}
checkIndex(position);
final int pos1 = lastSegmentIndex;
final int bufPosition = toActiveBufferPos(position);
checkIndex(limit - 1);
final int pos2 = lastSegmentIndex;
final int bufLimit = toActiveBufferPos(limit);
//noinspection ConstantConditions
if (pos1 == pos2) {
final Buffer buffer = buffers[pos1];
return buffer.toByteBuffer(bufPosition, bufLimit);
}
final ByteBuffer resultByteBuffer = MemoryUtils.allocateByteBuffer(
memoryManager, limit - position);
final Buffer startBuffer = buffers[pos1];
final ByteBufferArray array = ByteBufferArray.create();
fillByteBuffer(resultByteBuffer,
startBuffer.toByteBufferArray(array, bufPosition, startBuffer.limit()));
for(int i = pos1 + 1; i < pos2; i++) {
fillByteBuffer(resultByteBuffer, buffers[i].toByteBufferArray(array));
}
final Buffer endBuffer = buffers[pos2];
fillByteBuffer(resultByteBuffer,
endBuffer.toByteBufferArray(array, endBuffer.position(), bufLimit));
array.restore();
array.recycle();
return (ByteBuffer) resultByteBuffer.flip();