Created
October 5, 2023 10:07
-
-
Save in-async/975178a16338b5efbacae4d0ffbba16a to your computer and use it in GitHub Desktop.
.NET 8 未満向け MemoryExtensions.Split もどき
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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