forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Stream wrappers for memory and text-based types #1
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
Closed
Closed
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
c5d1781
Stream wrappers for String, ReadOnlyMemory<char>, ReadOnlyMemory<byte…
ViveliDuCh bbbf858
README update
ViveliDuCh ae2b9ce
StringStream can seek, get/set position and read non-sequentially. Up…
ViveliDuCh 0e9dd93
ReadOnly/Span<byte> overloads, and WriteaAsyn, ReadAsyn overrides for…
ViveliDuCh 42157f3
MemoryTStream and ReadOnlyMemoryStream merged into MemoryTStream
ViveliDuCh 7273ed1
Merge ROMemoryStream and MemoryTStream into MemoryTStream and remove …
ViveliDuCh 056df04
Cleanup: defensive coding and edge cases
ViveliDuCh 2bdaf3c
Update README. Address PR feedback
ViveliDuCh 4b7a67b
Add static methods into System.IO.Stream for Corelib types. Add a cla…
ViveliDuCh feb2e92
Address PR feedback
ViveliDuCh 947a27c
Address PR feedback - Same exception patterns as existing Stream impl…
ViveliDuCh 2c59022
Feedback - Fix using/namespaces plus MemoryByteStream
ViveliDuCh 7aaf192
Stream extension method with C#14 extension members pattern for ReadO…
ViveliDuCh 1c895e8
Fix XML documentation
ViveliDuCh df12a99
API replacements in production code
ViveliDuCh 62015c7
Merge remote-tracking branch 'upstream/main' into stream-tests
ViveliDuCh 6a79df0
Implementation update based on latest API Review final consensus
ViveliDuCh 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
203 changes: 203 additions & 0 deletions
203
src/libraries/System.Memory/src/System/Buffers/ReadOnlySequenceStream.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,203 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| using System.Threading; | ||
| using System.IO; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.Buffers | ||
| { | ||
| /// <summary> | ||
| /// Provides a seekable, read-only <see cref="Stream"/> implementation over a <see cref="ReadOnlySequence{T}"/> of bytes. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This type is not thread-safe. Synchronize access if the stream is used concurrently. | ||
| /// The underlying sequence should not be modified while the stream is in use. | ||
| /// Seeking beyond the end of the stream is supported; subsequent reads will return zero bytes. | ||
| /// </remarks> | ||
| // Seekable Stream from ReadOnlySequence<byte> | ||
| public sealed class ReadOnlySequenceStream : Stream | ||
| { | ||
| private ReadOnlySequence<byte> _sequence; | ||
| private SequencePosition _position; | ||
| private long _positionPastEnd; // -1 if within bounds, or the actual position if past end | ||
| private bool _isDisposed; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="ReadOnlySequenceStream"/> class over the specified <see cref="ReadOnlySequence{Byte}"/>. | ||
| /// </summary> | ||
| /// <param name="sequence">The <see cref="ReadOnlySequence{Byte}"/> to wrap.</param> | ||
| public ReadOnlySequenceStream(ReadOnlySequence<byte> sequence) | ||
| { | ||
| _sequence = sequence; | ||
| _position = sequence.Start; | ||
| _positionPastEnd = -1; | ||
| _isDisposed = false; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override bool CanRead => !_isDisposed; | ||
|
|
||
| /// <inheritdoc /> | ||
| public override bool CanSeek => !_isDisposed; | ||
|
|
||
| /// <inheritdoc /> | ||
| public override bool CanWrite => false; | ||
|
|
||
| private void EnsureNotDisposed() => ObjectDisposedException.ThrowIf(_isDisposed, this); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override long Length | ||
| { | ||
| get | ||
| { | ||
| EnsureNotDisposed(); | ||
| return _sequence.Length; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override long Position | ||
| { | ||
| get | ||
| { | ||
| EnsureNotDisposed(); | ||
| return _positionPastEnd >= 0 ? _positionPastEnd : _sequence.Slice(_sequence.Start, _position).Length; | ||
| } | ||
| set | ||
| { | ||
| EnsureNotDisposed(); | ||
| ArgumentOutOfRangeException.ThrowIfNegative(value); | ||
|
|
||
| // Allow seeking past the end | ||
| if (value >= Length) | ||
| { | ||
| _position = _sequence.End; | ||
| _positionPastEnd = value; | ||
| } | ||
| else | ||
| { | ||
| _position = _sequence.GetPosition(value, _sequence.Start); | ||
| _positionPastEnd = -1; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override int Read(byte[] buffer, int offset, int count) | ||
| { | ||
| ValidateBufferArguments(buffer, offset, count); | ||
| return Read(buffer.AsSpan(offset, count)); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override int Read(Span<byte> buffer) | ||
| { | ||
| EnsureNotDisposed(); | ||
|
|
||
| if (_positionPastEnd >= 0) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| ReadOnlySequence<byte> remaining = _sequence.Slice(_position); | ||
| int n = (int)Math.Min(remaining.Length, buffer.Length); | ||
| if (n <= 0) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| remaining.Slice(0, n).CopyTo(buffer); | ||
| _position = _sequence.GetPosition(n, _position); | ||
| return n; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
| { | ||
| ValidateBufferArguments(buffer, offset, count); | ||
|
|
||
| // If cancellation was requested, bail early | ||
| if (cancellationToken.IsCancellationRequested) | ||
| return Task.FromCanceled<int>(cancellationToken); | ||
|
|
||
| int n = Read(buffer, offset, count); | ||
| return Task.FromResult(n); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) | ||
| { | ||
| if (cancellationToken.IsCancellationRequested) | ||
| { | ||
| return ValueTask.FromCanceled<int>(cancellationToken); | ||
| } | ||
|
|
||
| int bytesRead = Read(buffer.Span); | ||
| return new ValueTask<int>(bytesRead); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(SR.NotSupported_UnwritableStream); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void Write(ReadOnlySpan<byte> buffer) => throw new NotSupportedException(SR.NotSupported_UnwritableStream); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new NotSupportedException(SR.NotSupported_UnwritableStream); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => throw new NotSupportedException(SR.NotSupported_UnwritableStream); | ||
|
|
||
| /// <summary> | ||
| /// Sets the position within the current stream. | ||
| /// </summary> | ||
| /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> | ||
| /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param> | ||
| /// <returns>The new position within the stream.</returns> | ||
| public override long Seek(long offset, SeekOrigin origin) | ||
| { | ||
| EnsureNotDisposed(); | ||
|
|
||
| long absolutePosition = origin switch | ||
| { | ||
| SeekOrigin.Begin => offset, | ||
| SeekOrigin.Current => (_positionPastEnd >= 0 ? _positionPastEnd : _sequence.Slice(_sequence.Start, _position).Length) + offset, | ||
| SeekOrigin.End => Length + offset, | ||
| _ => throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)) | ||
| }; | ||
|
|
||
| // Negative positions are invalid | ||
| if (absolutePosition < 0) | ||
| { | ||
| throw new IOException(SR.IO_SeekBeforeBegin); | ||
| } | ||
|
|
||
| // Update position - seeking past end is allowed | ||
| if (absolutePosition >= Length) | ||
| { | ||
| _position = _sequence.End; | ||
| _positionPastEnd = absolutePosition; | ||
| } | ||
| else | ||
| { | ||
| _position = _sequence.GetPosition(absolutePosition, _sequence.Start); | ||
| _positionPastEnd = -1; | ||
| } | ||
|
|
||
| return absolutePosition; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void Flush() { } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void SetLength(long value) => throw new NotSupportedException(SR.NotSupported_UnwritableStream); | ||
|
|
||
| /// <inheritdoc /> | ||
| protected override void Dispose(bool disposing) | ||
| { | ||
| _isDisposed = true; | ||
| base.Dispose(disposing); | ||
| } | ||
| } | ||
| } | ||
46 changes: 46 additions & 0 deletions
46
src/libraries/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceStream.ConformanceTests.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,46 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| using System.IO; | ||
| using System.Buffers; | ||
| using System.IO.Tests; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.Memory.Tests | ||
| { | ||
| /// <summary> | ||
| /// Conformance tests for ReadOnlySequenceStream - a read-only, seekable stream | ||
| /// wrapper around ReadOnlySequence{byte}. | ||
| /// </summary> | ||
| public class ROSequenceStreamConformanceTests : StandaloneStreamConformanceTests | ||
|
ViveliDuCh marked this conversation as resolved.
|
||
| { | ||
| // StreamConformanceTests flags to specify capabilities | ||
| protected override bool CanSeek => true; | ||
| // SetLength() is not supported because ReadOnlySequence{byte} is immutable. | ||
| protected override bool CanSetLength => false; | ||
|
ViveliDuCh marked this conversation as resolved.
|
||
| // ReadOnlySequenceStream doesn't buffer writes (it's read-only), | ||
| protected override bool NopFlushCompletesSynchronously => true; | ||
|
|
||
| protected override Task<Stream?> CreateReadOnlyStreamCore(byte[]? initialData) | ||
| { | ||
| if (initialData == null || initialData.Length == 0) | ||
| { | ||
| // Create empty sequence for null or empty data | ||
| var emptySequence = ReadOnlySequence<byte>.Empty; | ||
| return Task.FromResult<Stream?>(new ReadOnlySequenceStream(emptySequence)); | ||
| } | ||
|
|
||
| // ReadOnlySequence<byte> can be constructed from: | ||
| // 1. ReadOnlyMemory<byte> (single segment) | ||
| // 2. ReadOnlySequenceSegment<byte> chain (multi-segment) | ||
| var sequence = new ReadOnlySequence<byte>(initialData); // Single segment | ||
| return Task.FromResult<Stream?>(new ReadOnlySequenceStream(sequence)); | ||
| } | ||
|
|
||
| // Immutable | ||
| protected override Task<Stream?> CreateWriteOnlyStreamCore(byte[]? initialData) => Task.FromResult<Stream?>(null); | ||
|
|
||
|
|
||
| // Immutable | ||
| protected override Task<Stream?> CreateReadWriteStreamCore(byte[]? initialData) => Task.FromResult<Stream?>(null); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
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.
Thanks for the catch! You're right, since _position is never read when
_positionPastEnd >= 0, the assignment is currently redundant. Although, it still feels like a safer fallback than leaving it stale (in case future code reads _position without checking first).