-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Add PipeReader.Create from ReadOnlySequence<byte> #48369
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
Merged
davidfowl
merged 6 commits into
dotnet:main
from
Alxandr:feat/pipe-reader-from-sequence
Mar 18, 2021
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
927e2d0
Add PipeReader.Create from ReadOnlySequence<byte>
Alxandr 74c7315
Simplify cancel behaviour
Alxandr 034e1c3
Use @halter73's suggestion for clarity
Alxandr e4fc411
Apply suggestions from code review
Alxandr 179468f
Merge branch 'main' into feat/pipe-reader-from-sequence
Alxandr c1dbc5b
Remove TryReadInternal
Alxandr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/SequencePipeReader.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Buffers; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.IO.Pipelines | ||
| { | ||
| internal sealed class SequencePipeReader : PipeReader | ||
| { | ||
| private ReadOnlySequence<byte> _sequence; | ||
| private bool _isReaderCompleted; | ||
|
|
||
| private int _cancelNext; | ||
|
|
||
| public SequencePipeReader(ReadOnlySequence<byte> sequence) | ||
| { | ||
| _sequence = sequence; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void AdvanceTo(SequencePosition consumed) | ||
| { | ||
| AdvanceTo(consumed, consumed); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) | ||
| { | ||
| ThrowIfCompleted(); | ||
|
|
||
| // Fast path: did we consume everything? | ||
| if (consumed.Equals(_sequence.End)) | ||
| { | ||
| _sequence = ReadOnlySequence<byte>.Empty; | ||
| return; | ||
| } | ||
davidfowl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| _sequence = _sequence.Slice(consumed); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void CancelPendingRead() | ||
| { | ||
| Interlocked.Exchange(ref _cancelNext, 1); | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void Complete(Exception? exception = null) | ||
| { | ||
| if (_isReaderCompleted) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| _isReaderCompleted = true; | ||
| _sequence = ReadOnlySequence<byte>.Empty; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| if (TryRead(out ReadResult result)) | ||
| { | ||
| return new ValueTask<ReadResult>(result); | ||
| } | ||
|
|
||
| result = new ReadResult(ReadOnlySequence<byte>.Empty, isCanceled: false, isCompleted: true); | ||
| return new ValueTask<ReadResult>(result); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override bool TryRead(out ReadResult result) | ||
| { | ||
| ThrowIfCompleted(); | ||
|
|
||
| bool isCancellationRequested = Interlocked.Exchange(ref _cancelNext, 0) == 1; | ||
| if (isCancellationRequested || _sequence.Length > 0) | ||
| { | ||
| result = new ReadResult(_sequence, isCancellationRequested, isCompleted: true); | ||
| return true; | ||
| } | ||
|
|
||
| result = default; | ||
| return false; | ||
| } | ||
|
|
||
| private void ThrowIfCompleted() | ||
| { | ||
| if (_isReaderCompleted) | ||
| { | ||
| ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
232 changes: 232 additions & 0 deletions
232
src/libraries/System.IO.Pipelines/tests/SequencePipeReaderTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Buffers; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Threading.Tasks; | ||
| using Xunit; | ||
|
|
||
| namespace System.IO.Pipelines.Tests | ||
| { | ||
| public class SequencePipeReaderTests | ||
| { | ||
| [Fact] | ||
| public async Task CanRead() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World")); | ||
| var reader = PipeReader.Create(sequence); | ||
|
|
||
| ReadResult readResult = await reader.ReadAsync(); | ||
| ReadOnlySequence<byte> buffer = readResult.Buffer; | ||
|
|
||
| Assert.Equal(11, buffer.Length); | ||
| Assert.True(buffer.IsSingleSegment); | ||
| Assert.Equal("Hello World", Encoding.ASCII.GetString(buffer.ToArray())); | ||
|
|
||
| reader.AdvanceTo(buffer.End); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task TryReadReturnsTrueIfBufferedBytesAndNotExaminedEverything() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World")); | ||
| var reader = PipeReader.Create(sequence); | ||
|
|
||
| ReadResult readResult = await reader.ReadAsync(); | ||
| ReadOnlySequence<byte> buffer = readResult.Buffer; | ||
| Assert.Equal(11, buffer.Length); | ||
| Assert.True(buffer.IsSingleSegment); | ||
| reader.AdvanceTo(buffer.Start, buffer.GetPosition(5)); | ||
|
|
||
| Assert.True(reader.TryRead(out readResult)); | ||
| Assert.Equal(11, buffer.Length); | ||
| Assert.True(buffer.IsSingleSegment); | ||
| Assert.Equal("Hello World", Encoding.ASCII.GetString(buffer.ToArray())); | ||
|
|
||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task TryReadReturnsFalseIfBufferedBytesAndEverythingExamined() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("Hello World")); | ||
| var reader = PipeReader.Create(sequence); | ||
|
|
||
| ReadResult readResult = await reader.ReadAsync(); | ||
| ReadOnlySequence<byte> buffer = readResult.Buffer; | ||
| Assert.Equal(11, buffer.Length); | ||
| Assert.True(buffer.IsSingleSegment); | ||
| reader.AdvanceTo(buffer.End); | ||
|
|
||
| Assert.False(reader.TryRead(out readResult)); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ReadAsyncAfterReceivingCompletedReadResultDoesNotThrow() | ||
| { | ||
| var sequence = ReadOnlySequence<byte>.Empty; | ||
| PipeReader reader = PipeReader.Create(sequence); | ||
| ReadResult readResult = await reader.ReadAsync(); | ||
| Assert.True(readResult.Buffer.IsEmpty); | ||
| Assert.True(readResult.IsCompleted); | ||
| reader.AdvanceTo(readResult.Buffer.End); | ||
|
|
||
| readResult = await reader.ReadAsync(); | ||
| Assert.True(readResult.Buffer.IsEmpty); | ||
| Assert.True(readResult.IsCompleted); | ||
| reader.AdvanceTo(readResult.Buffer.End); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DataCanBeReadMultipleTimes() | ||
| { | ||
| var helloBytes = Encoding.ASCII.GetBytes("Hello World"); | ||
| var sequence = new ReadOnlySequence<byte>(helloBytes); | ||
| PipeReader reader = PipeReader.Create(sequence); | ||
|
|
||
|
|
||
| ReadResult readResult = await reader.ReadAsync(); | ||
| ReadOnlySequence<byte> buffer = readResult.Buffer; | ||
| reader.AdvanceTo(buffer.Start, buffer.End); | ||
|
|
||
| // Make sure IsCompleted is true | ||
| readResult = await reader.ReadAsync(); | ||
| buffer = readResult.Buffer; | ||
| reader.AdvanceTo(buffer.Start, buffer.End); | ||
| Assert.True(readResult.IsCompleted); | ||
|
|
||
| var value = await ReadFromPipeAsString(reader); | ||
| Assert.Equal("Hello World", value); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task NextReadAfterPartiallyExaminedReturnsImmediately() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes(new string('a', 10000))); | ||
| PipeReader reader = PipeReader.Create(sequence); | ||
|
|
||
| ReadResult readResult = await reader.ReadAsync(); | ||
| reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.GetPosition(2048)); | ||
|
|
||
| ValueTask<ReadResult> task = reader.ReadAsync(); | ||
|
|
||
| // This should complete synchronously since | ||
| Assert.True(task.IsCompleted); | ||
|
|
||
| readResult = await task; | ||
| reader.AdvanceTo(readResult.Buffer.End); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task CompleteReaderWithoutAdvanceDoesNotThrow() | ||
| { | ||
| PipeReader reader = PipeReader.Create(ReadOnlySequence<byte>.Empty); | ||
| await reader.ReadAsync(); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task AdvanceAfterCompleteThrows() | ||
| { | ||
| PipeReader reader = PipeReader.Create(new ReadOnlySequence<byte>(new byte[100])); | ||
| ReadOnlySequence<byte> buffer = (await reader.ReadAsync()).Buffer; | ||
|
|
||
| reader.Complete(); | ||
|
|
||
| Assert.Throws<InvalidOperationException>(() => reader.AdvanceTo(buffer.End)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ThrowsOnReadAfterCompleteReader() | ||
| { | ||
| PipeReader reader = PipeReader.Create(ReadOnlySequence<byte>.Empty); | ||
|
|
||
| reader.Complete(); | ||
| await Assert.ThrowsAsync<InvalidOperationException>(async () => await reader.ReadAsync()); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void TryReadAfterCancelPendingReadReturnsTrue() | ||
| { | ||
| PipeReader reader = PipeReader.Create(ReadOnlySequence<byte>.Empty); | ||
|
|
||
| reader.CancelPendingRead(); | ||
|
|
||
| Assert.True(reader.TryRead(out ReadResult result)); | ||
| Assert.True(result.IsCanceled); | ||
| reader.AdvanceTo(result.Buffer.End); | ||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ReadAsyncReturnsCanceledIfCanceledBeforeRead() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(new byte[10000]); | ||
| PipeReader reader = PipeReader.Create(sequence); | ||
|
|
||
| // Make sure state isn't used from before | ||
| for (var i = 0; i < 3; i++) | ||
| { | ||
| reader.CancelPendingRead(); | ||
| ValueTask<ReadResult> readResultTask = reader.ReadAsync(); | ||
| Assert.True(readResultTask.IsCompleted); | ||
| ReadResult readResult = readResultTask.GetAwaiter().GetResult(); | ||
| Assert.True(readResult.IsCanceled); | ||
| readResult = await reader.ReadAsync(); | ||
| reader.AdvanceTo(readResult.Buffer.End); | ||
| } | ||
|
|
||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ReadAsyncReturnsCanceledInterleaved() | ||
| { | ||
| var sequence = new ReadOnlySequence<byte>(new byte[10000]); | ||
| PipeReader reader = PipeReader.Create(sequence); | ||
|
|
||
| // Cancel and Read interleaved to confirm cancellations are independent | ||
| for (var i = 0; i < 3; i++) | ||
| { | ||
| reader.CancelPendingRead(); | ||
| ValueTask<ReadResult> readResultTask = reader.ReadAsync(); | ||
| Assert.True(readResultTask.IsCompleted); | ||
| ReadResult readResult = readResultTask.GetAwaiter().GetResult(); | ||
| Assert.True(readResult.IsCanceled); | ||
|
|
||
| readResult = await reader.ReadAsync(); | ||
| Assert.False(readResult.IsCanceled); | ||
| } | ||
|
|
||
| reader.Complete(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void OnWriterCompletedNoops() | ||
| { | ||
| bool fired = false; | ||
| PipeReader reader = PipeReader.Create(ReadOnlySequence<byte>.Empty); | ||
| #pragma warning disable CS0618 // Type or member is obsolete | ||
| reader.OnWriterCompleted((_, __) => { fired = true; }, null); | ||
| #pragma warning restore CS0618 // Type or member is obsolete | ||
| reader.Complete(); | ||
| Assert.False(fired); | ||
| } | ||
|
|
||
| private static async Task<string> ReadFromPipeAsString(PipeReader reader) | ||
| { | ||
| ReadResult readResult = await reader.ReadAsync(); | ||
| var result = Encoding.ASCII.GetString(readResult.Buffer.ToArray()); | ||
| reader.AdvanceTo(readResult.Buffer.End); | ||
| return result; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this fine? It points to the docs for
ReadOnlySequence<T>, with no indication of it being only for bytes. Is this just how things are?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is that how the other docs are?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried to google this issue (because you can't do
ReadOnlySequence<byte>), and the idea here is that there is no docs page to link to forReadOnlySequence<byte>, but the is forReadOnlySequence<T>, so that is why I believe. I'm not sure where else I would find docs like this in .NET as I can't recall any off the top of my head at least.