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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With