Skip to content

Commit

Permalink
Fix FlushAsyncInternal when emitting BOM (#52812)
Browse files Browse the repository at this point in the history
* Fix FlushAsyncInternal when emitting BOM


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

* Remove temporary variable
  • Loading branch information
meziantou authored May 26, 2021
1 parent ab7492c commit 5f7ba2b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -415,5 +415,20 @@ public void StreamWriter_WithOptionalArguments_NoExceptions()
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)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -941,10 +941,7 @@ private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, Cancellatio
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)
{
Expand All @@ -961,6 +958,7 @@ async Task Core(bool flushStream, bool flushEncoder, CancellationToken cancellat
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);
Expand Down

0 comments on commit 5f7ba2b

Please sign in to comment.