Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does ReadOnlySpan<T> not have an overload for Slice(…) that accepts a Range instance?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading