As I've gotten more familiar with ReadOnlySpan<T> and friends, I've really come to wonder why there is no overload of Slice() that accepts a Range. Specifically when one is using ReadOnlySpan<T>.Split(...), one ends up with a set of Range instances, and from there, it is (in my opinion) clunky to turn the Range instances into something more useful. For example:
// make a span
var myInput = "ab,cd,ef".AsSpan();
// set up a span to hold the ranges from the Split() call
Span<Range> splitRanges = stackalloc Range[3];
// split the span based on commas
myInput.Split(splitRanges, ',');
// get the offset and length of the first range
var (offset, length) = splitRanges[0].GetOffsetAndLength(myInput.Length);
// slice the original span based on the first range's values
var firstSpan = myInput.Slice(offset, length);
Am I missing something? Is there a more concise, or even more idiomatic way to accomplish this?
Because you can already use a Range to access a ReadOnlySpan<T> just like you would with a Span<T>, a string, or an array:
var firstSpan = myInput[splitRanges[0]];
It's not documented as such, because it uses the "implicit range support" feature, which, in short, will turn that into a call to Slice. So adding a Slice overload that takes a Range would have been redundant.
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