-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ImmutableArray<T>.Builder.AsSpan #43760
Comments
Tagging subscribers to this area: @eiriktsarpalis, @jeffhandley |
There is a similar (internal) API |
Related to #21727. I feel the concerns raised there also apply here. And given that immutable builders are niche compared to |
To give some context here, I wanted to use this in Roslyn's |
I think the main concern is that any modification to the builder after AsSpan call would be unsafe. Is there any "unsafe" way to get the span then? so that if someone is aware of the consequence at least they could save a copy |
I recall there was some discussion to have methods like this declared in It could be considered further if the Caller-Must-Be-Unsafe analyzer (#31354) gets done and shipped, so that anyone who wants to call this method knows that the rules of an |
This api will be unsound:
|
I think if we empty the original array just like MoveToImmutable all concerns are addressed. It is a MoveToImmutable but without Might as well rename to MoveToSpan? public ReadOnlySpan<T> MoveToSpan()
{
T[] temp = _elements;
_elements = ImmutableArray<T>.Empty.array!;
_count = 0;
return new ReadOnlySpan<T>(temp, 0, Count);
} |
But |
It seems wasteful to make a builder just for span. They use the same underlying type: array. So to me it makes sense to have a helper like that. This is more important now that MoveToImmutable requires the same Capacity as Count. That's a huge limitation when you want to avoid the copy. |
Yes, it is wasteful to make a |
I think it would make more sense for a CollectionsMarshal overload as @Joe4evr suggested: namespace System.Runtime.InteropServices
{
public static class CollectionsMarshal
{
public static Span<T> AsSpan<T>(ImmutableArray<T>.Builder builder);
}
} I withdraw this proposal. |
Background and Motivation
Before calling
ToImmutable
and making a copy, you may want to access the inner array as a Span. UnlikeMoveToImmutable
which also doesn't incur a copy, this does not requireCount == Capacity
asAsSpan
can only expose elements up toCount
.Proposed API
namespace System.Collections.Immutable { public partial struct ImmutableArray<T> { public sealed class Builder { + public Span<T> AsSpan(); } } }
The implementation is straightforward:
We may want to add a similar member to other builders as well.
The text was updated successfully, but these errors were encountered: