Fix FlushAsyncInternal when emitting BOM (#52812)
authorGérald Barré <meziantou@users.noreply.github.com>
Wed, 26 May 2021 10:58:03 +0000 (06:58 -0400)
committerGitHub <noreply@github.com>
Wed, 26 May 2021 10:58:03 +0000 (06:58 -0400)
* Fix FlushAsyncInternal when emitting BOM

Update StreamWriter.WriteTests.cs
Update StreamWriter.WriteTests.cs

* Remove temporary variable

src/libraries/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs
src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs

index 269a756..c531795 100644 (file)
@@ -415,5 +415,20 @@ namespace System.IO.Tests
                 Assert.False(tempStream.CanRead);
             }
         }
+
+        [Fact]
+        public async Task StreamWriter_WriteAsync_EmitBOMAndFlushDataWhenBufferIsFull()
+        {
+            Encoding UTF8BOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true);
+
+            using (var s = new MemoryStream())
+            using (var writer = new StreamWriter(s, UTF8BOM, 4))
+            {
+                await writer.WriteAsync("abcdefg");
+                await writer.FlushAsync();
+
+                Assert.Equal(10, s.Length); // BOM (3) + string value (7)
+            }
+        }
     }
 }
index ce84fbf..8752117 100644 (file)
@@ -941,10 +941,7 @@ namespace System.IO
                 return Task.CompletedTask;
             }
 
-            Task flushTask = Core(flushStream, flushEncoder, cancellationToken);
-
-            _charPos = 0;
-            return flushTask;
+            return Core(flushStream, flushEncoder, cancellationToken);
 
             async Task Core(bool flushStream, bool flushEncoder, CancellationToken cancellationToken)
             {
@@ -961,6 +958,7 @@ namespace System.IO
                 byte[] byteBuffer = _byteBuffer ??= new byte[_encoding.GetMaxByteCount(_charBuffer.Length)];
 
                 int count = _encoder.GetBytes(new ReadOnlySpan<char>(_charBuffer, 0, _charPos), byteBuffer, flushEncoder);
+                _charPos = 0;
                 if (count > 0)
                 {
                     await _stream.WriteAsync(new ReadOnlyMemory<byte>(byteBuffer, 0, count), cancellationToken).ConfigureAwait(false);