csharp/71/Cometary/src/Cometary.Core/Internal/LightList.cs

LightList.cs
using System;
using System.Collections;
using System.Collections.Generic;

namespace Cometary
{
    /// 
    ///   Represents a lightweight array with the ability to
    ///   add values, and clear all values.
    /// 
    internal sealed clast LightList : IList, IReadOnlyList
    {
        private T[] underlyingArray = new T[0];

        public T this[int index]
        {
            get => underlyingArray[index];
            set => underlyingArray[index] = value;
        }

        T IList.this[int index]
        {
            get => underlyingArray[index];
            set => underlyingArray[index] = value;
        }

        /// 
        ///   Gets the underlying array in which items are stored.
        /// 
        public T[] UnderlyingArray => underlyingArray;

        /// 
        public int Count => ((IReadOnlyList)this.UnderlyingArray).Count;

        /// 
        public bool IsReadOnly => false;

        /// 
        public void Add(T item)
        {
            T[] array = underlyingArray;
            int newSize = array.Length + 1;

            T[] newArray = new T[newSize--];
            Array.Copy(array, 0, newArray, 0, newSize);
            newArray[newSize] = item;

            underlyingArray = newArray;
        }

        /// 
        public void Clear() => underlyingArray = new T[0];

        /// 
        public bool Contains(T item) => Array.IndexOf(underlyingArray, item) != -1;

        /// 
        public void CopyTo(T[] array, int arrayIndex) => underlyingArray.CopyTo(array, arrayIndex);

        /// 
        public int IndexOf(T item) => Array.IndexOf(underlyingArray, item);

        /// 
        public void Insert(int index, T item) => throw new NotSupportedException();

        /// 
        public bool Remove(T item)
        {
            int index = Array.IndexOf(underlyingArray, item);

            if (index == -1)
                return false;

            RemoveAt(ref underlyingArray, index);

            return true;
        }

        /// 
        public void RemoveAt(int index)
        {
            if (index < Count)
                RemoveAt(ref underlyingArray, index);
        }

        private static void RemoveAt(ref T[] array, int index)
        {
            int newSize = array.Length - 1;

            T[] newArray = new T[newSize];
            Array.Copy(array, 0, newArray, 0, index);
            Array.Copy(array, index, newArray, index, newSize - index);
        }

        /// 
        public IEnumerator GetEnumerator() => ((IList)UnderlyingArray).GetEnumerator();

        /// 
        IEnumerator IEnumerable.GetEnumerator() => UnderlyingArray.GetEnumerator();

        public T[] ToArray() => underlyingArray;
    }
}