using System; using System.Buffers; using System.Diagnostics.CodeAnalysis; #if NET6_0_OR_GREATER using System.Numerics; #endif using System.Runtime.CompilerServices; #if !NET6_0_OR_GREATER using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations; #endif namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; /// internal static class ArrayPoolBinaryWriter { /// /// The default buffer size to use to expand empty arrays. /// public const int DefaultInitialBufferSize = 256; } /// /// Represents a heap-based, array-backed output sink into which data can be written. /// /// The type of values to write. internal ref struct ArrayPoolBufferWriter where T : unmanaged { /// /// The underlying array. /// private T[]? array; /// /// The starting offset within . /// private int index; /// /// Initializes a new instance of the class. /// public ArrayPoolBufferWriter(int capacity) { this.array = ArrayPool.Shared.Rent(capacity); this.index = 0; } /// /// Gets the data written to the underlying buffer so far, as a . /// [UnscopedRef] public readonly ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { T[]? array = this.array; if (array is null) { ArrayPoolBufferWriterHelpers.ThrowObjectDisposedException(); } return array.AsSpan(0, this.index); } } /// /// Advances the current writer. /// /// The amount to advance. /// /// Must be called after . /// This and the methods below are to enable mutating extensions. /// internal void Advance(int count) { T[]? array = this.array; if (array is null) { ArrayPoolBufferWriterHelpers.ThrowObjectDisposedException(); } if (count < 0) { ArrayPoolBufferWriterHelpers.ThrowArgumentOutOfRangeExceptionForNegativeCount(); } if (this.index > array.Length - count) { ArrayPoolBufferWriterHelpers.ThrowArgumentExceptionForAdvancedTooFar(); } this.index += count; } /// /// Gets a to write data to, with an optional minimum capacity. /// /// The capacity to request. /// A to write data to. [UnscopedRef] internal Span GetSpan(int sizeHint = 0) { CheckBufferAndEnsureCapacity(sizeHint); return this.array.AsSpan(this.index); } /// /// Ensures that has enough free space to contain a given number of new items. /// /// The minimum number of items to ensure space for in . [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBufferAndEnsureCapacity(int sizeHint) { T[]? array = this.array; if (array is null) { ArrayPoolBufferWriterHelpers.ThrowObjectDisposedException(); } if (sizeHint < 0) { ArrayPoolBufferWriterHelpers.ThrowArgumentOutOfRangeExceptionForNegativeSizeHint(); } if (sizeHint == 0) { sizeHint = 1; } if (sizeHint > array.Length - this.index) { ResizeBuffer(sizeHint); } } /// /// Resizes to ensure it can fit the specified number of new items. /// /// The minimum number of items to ensure space for in . [MethodImpl(MethodImplOptions.NoInlining)] private unsafe void ResizeBuffer(int sizeHint) { uint minimumSize = (uint)this.index + (uint)sizeHint; // The ArrayPool class has a maximum threshold of 1024 * 1024 for the maximum length of // pooled arrays, and once this is exceeded it will just allocate a new array every time // of exactly the requested size. In that case, we manually round up the requested size to // the nearest power of two, to ensure that repeated consecutive writes when the array in // use is bigger than that threshold don't end up causing a resize every single time. if (minimumSize > 1024 * 1024) { minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize); } T[] newArray = ArrayPool.Shared.Rent((int)minimumSize); Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index * sizeof(T)); ArrayPool.Shared.Return(this.array!); this.array = newArray; } /// public void Dispose() { T[]? array = this.array; if (array is null) { return; } this.array = null; ArrayPool.Shared.Return(array); } } /// /// Private helpers for . /// file static class ArrayPoolBufferWriterHelpers { /// /// Throws an when the requested count is negative. /// [DoesNotReturn] public static void ThrowArgumentOutOfRangeExceptionForNegativeCount() { throw new ArgumentOutOfRangeException("count", "The count can't be a negative value."); } /// /// Throws an when the size hint is negative. /// [DoesNotReturn] public static void ThrowArgumentOutOfRangeExceptionForNegativeSizeHint() { throw new ArgumentOutOfRangeException("sizeHint", "The size hint can't be a negative value."); } /// /// Throws an when the requested count is negative. /// [DoesNotReturn] public static void ThrowArgumentExceptionForAdvancedTooFar() { throw new ArgumentException("The buffer writer has advanced too far."); } /// /// Throws an when the array is . /// [DoesNotReturn] public static void ThrowObjectDisposedException() { throw new ObjectDisposedException("The current buffer has already been disposed."); } }