'Advice neaed: a best way to write binary data to pipe

I need a way to write data with minimum allocations, as it possible when read from ReadOnlySequence.

A best way that I found is SpanWriter from side library.

But probably some one knows a better standard solution.

using System.IO.Pipelines

namespace WriteSample
{
    public async Task Write()
    {
        var pipe = new Pipe();

        var memory = pipe.Writer.GetMemory(2048);
        
        var writer = new Writer???(memory.Span);

        writer.Write((byte)0xFF);
        writer.Write((long)12345);
        writer.WriteBigEndian((long)12345);

        await pipe.Writer.FlushAsync()

    }
}


Solution 1:[1]

The way provided by the runtime is using BinaryPrimitives:

var span = memory.Span;
span[0] = 0xFF;
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(1), 12345);
BinaryPrimitives.WriteInt64BigEndian(span.Slice(9), 12345);

This does have the disadvantage of meaning you need to keep track of where in the span you've written to so far, unlike e.g. BinaryWriter. I don't know of any types in the runtime to help with this, so you'll probably have to write your own, if you care.

Something like:

public ref struct SpanWriter
{
    private Span<byte> span;    
    public SpanWriter(Span<byte> span) => this.span = span;
    
    public void WriteInt64BigEndian(long value)
    {
        BinaryPrimitives.WriteInt64BigEndian(span, value);
        span = span.Slice(8);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1