diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs index 09aa09d3446056..df026a925b43ba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs @@ -1078,7 +1078,8 @@ private async ValueTask WriteToUnderlyingStreamAsync( { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + buffer.Length; - useBuffer = (totalUserBytes + buffer.Length < (_bufferSize + _bufferSize)); + // Allow current totalUserBytes up to int.MaxValue by using uint arithmetic operation for totalUserBytes + buffer.Length + useBuffer = ((uint)totalUserBytes + buffer.Length < (_bufferSize + _bufferSize)); } if (useBuffer) diff --git a/src/libraries/System.Runtime/tests/System.IO.Tests/BufferedStream/BufferedStreamTests.cs b/src/libraries/System.Runtime/tests/System.IO.Tests/BufferedStream/BufferedStreamTests.cs index 8d11c80336711a..009d3a0e51025f 100644 --- a/src/libraries/System.Runtime/tests/System.IO.Tests/BufferedStream/BufferedStreamTests.cs +++ b/src/libraries/System.Runtime/tests/System.IO.Tests/BufferedStream/BufferedStreamTests.cs @@ -99,6 +99,29 @@ public void WriteFromSpan_InputSizeLargerThanHalfOfMaxInt_ShouldSuccess() } } + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))] + [OuterLoop] + public async Task WriteAsyncFromMemory_InputSizeLargerThanHalfOfMaxInt_ShouldSuccess() + { + const int InputSize = int.MaxValue / 2 + 1; + byte[] bytes; + try + { + bytes = new byte[InputSize]; + } + catch (OutOfMemoryException) + { + throw new SkipTestException("Not enough memory"); + } + + var writableStream = new WriteOnlyStream(); + using (var bs = new BufferedStream(writableStream)) + { + await bs.WriteAsync(new ReadOnlyMemory(bytes)); + Assert.Equal(InputSize, writableStream.Position); + } + } + [Theory] [InlineData(true)] [InlineData(false)]