| | 1 | | // Copyright (c) 2020-2024 dotBunny Inc. |
| | 2 | | // dotBunny licenses this file to you under the BSL-1.0 license. |
| | 3 | | // See the LICENSE file in the project root for more information. |
| | 4 | |
|
| | 5 | | using System; |
| | 6 | |
|
| | 7 | | namespace GDX.Collections.Generic |
| | 8 | | { |
| | 9 | | #if UNITY_2021_2_OR_NEWER |
| | 10 | | public struct ExpandingArray<T> |
| | 11 | | { |
| | 12 | | T[] m_Array; |
| | 13 | | int m_Head; |
| | 14 | | int m_Size; |
| | 15 | |
|
| | 16 | | public ExpandingArray(int size) |
| 0 | 17 | | { |
| 0 | 18 | | m_Array = new T[size]; |
| 0 | 19 | | m_Head = 0; |
| 0 | 20 | | m_Size = size; |
| 0 | 21 | | } |
| | 22 | |
|
| | 23 | | public void Add(T item) |
| 0 | 24 | | { |
| 0 | 25 | | Ensure(1); |
| 0 | 26 | | m_Array[m_Head] = item; |
| 0 | 27 | | m_Head++; |
| 0 | 28 | | } |
| | 29 | |
|
| | 30 | | public void AddRange(T[] items) |
| 0 | 31 | | { |
| 0 | 32 | | int size = items.Length; |
| 0 | 33 | | Ensure(size); |
| 0 | 34 | | Array.Copy(items, 0, m_Array, m_Head, size); |
| 0 | 35 | | m_Head += size; |
| 0 | 36 | | } |
| | 37 | |
|
| | 38 | | public void AddRangeUnchecked(T[] items) |
| 0 | 39 | | { |
| 0 | 40 | | int size = items.Length; |
| 0 | 41 | | Array.Copy(items, 0, m_Array, m_Head, size); |
| 0 | 42 | | m_Head += size; |
| 0 | 43 | | } |
| | 44 | | public void AddUnchecked(T item) |
| 0 | 45 | | { |
| 0 | 46 | | m_Array[m_Head] = item; |
| 0 | 47 | | m_Head++; |
| 0 | 48 | | } |
| | 49 | |
|
| | 50 | | public void Clear() |
| 0 | 51 | | { |
| 0 | 52 | | for (int i = 0; i < m_Size; i++) |
| 0 | 53 | | { |
| 0 | 54 | | m_Array[i] = default; |
| 0 | 55 | | } |
| 0 | 56 | | m_Head = 0; |
| 0 | 57 | | } |
| | 58 | |
|
| | 59 | | void Ensure(int needed) |
| 0 | 60 | | { |
| 0 | 61 | | int space = m_Size - m_Head; |
| 0 | 62 | | if (space >= needed) |
| 0 | 63 | | { |
| 0 | 64 | | return; |
| | 65 | | } |
| | 66 | |
|
| 0 | 67 | | m_Size += needed; |
| 0 | 68 | | Array.Resize(ref m_Array, m_Size); |
| 0 | 69 | | } |
| | 70 | |
|
| | 71 | | public Span<T> GetSpan() |
| 0 | 72 | | { |
| 0 | 73 | | return new Span<T>(m_Array, 0, m_Head); |
| 0 | 74 | | } |
| | 75 | |
|
| | 76 | | public Span<T> GetSpan(int startIndex, int count) |
| 0 | 77 | | { |
| 0 | 78 | | return new Span<T>(m_Array, startIndex, count); |
| 0 | 79 | | } |
| | 80 | |
|
| | 81 | | public ReadOnlySpan<T> GetReadOnlySpan() |
| 0 | 82 | | { |
| 0 | 83 | | return new ReadOnlySpan<T>(m_Array, 0, m_Head); |
| 0 | 84 | | } |
| | 85 | |
|
| | 86 | | public ReadOnlySpan<T> GetReadOnlySpan(int startIndex, int count) |
| 0 | 87 | | { |
| 0 | 88 | | return new ReadOnlySpan<T>(m_Array, startIndex, count); |
| 0 | 89 | | } |
| | 90 | |
|
| | 91 | | public bool HasData() |
| 0 | 92 | | { |
| 0 | 93 | | return m_Head > 0; |
| 0 | 94 | | } |
| | 95 | |
|
| | 96 | | public void Reset() |
| 0 | 97 | | { |
| 0 | 98 | | m_Head = 0; |
| 0 | 99 | | } |
| | 100 | | } |
| | 101 | | #endif // UNITY_2021_2_OR_NEWER |
| | 102 | | } |