Find position of Span<T> in an array
Asked Answered
B

0

6

Span points to a memory area. Given that I know what memory area it is (i.e. array), can I (efficiently) figure out what first element in the array it is pointing to? I figured since it is pointing to non-pinned memory this information has to be stored somewhere, as address has to be updated by GC.

var buffer = new byte[100];
var span = new Span<byte>(buffer);
span = span.Slice(10, 5);
// How can I figure out where in buffer this span starts?
Bickel answered 28/4, 2020 at 12:31 Comment(3)
Maybe using IndexOf method from MemoryExtensions?Haggerty
No, IndexOf is for searching for content. Span can be 1 byte and buffer can be 100 MB, so the information from IndexOf would not tell me anything useful. I could use IndexOf and index all hits, change first value of span and check all the hits for the one that changed. But this is a bit inefficient way of doing it, and defeats the whole purpose of Span<T>. :PBickel
int elementOffsetOf<T>(Span<T> span, T[] array) => (int) Unsafe.ByteOffset(ref array[0], ref span[0]) / Unsafe.SizeOf<T>() would do it (this could potentially become an (internal!) extension method of T[]). I'm not sure there's not a more elegant way. Note that this produces garbage if you don't pass a span that actually points to an element of array; making sure this is the case is your own responsibility, though checks could be added (at some cost).Coelom

© 2022 - 2024 — McMap. All rights reserved.