using System.Runtime.CompilerServices; namespace Brutal.Collections; /// /// Interface for a free list index pool, a lightweight allocator that tracks free elements /// See: https://en.wikipedia.org/wiki/Free_list /// public interface IFreeListIndexPool { /// /// Total backing capacity /// public int Capacity { get; set; } /// /// Add element to list, returns index/key to element /// /// Index to element public int Add(); /// /// Check if element at index is empty /// public bool IsEmpty(int index); /// /// Remove element at index /// public void Remove(int index); /// /// Reset list as empty /// public void Clear(); } /// /// Pool/allocator of indices that tracks free elements to avoid reallocation. /// Can be used as the allocator for a FreeList. See: https://en.wikipedia.org/wiki/Free_list /// public class FreeListIndexPool : IFreeListIndexPool { /// /// Empty element index not part of linked list of free elements /// const int OCCUPIED = -1; /// /// Construct a new free list, that is empty and can grow /// public FreeListIndexPool() { _list = new(); AllowResize = true; } /// /// Construct a new free list with a given capacity /// /// Initial capacity /// If false, will throw instead of growing capacity when backing list is full public FreeListIndexPool(int capacity, bool allowResize) { _list = new(capacity); AllowResize = allowResize; } private readonly List _list; private int _firstFree = OCCUPIED; /// /// If true, the list will grow when full, if false, it will throw an exception /// public readonly bool AllowResize; /// public int Capacity { get => _list.Capacity; set => _list.Capacity = value; } /// /// Access element by index /// public int this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _list[index]; [MethodImpl(MethodImplOptions.AggressiveInlining)] set => _list[index] = value; } /// public bool IsEmpty(int index) { return _list[index] == OCCUPIED; } public bool TryAdd(out int index) { if (_firstFree != OCCUPIED) { index = _firstFree; _firstFree = _list[index]; _list[index] = OCCUPIED; } else { if (!AllowResize && _list.Count == _list.Capacity) { index = -1; return false; } _list.Add(OCCUPIED); index = _list.Count - 1; } return true; } /// public int Add() { if (!TryAdd(out var index)) throw new Exception("FreeListIndexPool is full, and is not allowed to grow"); return index; } /// public void Remove(int index) { _list[index] = _firstFree; _firstFree = index; } /// public void Clear() { _list.Clear(); _firstFree = OCCUPIED; } }