I want to check does a Span<T> contains a Span<T> elements in the same order.
Span<byte> buffer = stackalloc byte[] { 1, 6, 2, 5, 3, 4 };
Span<byte> needle1 = stackalloc byte[] { 2, 5, 3 }; // this one is contained in buffer in the same order
Span<byte> needle2 = stackalloc byte[] { 2, 5, 4 }; // this one is not contained in buffer in the same order
I’m aware I can use Span<T>.Contains() that takes only one element as parameter to find the first element of needle in the buffer and then manually compare next elements one by one, but this seems highly suboptimal and tedious process.
Span<T>.Overlaps() is not the answer here, because needle is not stored in the same memory address as buffer. I’d like to avoid LINQ, because of performance reasons. Is there additional method in the standard library I am missing?
>Solution :
You can use MemoryExtensions.IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value):
Searches for the specified sequence and returns the index of its first occurrence. Values are compared using
IEquatable{T}.Equals(T).
Returns
Int32
The index of the occurrence of thevaluein thespan. If not found, returns -1.
var contains1 = buffer.IndexOf(needle1) >= 0;
var contains2 = buffer.IndexOf(needle2) >= 0;