Operations on ReadOnlySequence<byte>

1.7k Views Asked by At

I am doing some experimenting with System.IO.Pipelines and can't work out the best way to convert or use the returned ReadOnlySequence objects.

The only way I have been able to do anything with it is to convert it to an array and then do normal byte functions, eg given the following:

        byte[] byteArray = new byte[]{ 0x01, 0x02, 0x03, 0x50, 0x99 };
        ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(byteArray);

Do operations on the Buffer:

        var theArray = buffer.ToArray();
        // perform normal byte array operations

Things I can't figure out how to do without converting to an Array:

        foreach(byte theByte in buffer)
            // do something with the byte

Testing a particular Byte in the buffer

        if(buffer[0] == 0x11)
            ...

Copying the byte buffer to a Struct

        Marshal.Copy(

Is the only way to access the contents of the ReadOnlySequence by turning it back into an array?

1

There are 1 best solutions below

2
On

You can foreach over the ReadOnlySequence like this:

foreach (var item in buffer)
{
    if (item.Span[0] == 0x01)
    {
        Console.WriteLine("hello");
    }
}