private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken)
{
try
{
while (true)
{
int bytesRead = await readTask.ConfigureAwait(false);
EnsureNotDisposed();
if (bytesRead <= 0)
{
// This indicates the base stream has received EOF
return 0;
}
else if (bytesRead > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
cancellationToken.ThrowIfCancellationRequested();
// Feed the data from base stream into decompression engine
_inflater.SetInput(_buffer, 0, bytesRead);
bytesRead = _inflater.Inflate(array, offset, count);
if (bytesRead == 0 && !_inflater.Finished())
{
// We could have read in head information and didn't get any data.
// Read from the base stream again.
readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
if (readTask == null)
{
throw new InvalidOperationException(SR.NotSupported_UnreadableStream);
}
}
else
{
return bytesRead;
}
}
}
finally
{
AsyncOperationCompleting();
}
}