DynamicArray.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. namespace UnityEngine.Rendering
  3. {
  4. /// <summary>
  5. /// Generic growable array.
  6. /// </summary>
  7. /// <typeparam name="T">Type of the array.</typeparam>
  8. public class DynamicArray<T> where T: new()
  9. {
  10. T[] m_Array = null;
  11. /// <summary>
  12. /// Number of elements in the array.
  13. /// </summary>
  14. public int size { get; private set; }
  15. /// <summary>
  16. /// Constructor.
  17. /// Defaults to a size of 32 elements.
  18. /// </summary>
  19. public DynamicArray()
  20. {
  21. m_Array = new T[32];
  22. size = 32;
  23. }
  24. /// <summary>
  25. /// Constructor
  26. /// </summary>
  27. /// <param name="size">Number of elements.</param>
  28. public DynamicArray(int size)
  29. {
  30. m_Array = new T[size];
  31. this.size = size;
  32. }
  33. /// <summary>
  34. /// Clear the array of all elements.
  35. /// </summary>
  36. public void Clear()
  37. {
  38. size = 0;
  39. }
  40. /// <summary>
  41. /// Add an element to the array.
  42. /// </summary>
  43. /// <param name="value">Element to add to the array.</param>
  44. /// <returns>The index of the element.</returns>
  45. public int Add(in T value)
  46. {
  47. int index = size;
  48. // Grow array if needed;
  49. if (index >= m_Array.Length)
  50. {
  51. var newArray = new T[m_Array.Length * 2];
  52. Array.Copy(m_Array, newArray, m_Array.Length);
  53. m_Array = newArray;
  54. }
  55. m_Array[index] = value;
  56. size++;
  57. return index;
  58. }
  59. /// <summary>
  60. /// Resize the Dynamic Array.
  61. /// This will reallocate memory if necessary and set the current size of the array to the provided size.
  62. /// </summary>
  63. /// <param name="newSize">New size for the array.</param>
  64. /// <param name="keepContent">Set to true if you want the current content of the array to be kept.</param>
  65. public void Resize(int newSize, bool keepContent = false)
  66. {
  67. if (newSize > m_Array.Length)
  68. {
  69. if (keepContent)
  70. {
  71. var newArray = new T[newSize];
  72. Array.Copy(m_Array, newArray, m_Array.Length);
  73. m_Array = newArray;
  74. }
  75. else
  76. {
  77. m_Array = new T[newSize];
  78. }
  79. }
  80. size = newSize;
  81. }
  82. /// <summary>
  83. /// ref access to an element.
  84. /// </summary>
  85. /// <param name="index">Element index</param>
  86. /// <returns>The requested element.</returns>
  87. public ref T this[int index]
  88. {
  89. get
  90. {
  91. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  92. if (index >= size)
  93. throw new IndexOutOfRangeException();
  94. #endif
  95. return ref m_Array[index];
  96. }
  97. }
  98. }
  99. }