Skip to content

Instantly share code, notes, and snippets.

@in-async
Created October 5, 2023 10:07
Show Gist options
  • Save in-async/975178a16338b5efbacae4d0ffbba16a to your computer and use it in GitHub Desktop.
Save in-async/975178a16338b5efbacae4d0ffbba16a to your computer and use it in GitHub Desktop.
.NET 8 未満向け MemoryExtensions.Split もどき
public static class SpanSplitExtensions {
public static int Split<T>(this ReadOnlySpan<T> source, Span<Range> destination, T separator) where T: IEquatable<T> {
return Split(source, destination, new ReadOnlySpan<T>(separator));
}
public static int Split<T>(this ReadOnlySpan<T> source, Span<Range> destination, ReadOnlySpan<T> separator) where T: IEquatable<T> {
int rangesWritten = 0;
int offset = 0;
foreach (ref Range dest in destination) {
if (rangesWritten + 1 == destination.Length) {
dest = offset..;
rangesWritten++;
break;
}
int idx = source[offset..].IndexOf(separator);
if (idx < 0) {
dest = offset..;
rangesWritten++;
break;
}
dest = offset..(offset + idx);
rangesWritten++;
offset += idx + 1;
}
return rangesWritten;
}
}
ReadOnlySpan<char> payload = "a::bc:def";
Span<Range> ranges = stackalloc Range[3];
int rangesWritten = payload.Split(ranges, ':').Dump();
foreach (Range range in ranges[..rangesWritten]) {
payload[range].ToString().Dump();
}
// 3
// a
//
// bc:def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment