PkmnLibRSharp/PkmnLibRSharp/StaticData/Libraries/DataLibrary.cs

48 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using PkmnLibSharp.Utils;
namespace PkmnLibSharp.StaticData.Libraries
{
public abstract class DataLibrary<T> : ExternPointer<DataLibrary<T>.CacheData>
{
protected DataLibrary(IntPtr ptr, bool isOwner) : base(ptr, isOwner)
{
}
public class CacheData
{
public Dictionary<string, T> ValueCache { get; } = new();
}
public abstract void Add(string key, T value);
public abstract ulong Length { get; }
protected abstract T? GetValueByKey(string key);
public bool TryGetValue(string key, out T? value)
{
if (Cache.ValueCache.TryGetValue(key, out value) && value != null)
return true;
value = GetValueByKey(key);
if (value != null)
{
Cache.ValueCache.Add(key, value);
}
return value != null;
}
public T this[string key]
{
get
{
if (!TryGetValue(key, out var value))
throw new KeyNotFoundException($"Value with key `{key}` was not found");
return value!;
}
}
protected override CacheData CreateCache() => new();
}
}