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
934 B
7
Indexable
public long Sum() {
    int itemSize = UnsafeUtility.SizeOf<Foo>();
    Span<Foo> buffer = new Foo[100]; // alloc items buffer
    Span<byte> rawBuffer = MemoryMarshal.Cast<Foo, byte>(buffer); // cast items buffer to bytes buffer (no copies)
    long sum = 0L;
    while (true) {
        int bytesRead = stream.Read(rawBuffer);
        if (bytesRead == 0) {
            break;
        }
        int remainder = bytesRead % itemSize;
        if (remainder != 0) {
            // read the remaining bytes of the Foo struct till the end
            for (int i = 1; i <= remainder; i++) {
                int b = stream.ReadByte();
                Assert.AreNotEqual(-1, b);
                rawBuffer[i] = (byte)b;
            }
            bytesRead += remainder;
        }
        int itemsRead = bytesRead / itemSize;
        for (int i = 0; i < itemsRead; i++) {
            sum += buffer[i].Integer;
        }
    }
    return sum;
}
Editor is loading...
Leave a Comment