Skip to content

Provide a way to get a PipeReader from a ReadOnlySequence<byte> #47990

@Alxandr

Description

@Alxandr

Background and Motivation

Sometimes you have data available in memory (either already downloaded or read from file or generated by your process), represented as a ReadOnlySequence<byte> (which may or may not be a single contiguous Span<byte>), and you need to feed that into an API that expects a PipeReader. This is basically the same usecase as a MemoryStream over a byte[], except it's in the new APIs of Pipes and ReadOnlySequence<byte>s. The exact signature for this API isn't too terribly important (wether it's an extension method on ReadOnlySequence<byte>, an overload of PipeReader.Create or new MemoryPipeReader(sequence)), since this template requires a proposed API, I will be writing the static Create, as that is closest to what exist for Stream.

Proposed API

namespace System.IO.Pipelines
{
    public abstract class PipeReader
    {
+       public static PipeReader Create(ReadOnlySequence<byte> sequence);

Usage Examples

var data = GenerateDataAsSequence();
var obj = await DeserializeAsync(PipeReader.Create(data));

Alternative Designs

Using the package Nerdbank.Streams, it's possible to achieve a similar result going through a Stream;

var data = GenerateDataAsSequence();
var obj = await DeserializeAsync(PipeReader.Create(data.AsStream()));

Alternatively, the fake "generate" method here needs to be rewritten to take a writer:

var pipe = new Pipe();
var task = GenerateDataIntoPipe(pipe.Writer);
var obj = await DeserializeAsync(pipe.Reader);
await task;

While this is probably the better solution in many cases, you don't always have access to rewrite the APIs that generate the data.

Risks

The only risk I can see is an expanded API surface area to teach/maintain.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions