Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Growing a Span<T>, assuming underlying array has enough capacity

Tags:

c#

Assume we have a span which points to a sub-range of an array.

Is there any way to grow this span, assuming the initial underlying array has enough capacity to do so? (Assuming we can't use

Example:

int[] array = new int[]{4, 17, 0, 2, 3, 16, 1};
var span = new Span<int>(array);

var s1 = span.Slice(0, 1);
// Assume we can't use "array" directly here anymore, but only s1
var s2 = s1.Slice(0, 2); // bang! Argument of ouf range exception, even though array would have enough capacity
like image 419
Bogey Avatar asked Jun 08 '26 10:06

Bogey


1 Answers

Not safely -- the Span doesn't know how large the underlying array is.


One unsafe option is to use MemoryMarshal:

var s2 = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(s1), 7);

We use GetReference to get a ref int variable which points to the first element in the array, and pass that to CreateSpan with an explicit length.

You can write to arbitrary memory if you get the length wrong, so be careful!


There might be a way to try and get the original array back out of the Span, and then query its length, but I can't find one. MemoryMarshal.TryGetArray takes a Memory, not a Span.

like image 76
canton7 Avatar answered Jun 10 '26 19:06

canton7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!