-
Couldn't load subscription status.
- Fork 5.2k
Description
Description
Calling BufferedStream.Write(array, offset, count) where count > 1073741823 results in an OverflowException.
This works as expected:
byte[] bytes = new byte[int.MaxValue / 2];
using (BufferedStream stream = new BufferedStream(Stream.Null))
{
stream.Write(bytes, 0, bytes.Length);
}
This throws an OverflowException (note the + 1):
byte[] bytes = new byte[(int.MaxValue / 2) + 1];
using (BufferedStream stream = new BufferedStream(Stream.Null))
{
stream.Write(bytes, 0, bytes.Length);
}
Expected behaviour is that the above should write successfully and not throw an OverflowException.
Configuration
- Windows 10
- VS 2019
- .NET 5.0
Regression?
Also fails in .NET Framework 4.7.2 and 4.8. Looking at Reference Source, the code seems to be the same.
Other information
I believe this is related to the heuristic check for useBuffer, where count is added twice:
checked
{ // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
totalUserbytes = _writePos + count;
useBuffer = (totalUserbytes + count < (_bufferSize + _bufferSize));
}
If count is larger than Int32.MaxValue / 2, adding it to itself will overflow.
While the comment "we do not expect buffer sizes big enough for an overflow" seems reasonable for the internal buffer, the buffer argument supplied to Write() comes from user code and it doesn't seem intuitive for BufferedStream to accept a different maximum buffer size to other Stream implementations.
Could this check use long arithmetic to avoid the overflow where count * 2 > Int32.MaxValue?