75 lines
1.7 KiB
C#
75 lines
1.7 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Engine.Core;
|
|
|
|
public class FastList<T> : IReadOnlyList<T>, IEnumerable<T> where T : notnull
|
|
{
|
|
private readonly List<T> items = [];
|
|
private readonly Dictionary<T, int> indexMap = [];
|
|
|
|
public int Count => items.Count;
|
|
|
|
public T this[int index] => items[index];
|
|
|
|
public void Add(T item)
|
|
{
|
|
indexMap[item] = items.Count;
|
|
items.Add(item);
|
|
}
|
|
|
|
public void RemoveAt(int i) => Remove(items[i], i);
|
|
public bool Remove(T item)
|
|
{
|
|
if (!indexMap.TryGetValue(item, out int index))
|
|
return false;
|
|
|
|
Remove(item, index);
|
|
|
|
return true;
|
|
}
|
|
|
|
private void Remove(T item, int index)
|
|
{
|
|
int lastIndex = items.Count - 1;
|
|
T lastItem = items[lastIndex];
|
|
|
|
items[index] = lastItem;
|
|
indexMap[lastItem] = index;
|
|
|
|
items.RemoveAt(lastIndex);
|
|
indexMap.Remove(item);
|
|
}
|
|
|
|
public void Insert(int index, T item)
|
|
{
|
|
items.Insert(index, item);
|
|
|
|
for (int i = index; i < items.Count; i++)
|
|
indexMap[items[i]] = i;
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
items.Clear();
|
|
indexMap.Clear();
|
|
}
|
|
|
|
public bool Contains(T item) => indexMap.ContainsKey(item);
|
|
|
|
public int BinarySearch(T item, IComparer<T>? comparer = null) => items.BinarySearch(item, comparer);
|
|
public void Sort(IComparer<T> comparer)
|
|
{
|
|
items.Sort(comparer);
|
|
|
|
for (int i = 0; i < items.Count; i++)
|
|
indexMap[items[i]] = i;
|
|
}
|
|
|
|
public IEnumerator<T> GetEnumerator() => items.GetEnumerator();
|
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
|
|
|
public FastList() { }
|
|
public FastList(int count) { items.Capacity = count; }
|
|
}
|