dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.36k stars 4.75k forks source link

[API Proposal]: Expose span on SpanSplitEnumerator #109874

Open JeremyKuhne opened 1 day ago

JeremyKuhne commented 1 day ago

Background and motivation

Exposing it would allow writing extension methods on it, so one could do something like Split('\0').ToArray().

// Not possible to write currently
public static T[] ToArray<T>(this MemoryExtensions.SpanSplitEnumerator<T> enumerator) where T : IEquatable<T>

934 #104534

API Proposal

public ref struct SpanSplitEnumerator<T>
{
    public SpanSplitEnumerator<T> GetEnumerator();
    public bool MoveNext();
    public Range Current { get; }
+   public ReadOnlySpan<T> Span;
}

API Usage

// This is a common pattern in Win32
public static string[] SplitStringList(this ReadOnlySpan<char> strings)
    => strings.Split('\0').ToArray();

// Usable by above and any other code that needs to convert to an array
public static T[] ToArray<T>(this MemoryExtensions.SpanSplitEnumerator<T> enumerator) where T : IEquatable<T>
// ... implementation that grabs the ranges and creates the appropriately sized array if needed

Alternative Designs

Could possibly expose range related methods so one could do something like enumerator[enumerator.Current]?

Risks

None known.

dotnet-policy-service[bot] commented 1 day ago

Tagging subscribers to this area: @dotnet/area-system-memory See info in area-owners.md if you want to be subscribed.