CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.99k stars 294 forks source link

Add ArrayPoolBufferWriter<T>.DangerousGetArray() API #615

Closed Sergio0694 closed 1 year ago

Sergio0694 commented 1 year ago

Overview

Related to #614. The ArrayPoolBufferWriter<T> lacks the DangerousGetArray() API which MemoryOwner<T> and SpanOwner<T> have. We should add it there too to make it easier and clearer how to get the underlying array from a writer.

API breakdown

namespace CommunityToolkit.HighPerformance.Buffers;

public sealed class ArrayPoolBufferWriter<T> : IBuffer<T>, IMemoryOwner<T>
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public ArraySegment<T> DangerousGetArray();
}

Usage example

ArraySegment<byte> segment = bufferWriter.DangerousGetArray();

stream.Write(segment.Array!, segment.Offset, segment.Count);

Breaking change?

No

Alternatives

Use MemoryMarshal.TryGetArray. That's less clear and less discoverable, so not ideal.