PkmnLibRSharp/PkmnLibRSharp/StaticData/Libraries/DataLibrary.cs

101 lines
2.7 KiB
C#
Raw Normal View History

2022-09-23 16:45:56 +00:00
using System;
2022-10-01 13:39:33 +00:00
using System.Collections;
2022-09-23 16:45:56 +00:00
using System.Collections.Generic;
2023-04-15 07:58:21 +00:00
using System.Diagnostics.CodeAnalysis;
2022-10-01 13:39:33 +00:00
using System.Linq;
2022-10-08 11:42:30 +00:00
using PkmnLibSharp.FFI;
2022-09-23 16:45:56 +00:00
using PkmnLibSharp.Utils;
namespace PkmnLibSharp.StaticData.Libraries
{
2022-10-01 13:39:33 +00:00
public abstract class DataLibrary<T> : ExternPointer<DataLibrary<T>.CacheData>, IReadOnlyDictionary<string, T>
2022-09-23 16:45:56 +00:00
{
2022-10-08 11:42:30 +00:00
protected DataLibrary(IdentifiablePointer ptr, bool isOwner) : base(ptr, isOwner)
2022-09-23 16:45:56 +00:00
{
}
public class CacheData
{
2022-10-01 13:39:33 +00:00
public List<string>? KeyCache { get; internal set; }
2022-09-23 16:45:56 +00:00
public Dictionary<string, T> ValueCache { get; } = new();
}
public abstract void Add(string key, T value);
2022-10-01 13:39:33 +00:00
public abstract int Count { get; }
2022-09-23 16:45:56 +00:00
protected abstract T? GetValueByKey(string key);
2022-10-01 13:39:33 +00:00
public bool ContainsKey(string key)
{
return GetValueByKey(key) != null;
}
2023-04-15 07:58:21 +00:00
public bool TryGetValue(string key, [NotNullWhen(true)] out T value)
2022-09-23 16:45:56 +00:00
{
if (Cache.ValueCache.TryGetValue(key, out value) && value != null)
return true;
2022-10-01 13:39:33 +00:00
var v = GetValueByKey(key);
if (v != null)
2022-09-23 16:45:56 +00:00
{
2022-10-01 13:39:33 +00:00
Cache.ValueCache.Add(key, v);
value = v;
2022-09-23 16:45:56 +00:00
}
2022-10-01 13:39:33 +00:00
return v != null;
2022-09-23 16:45:56 +00:00
}
public T this[string key]
{
get
{
if (!TryGetValue(key, out var value))
throw new KeyNotFoundException($"Value with key `{key}` was not found");
return value!;
}
}
2022-10-01 13:39:33 +00:00
public abstract string? GetKeyByIndex(ulong index);
public IEnumerable<string> Keys
{
get
{
if (Cache.KeyCache == null)
{
Cache.KeyCache = new List<string>(Count);
for (ulong i = 0; i < (ulong)Count; i++)
{
var key = GetKeyByIndex(i);
if (key == null)
break;
Cache.KeyCache.Add(key);
}
}
return Cache.KeyCache;
}
}
public IEnumerable<T> Values
{
get { return Keys.Select(key => this[key]); }
}
2022-09-23 16:45:56 +00:00
protected override CacheData CreateCache() => new();
2022-10-01 13:39:33 +00:00
public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
return Keys.Select(key => new KeyValuePair<string, T>(key, this[key])).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
2022-10-08 11:42:30 +00:00
~DataLibrary()
{
Dispose();
}
2022-09-23 16:45:56 +00:00
}
}