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

Fix FlushAsyncInternal when emitting BOM #52812

Merged
merged 2 commits into from
May 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -942,8 +942,6 @@ private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, Cancellatio
}

Task flushTask = Core(flushStream, flushEncoder, cancellationToken);

_charPos = 0;
return flushTask;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can now be:

return Core(flushStream, flushEncoder, cancellationToken);

The separation was just to be able to have the charPos = 0 in the middle, but that's now gone.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, should be ok now


async Task Core(bool flushStream, bool flushEncoder, CancellationToken cancellationToken)
Expand All @@ -961,6 +959,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