Skip to content

[API Proposal]: Expose span on SpanSplitEnumerator #109874

@JeremyKuhne

Description

@JeremyKuhne

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 partial struct SpanSplitEnumerator<T>
{
   public ReadOnlySpan<T> Span;
}

The current API, for context:

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

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.

Metadata

Metadata

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Memoryin-prThere is an active PR which will close this issue when it is merged

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions