public override int Read(byte[] buffer, int offset, int count)
{
int startOffset = (int)(_position % _blockSize);
if (startOffset == 0 && (count % _blockSize == 0 || _position + count == Length))
{
// Aligned read - pass through to underlying stream.
WrappedStream.Position = _position;
int numRead = WrappedStream.Read(buffer, offset, count);
_position += numRead;
return(numRead);
}
long startPos = MathUtilities.RoundDown(_position, _blockSize);
long endPos = MathUtilities.RoundUp(_position + count, _blockSize);
if (endPos - startPos > int.MaxValue)
{
throw new IOException("Oversized read, after alignment");
}
byte[] tempBuffer = new byte[endPos - startPos];
WrappedStream.Position = startPos;
int read = WrappedStream.Read(tempBuffer, 0, tempBuffer.Length);
int available = Math.Min(count, read - startOffset);
Array.Copy(tempBuffer, startOffset, buffer, offset, available);
_position += available;
return(available);
}