PkmnLibRSharp/PkmnLibRSharp/Utils/CacheHandler.cs

31 lines
856 B
C#

using System;
using System.Collections.Concurrent;
namespace PkmnLibSharp.Utils
{
internal static class CacheHandler
{
private static readonly ConcurrentDictionary<IntPtr, object> Caches = new();
internal static T GetCache<T>(IntPtr ptr, Func<object> ctor)
{
if (!Caches.TryGetValue(ptr, out var cache))
{
cache = ctor();
Caches.TryAdd(ptr, cache);
}
if (cache.GetType() != typeof(T))
{
throw new InvalidCastException(
$"Can't cast from cache data `{cache.GetType().FullName}` to cache data `{typeof(T).FullName}`");
}
return (T)cache;
}
internal static void RemoveCache(IntPtr ptr)
{
Caches.TryRemove(ptr, out _);
}
}
}