Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change exception for overflow in ArrayBufferWriter #32587

Merged
merged 13 commits into from
Mar 25, 2020
21 changes: 18 additions & 3 deletions src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,24 @@ private void CheckAndResizeBuffer(int sizeHint)

if (sizeHint > FreeCapacity)
{
int growBy = Math.Max(sizeHint, _buffer.Length);
int currentLength = _buffer.Length;
int growBy = Math.Max(sizeHint, currentLength);

if (_buffer.Length == 0)
if (currentLength == 0)
{
growBy = Math.Max(growBy, DefaultInitialBufferSize);
}

int newSize = checked(_buffer.Length + growBy);
int newSize = currentLength + growBy;

if ((uint)newSize > int.MaxValue)
{
newSize = currentLength + sizeHint;
if ((uint)newSize > int.MaxValue)
{
ThrowOutOfMemoryException((uint)newSize);
}
}

Array.Resize(ref _buffer, newSize);
}
Expand All @@ -186,5 +196,10 @@ private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity)
{
throw new InvalidOperationException(SR.Format(SR.BufferWriterAdvancedTooFar, capacity));
}

private static void ThrowOutOfMemoryException(uint capacity)
felipepessoto marked this conversation as resolved.
Show resolved Hide resolved
{
throw new OutOfMemoryException(SR.Format(SR.BufferMaximumSizeExceeded, capacity));
felipepessoto marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,13 @@ public void GetMemory_DefaultCtor(int sizeHint)
Assert.Equal(sizeHint <= 256 ? 256 : sizeHint, memory.Length);
}

[Fact]
public void GetMemory_ExceedMaximumBufferSize()
felipepessoto marked this conversation as resolved.
Show resolved Hide resolved
{
var output = new ArrayBufferWriter<T>(256);
Assert.Throws<OutOfMemoryException>(() => output.GetMemory(int.MaxValue));
felipepessoto marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public void GetMemory_InitSizeCtor()
{
Expand Down