From 2fec396d135e882376603f94b1d29bc4a42ab8f9 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 5 Jul 2017 14:11:35 +1000 Subject: [PATCH] Fixed BufferedStream.ReadByteSlow() to correctly set _readPos (#1) 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. --- src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs index 32aa4db3e662..4c8812368782 100644 --- a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs +++ b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs @@ -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++]; }