using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace View_by_Distance.ThumbHash.Models; internal readonly ref struct SpanOwner { private static ArrayPool DefaultPool { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ArrayPool.Shared; } private readonly T[] _Buffer; private readonly int _Length; public static SpanOwner Empty { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new(0); } public Span Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { ref T r0 = ref MemoryMarshal.GetArrayDataReference(_Buffer); return MemoryMarshal.CreateSpan(ref r0, _Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public SpanOwner WithLength(int length) => new(length, _Buffer); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SpanOwner(int length) : this(length, DefaultPool.Rent(length)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SpanOwner(int length, T[] buffer) { _Length = length; _Buffer = buffer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() => DefaultPool.Return(_Buffer); }