PkmnLibSharp/PkmnLibSharp/Library/AbilityLibrary.cs

100 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using PkmnLibSharp.Utilities;
namespace PkmnLibSharp.Library
{
public class AbilityLibrary : PointerWrapper
{
private readonly Dictionary<string, Ability> _cache =
new Dictionary<string, Ability>(StringComparer.InvariantCultureIgnoreCase);
public ulong Count => Creaturelib.Generated.TalentLibrary.GetCount(Ptr);
public void Insert(string key, Ability ability)
{
Creaturelib.Generated.TalentLibrary.Insert(Ptr, key.ToPtr(), ability.Ptr).Assert();
_cache.Add(key, ability);
}
public void Delete(string key)
{
Creaturelib.Generated.TalentLibrary.Delete(Ptr, key.ToPtr()).Assert();
_cache.Remove(key);
}
public bool TryGet(string key, out Ability? ability)
{
if (_cache.TryGetValue(key, out ability))
return true;
var ptr = IntPtr.Zero;
if (Creaturelib.Generated.TalentLibrary.TryGet(Ptr, key.ToPtr(), ref ptr) != MarshalHelper.True)
return false;
if (TryResolvePointer(ptr, out ability))
{
_cache.Add(key, ability!);
return true;
}
ability = Constructor.Active.ConstructAbility(ptr)!;
_cache.Add(key, ability);
return true;
}
public Ability Get(string key)
{
if (_cache.TryGetValue(key, out var ability))
return ability;
var ptr = IntPtr.Zero;
Creaturelib.Generated.TalentLibrary.Get(Ptr, key.ToPtr(), ref ptr).Assert();
if (TryResolvePointer(ptr, out Ability? s))
{
_cache.Add(key, s!);
return s!;
}
ability = Constructor.Active.ConstructAbility(ptr)!;
_cache.Add(key, ability);
return ability;
}
public IEnumerable<Ability> GetEnumerator()
{
var count = Creaturelib.Generated.TalentLibrary.GetCount(Ptr);
var ptr = IntPtr.Zero;
for (ulong i = 0; i < count; i++)
{
Creaturelib.Generated.TalentLibrary.GetAtIndex(Ptr, i, ref ptr).Assert();
if (TryResolvePointer(ptr, out Ability? ability))
yield return ability!;
else
yield return Constructor.Active.ConstructAbility(ptr)!;
}
}
internal AbilityLibrary(IntPtr ptr) : base(ptr)
{
}
public AbilityLibrary(ulong initialCapacity) : base()
{
var ptr = IntPtr.Zero;
Creaturelib.Generated.TalentLibrary.Construct(ref ptr, initialCapacity).Assert();
Initialize(ptr);
}
protected override void DeletePtr()
{
Creaturelib.Generated.TalentLibrary.Destruct(Ptr);
}
protected internal override void MarkAsDeleted()
{
base.MarkAsDeleted();
foreach (var ability in _cache)
{
ability.Value.MarkAsDeleted();
}
}
}
}