using System; using System.Buffers; namespace Duplicati.Proprietary.DiskImage.Disk; /// /// A disposable struct that rents a byte array from the shared ArrayPool and returns it when disposed. /// This eliminates GC pressure from repeated large byte[] allocations, especially for buffers >= 85 KB /// which would otherwise land on the Large Object Heap and cause Gen2 GC pauses. /// internal readonly struct PooledBuffer : IDisposable { private readonly byte[] _array; /// /// Gets the actual length of data requested (may be less than the array length). /// public readonly int Length; /// /// Gets the underlying array. Note: the array may be larger than . /// Always use Length when accessing data, not _array.Length. /// public byte[] Array => _array; /// /// Gets a Memory view of the buffer sized to the requested length. /// public Memory Memory => _array.AsMemory(0, Length); /// /// Gets a Span view of the buffer sized to the requested length. /// public Span Span => _array.AsSpan(0, Length); /// /// Rents a buffer from the shared ArrayPool. /// /// The minimum size of the buffer needed. public PooledBuffer(int size) { _array = ArrayPool.Shared.Rent(size); Length = size; } /// /// Returns the buffer to the shared ArrayPool. /// public void Dispose() { ArrayPool.Shared.Return(_array); } }