Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if two Span<T> intersect?

Tags:

c#

Consider the following function:

public static bool TryToDoStuff(ReadOnlySpan<byte> input, Span<byte> destination) {
    ...
}

This function returns whether it was able to "do stuff" on destination based on input's content.

I'd like to check if the memory regions "wrapped" by input and destination intersect, and if so, throw an exception, since this would corrupt input's data. How can I do that (without reflection or unsafe code)?

I know I could write some xmldoc and warn the users that the parameters should not intersect, but that's a poor man's solution.

Edit: for those asking for examples, Wazner's examples are on point.

// On arrays
Span<byte> firstArray = new byte[10];
Span<byte> secondArray = new byte[10];
Intersects<byte>(firstArray.Slice(5, 5), firstArray.Slice(3, 5)); // Should throw
Intersects<byte>(firstArray.Slice(5, 5), secondArray.Slice(3, 5)); // Should not throw

// And on stackallocated memory
Span<byte> firstStack = stackalloc byte[10];
Span<byte> secondStack = stackalloc byte[10];
Intersects<byte>(firstStack.Slice(5, 5), firstStack.Slice(3, 5)); // Should throw
Intersects<byte>(firstStack.Slice(5, 5), secondStack.Slice(3, 5)); // Should not throw
like image 689
Trauer Avatar asked Aug 21 '18 03:08

Trauer


1 Answers

I created an issue on dotnet/corefx repository and one of the contributors posted this link:

https://docs.microsoft.com/en-us/dotnet/api/system.memoryextensions.overlaps?view=netcore-2.1

So yeah, there is a elegant, concise, safe and within-framework solution to this problem.

like image 86
Trauer Avatar answered Sep 20 '22 18:09

Trauer