Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

Commit

Permalink
Fixed BufferedStream.ReadByteSlow() to correctly set _readPos (#1)
Browse files Browse the repository at this point in the history
The following code throws an exception, caused by incorrect logic in BufferedStream.ReadByteSlow():

            byte[] input = new byte[] { 1, 2 };
            using (var reader = new BufferedStream(new MemoryStream(input), 2))
            {
                reader.ReadByte();
                reader.ReadByte();
                reader.ReadByte();

                byte[] mybuffer = new byte[10];
                reader.Read(mybuffer, 0, 1);   // throws System.ArgumentOutOfRangeException: 'Non-negative number required.'
            }

When the input data is exhausted through a sequence of ReadByte() calls, ReadByteSlow() does not reset _readPos to zero.
This causes a break in the contract specified in Read() - because because _readLen - _readPos is negative.
Then the block copy fails because the count to copy is negative.
Fix is to reset _readPos to zero before returning -1.
  • Loading branch information
channeladam authored and stephentoub committed Jul 6, 2017
1 parent 4a9d2b8 commit 2fec396
Showing 1 changed file with 2 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -690,10 +690,11 @@ private int ReadByteSlow()

EnsureBufferAllocated();
_readLen = _stream.Read(_buffer, 0, _bufferSize);
_readPos = 0;

if (_readLen == 0)
return -1;

_readPos = 0;
return _buffer[_readPos++];
}

Expand Down

0 comments on commit 2fec396

Please sign in to comment.