How should I create an ImmutableArray from a Span/ReadOnlySpan?

Viewed 298

Suppose I have a method like the following:

unsafe void Convert(byte* ptr, int length)
{
    var span = new Span<byte>(ptr, length);
    var arr = ImmutableArray.CreateRange(span); // error: cannot convert from 'System.Span<byte>' to 'System.Collections.Generic.IEnumerable<byte>'
    Use(arr);
}

The CreateRange method in the above sample is the CreateRange<T>(IEnumerable<T>) overload. Since Span doesn't implement any interfaces it makes sense that we can't make this call. But I am actually a bit stumped as to what to do instead. Is there some idiomatic way to create an ImmutableArray from a Span with minimal copying/allocation? (i.e. using Span<T>.ToArray() and then ImmutableArray<T>.ToImmutableArray() would not be ideal)

Would also appreciate any suggestions that involve using the pointer+length directly in some way.

1 Answers

There is an open issue (as of June 2021) discussing adding APIs for this.

Until then, the issue suggests using a builder like this:

static ImmutableArray<T> ImmutableArrayFromSpan<T>(ReadOnlySpan<T> span)
{
    var builder = ImmutableArray.CreateBuilder<T>(span.Length);
    foreach (var i in span) {
        builder.Add(i);
    }
    return builder.MoveToImmutable();
}
Related