using System; using System.Buffers; using System.Diagnostics.CodeAnalysis; #if NET6_0_OR_GREATER using System.Numerics; #endif using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; #if !NET6_0_OR_GREATER using ComputeSharp.D2D1.NetStandard.System.Text; using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations; #endif namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; /// /// Represents a heap-based, array-backed output sink into which binary data can be written. /// internal ref struct ArrayPoolBinaryWriter { /// /// The default buffer size to use to expand empty arrays. /// public const int DefaultInitialBufferSize = 256; /// /// The underlying array. /// private byte[]? array; /// /// The starting offset within . /// private int index; /// /// Initializes a new instance of the class. /// public ArrayPoolBinaryWriter(int capacity) { this.array = ArrayPool.Shared.Rent(capacity); this.index = 0; } /// /// Gets the data written to the underlying buffer so far, as a . /// public ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { byte[]? array = this.array; if (array is null) { ThrowObjectDisposedException(); } return array.AsSpan(0, this.index); } } /// /// Writes a value of type into the buffer. /// /// The type of value to write. /// The value to write. public unsafe void Write(in T value) where T : unmanaged { Span span = GetSpan(sizeof(T)); MemoryMarshal.Write(span, ref Unsafe.AsRef(in value)); Advance(sizeof(T)); } /// /// Writes text as UTF8 bytes into the buffer. /// /// The text to write. public unsafe void WriteAsUtf8(string text) { int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length); Span span = GetSpan(maximumByteSize); int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span); Advance(writtenBytes); } /// /// Advances the current writer. /// /// The amount to advance. /// Must be called after . private void Advance(int count) { byte[]? array = this.array; if (array is null) { ThrowObjectDisposedException(); } if (count < 0) { ThrowArgumentOutOfRangeExceptionForNegativeCount(); } if (this.index > array.Length - count) { ThrowArgumentExceptionForAdvancedTooFar(); } this.index += count; } /// /// Gets a to write data to, with an optional minimum capacity. /// /// The capacity to request. /// A to write data to. private 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) { byte[]? array = this.array; if (array is null) { ThrowObjectDisposedException(); } if (sizeHint < 0) { 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 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); } byte[] newArray = ArrayPool.Shared.Rent((int)minimumSize); Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index); ArrayPool.Shared.Return(this.array!); this.array = newArray; } /// public void Dispose() { byte[]? array = this.array; if (array is null) { return; } this.array = null; ArrayPool.Shared.Return(array); } /// /// Throws an when the requested count is negative. /// [DoesNotReturn] private static void ThrowArgumentOutOfRangeExceptionForNegativeCount() { throw new ArgumentOutOfRangeException("count", "The count can't be a negative value."); } /// /// Throws an when the size hint is negative. /// [DoesNotReturn] private 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] private static void ThrowArgumentExceptionForAdvancedTooFar() { throw new ArgumentException("The buffer writer has advanced too far."); } /// /// Throws an when is . /// [DoesNotReturn] private static void ThrowObjectDisposedException() { throw new ObjectDisposedException("The current buffer has already been disposed."); } }