How to use Span<T> and Memory<T>

https://antao-almada.medium.com/how-to-use-span-t-and-memory-t-c0b126aae652
 avatar
KyryloKuzyk
csharp
2 years ago
902 B
4
Indexable
public long Sum()
{
    var itemSize = UnsafeUtility.SizeOf<Foo>();

    Span<Foo> buffer = new Foo[100]; // alloc items buffer
    var rawBuffer = MemoryMarshal.Cast<Foo, byte>(buffer); // cast items buffer to bytes buffer (no copies)

    var bytesRead = stream.Read(rawBuffer);
    var sum = 0L;
    while (bytesRead > 0)
    {
        int remainder = bytesRead % itemSize;
        for (int i = 0; i < remainder; i++) // read the remaining bytes of the Foo struct till the end 
        { 
            int b = stream.ReadByte();
            if (b == -1)
                break;
            rawBuffer[i] = (byte)b;
        }
        bytesRead += remainder;
        
        var itemsRead = bytesRead / itemSize;
        foreach (var foo in buffer.Slice(0, itemsRead)) // iterate through the item buffer
            sum += foo.Integer;
        bytesRead = stream.Read(rawBuffer);
    }
    return sum;
}
Editor is loading...
Leave a Comment