|-------|---------- secondary buffer (slice) ----------------|
*/
// If the byte size to read fits within the extra buffer, use the extraBuffer
MessageBuffer newBuffer = byteSizeToRead <= extraBuffer.size() ? extraBuffer : MessageBuffer.newBuffer(byteSizeToRead);
// Copy the remaining buffer contents to the new buffer
int firstHalfSize = buffer.size() - position;
if(firstHalfSize > 0)
buffer.copyTo(position, newBuffer, 0, firstHalfSize);
// Read the last half contents from the next buffers
int cursor = firstHalfSize;
while(cursor < byteSizeToRead) {
secondaryBuffer = takeNextBuffer();
if(secondaryBuffer == null)
return false; // No more buffer to read
// Copy the contents from the secondary buffer to the new buffer
int copyLen = Math.min(byteSizeToRead - cursor, secondaryBuffer.size());
secondaryBuffer.copyTo(0, newBuffer, cursor, copyLen);
// Truncate the copied part from the secondaryBuffer
secondaryBuffer = copyLen == secondaryBuffer.size() ? null : secondaryBuffer.slice(copyLen, secondaryBuffer.size()-copyLen);
cursor += copyLen;
}
// Replace the current buffer with the new buffer
totalReadBytes += position;
buffer = byteSizeToRead == newBuffer.size() ? newBuffer : newBuffer.slice(0, byteSizeToRead);
position = 0;
return true;
}