50 lines
1.1 KiB
C#
50 lines
1.1 KiB
C#
namespace FoodFactory.Core;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
public class Registry<TEntry> where TEntry : notnull
|
|
{
|
|
private readonly Dictionary<TEntry, int> _data = [];
|
|
private readonly List<TEntry> _list = [];
|
|
private readonly object _lock = new();
|
|
public IReadOnlyList<TEntry> Entries => _list;
|
|
public void Clear()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
_data.Clear();
|
|
_list.Clear();
|
|
}
|
|
}
|
|
public int GetOrCreate(TEntry name)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (_data.TryGetValue(name, out var tag))
|
|
{
|
|
return tag;
|
|
}
|
|
return CreateNewKey(name);
|
|
}
|
|
}
|
|
public TEntry GetEntry(int index)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if ((uint)index >= (uint)_list.Count)
|
|
{
|
|
throw new KeyNotFoundException($"The index {index} you are trying to access does not exist in the registry. The registry only has {_list.Count} of type {typeof(TEntry).Name}s");
|
|
}
|
|
return _list[index];
|
|
}
|
|
}
|
|
|
|
private int CreateNewKey(TEntry name)
|
|
{
|
|
int index = _list.Count;
|
|
_list.Add(name);
|
|
_data[name] = index;
|
|
return index;
|
|
}
|
|
}
|