using System; using System.Collections.Generic; namespace TestPooling.DirtyList { using System.Collections; [Serializable] public class DirtyList : IList, IReadOnlyList { private readonly List data; private int topIndex; public DirtyList(int capacity = 0) { data = new List(capacity); } public IEnumerator GetEnumerator() { return data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(T item) { if (topIndex == data.Count) { data.Add(item); } else { data[topIndex] = item; } topIndex++; } public void AddRange(IEnumerable items) { foreach (var item in items) { Add(item); } } public void RemoveRange(IEnumerable items) { foreach (var item in items) { Remove(item); } } public void Clear() { topIndex = 0; } public bool Contains(T item) { if (item == null) { for (int i = 0; i < topIndex; i++) if (data[i] == null) return true; return false; } else { var c = EqualityComparer.Default; for (int i = 0; i < topIndex; i++) { if (c.Equals(data[i], item)) return true; } return false; } } public void CopyTo(T[] array, int arrayIndex) { data.CopyTo(0, array, arrayIndex, topIndex); } public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); topIndex--; return true; } return false; } int ICollection.Count { get { return topIndex == 0 ? 0 : topIndex - 1; } } public bool IsReadOnly { get { return ((ICollection)data).IsReadOnly; } } public int IndexOf(T item) { for (var i = 0; i < topIndex; i++) { if (data.Equals(data[i])) return i; } return -1; } public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)topIndex) { throw new ArgumentOutOfRangeException("index"); } data.Insert(index, item); } public void RemoveAt(int index) { if ((uint)index > (uint)topIndex) { throw new ArgumentOutOfRangeException("index"); } data.RemoveAt(index); topIndex--; } T IList.this[int index] { get { if ((uint)index > (uint)topIndex) { throw new ArgumentOutOfRangeException("index"); } return data[index]; } set { if ((uint)index > (uint)topIndex) { throw new ArgumentOutOfRangeException("index"); } data[index] = value; } } int IReadOnlyCollection.Count { get { return topIndex < 0 ? 0 : topIndex; } } T IReadOnlyList.this[int index] { get { if ((uint)index > (uint)topIndex) { throw new ArgumentOutOfRangeException("index"); } return data[index]; } } } }