| | | 1 | | using System; |
| | | 2 | | using System.Buffers; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Runtime.CompilerServices; |
| | | 5 | | using UnityEngine.Assertions; |
| | | 6 | | |
| | | 7 | | namespace Hertzole.ScriptableValues |
| | | 8 | | { |
| | | 9 | | // Basically coped from https://github.com/CommunityToolkit/dotnet/blob/657c6971a8d42655c648336b781639ed96c2c49f/src |
| | | 10 | | internal readonly ref struct SpanOwner<T> |
| | | 11 | | { |
| | | 12 | | private readonly ArrayPool<T> pool; |
| | | 13 | | private readonly T[] array; |
| | | 14 | | |
| | | 15 | | public Span<T> Span |
| | | 16 | | { |
| | | 17 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 360 | 18 | | get { return new Span<T>(array, 0, Length); } |
| | | 19 | | } |
| | | 20 | | |
| | | 21 | | public int Length |
| | | 22 | | { |
| | 120 | 23 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 24 | | get; |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | public static SpanOwner<T> Empty |
| | | 28 | | { |
| | | 29 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 0 | 30 | | get { return new SpanOwner<T>(0, ArrayPool<T>.Shared); } |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | private SpanOwner(int length, ArrayPool<T> pool) |
| | 90 | 34 | | { |
| | 90 | 35 | | Length = length; |
| | 90 | 36 | | this.pool = pool; |
| | 90 | 37 | | array = pool.Rent(length); |
| | | 38 | | |
| | 90 | 39 | | if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) |
| | 0 | 40 | | { |
| | 0 | 41 | | array.AsSpan(0, length).Clear(); |
| | 0 | 42 | | } |
| | 90 | 43 | | } |
| | | 44 | | |
| | | 45 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 46 | | public void CopyFrom(ICollection<T> collection) |
| | 0 | 47 | | { |
| | 0 | 48 | | Assert.IsTrue(collection.Count <= Length, "The collection is larger than the allocated array."); |
| | | 49 | | |
| | 0 | 50 | | collection.CopyTo(array, 0); |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 54 | | public static SpanOwner<T> Allocate(int size) |
| | 90 | 55 | | { |
| | 90 | 56 | | return new SpanOwner<T>(size, ArrayPool<T>.Shared); |
| | 90 | 57 | | } |
| | | 58 | | |
| | | 59 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 60 | | public void Dispose() |
| | 90 | 61 | | { |
| | 90 | 62 | | pool.Return(array); |
| | 90 | 63 | | } |
| | | 64 | | } |
| | | 65 | | } |