using System;

namespace Quik.VertexGenerator
{
    /// <summary>
    /// A small list which whose items can be used by reference.
    /// </summary>
    /// <typeparam name="T">Container type.</typeparam>
    public class RefList<T>
    {
        private T[] _array = Array.Empty<T>();
        private int _count = 0;

        public T[] InternalArray => _array;

        public ref T this[int index] => ref _array[index];

        public int Count => _count;

        public int Capacity => _array.Length;

        public void Add(in T item)
        {
            EnsureCapacity(Count + 1);
            this[_count++] = item;
        }

        public void Add(T item)
        {
            EnsureCapacity(Count + 1);
            this[_count++] = item;
        }

        public void Clear()
        {
            Array.Resize(ref _array, 0);
            _count = 0;
        }

        private void EnsureCapacity(int needed)
        {
            while (_array.Length < needed)
            {
                Array.Resize(ref _array, Math.Max(1, _array.Length) * 2);
            }
        }
    }
}