Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently write ReadOnlySequence to Stream

Reading data using a PipeReader returns a ReadResult containing the requested data as a ReadOnlySequence<byte>. Currently I am using this (simplified) snippet to write the data fetched from the reader to my target stream:

var data = (await pipeReader.ReadAsync(cancellationToken)).Buffer;

// lots of parsing, advancing, etc.

var position = data.GetPosition(0);

while (data.TryGet(ref position, out var memory))
{
    await body.WriteAsync(memory);
}

This seems to be a lot of code for such a basic task, which I would usually expect to be a one-liner in .NET. Analyzing the overloads provided by Stream I fail to see how this functionality can be achieved with less code.

Is there some kind of extension method I am missing?

like image 411
Gene Avatar asked Feb 05 '26 18:02

Gene


1 Answers

Looks like what you are looking for is planned for .NET 7:

Stream wrappers for more types. Developers have asked for the ability to create a Stream around the contents of a ReadOnlyMemory, a ReadOnlySequence...

Not the greatest answer, but at least you can stop worrying that you are missing something obvious.

like image 75
edo.n Avatar answered Feb 07 '26 09:02

edo.n