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

Override Read(Span)/ReadByte on PipeReaderStream #55086

Merged
merged 1 commit into from
Jul 8, 2021
Merged
Changes from all commits
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 @@ -45,8 +45,28 @@ public override void Flush()
{
}

public override int Read(byte[] buffer, int offset, int count) =>
ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer is null)
{
throw new ArgumentNullException(nameof(buffer));
}

return ReadInternal(new Span<byte>(buffer, offset, count));
}

public override int ReadByte()
{
Span<byte> oneByte = stackalloc byte[1];
return ReadInternal(oneByte) == 0 ? -1 : oneByte[0];
}

private int ReadInternal(Span<byte> buffer)
{
ValueTask<ReadResult> vt = _pipeReader.ReadAsync();
ReadResult result = vt.IsCompletedSuccessfully ? vt.Result : vt.AsTask().Result;
return HandleReadResult(result, buffer);
}

public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();

Expand All @@ -71,6 +91,11 @@ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Cancel
}

#if (!NETSTANDARD2_0 && !NETFRAMEWORK)
public override int Read(Span<byte> buffer)
{
return ReadInternal(buffer);
}

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
return ReadAsyncInternal(buffer, cancellationToken);
Expand All @@ -80,7 +105,11 @@ public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken
private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, CancellationToken cancellationToken)
{
ReadResult result = await _pipeReader.ReadAsync(cancellationToken).ConfigureAwait(false);
return HandleReadResult(result, buffer.Span);
}

private int HandleReadResult(ReadResult result, Span<byte> buffer)
{
if (result.IsCanceled)
{
ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
Expand All @@ -98,7 +127,7 @@ private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, Cancellation

ReadOnlySequence<byte> slice = actual == bufferLength ? sequence : sequence.Slice(0, actual);
consumed = slice.End;
slice.CopyTo(buffer.Span);
slice.CopyTo(buffer);

return actual;
}
Expand Down