PkmnLibSharp/PkmnLibSharp/Library/Moves/MoveLibrary.cs

98 lines
2.9 KiB
C#
Raw Normal View History

2020-05-03 21:34:28 +00:00
using System;
using System.Collections.Generic;
using Creaturelib.Generated;
2020-05-03 21:34:28 +00:00
using PkmnLibSharp.Utilities;
namespace PkmnLibSharp.Library.Moves
2020-05-03 21:34:28 +00:00
{
public class MoveLibrary : PointerWrapper
{
2020-07-18 14:49:11 +00:00
private readonly Dictionary<string, MoveData> _cache =
new Dictionary<string, MoveData>(StringComparer.InvariantCultureIgnoreCase);
internal MoveLibrary(IntPtr ptr) : base(ptr)
{
}
2020-05-03 21:34:28 +00:00
public ulong Count => AttackLibrary.GetCount(Ptr);
public void Insert(string key, MoveData move)
{
AttackLibrary.Insert(Ptr, key.ToPtr(), move.Ptr).Assert();
_cache.Add(key, move);
}
public void Delete(string key)
{
_cache.Remove(key);
2022-03-12 09:32:31 +00:00
AttackLibrary.Delete(Ptr, key.ToPtr()).Assert();
2020-05-03 21:34:28 +00:00
}
public bool TryGet(string key, out MoveData? move)
2020-05-03 21:34:28 +00:00
{
if (_cache.TryGetValue(key, out move))
return true;
var ptr = IntPtr.Zero;
2020-07-18 14:49:11 +00:00
if (AttackLibrary.TryGet(Ptr, key.ToPtr(), ref ptr) != MarshalHelper.True)
2020-05-03 21:34:28 +00:00
return false;
if (TryResolvePointer(ptr, out move))
{
_cache.Add(key, move!);
2020-05-03 21:34:28 +00:00
return true;
}
2020-07-18 14:49:11 +00:00
move = Constructor.Active.ConstructMove(ptr)!;
2020-05-03 21:34:28 +00:00
_cache.Add(key, move);
return true;
}
public MoveData Get(string key)
{
if (_cache.TryGetValue(key, out var move))
return move;
var ptr = IntPtr.Zero;
AttackLibrary.Get(Ptr, key.ToPtr(), ref ptr).Assert();
if (TryResolvePointer(ptr, out MoveData? m))
2020-05-03 21:34:28 +00:00
{
_cache.Add(key, m!);
return m!;
2020-05-03 21:34:28 +00:00
}
2020-07-18 14:49:11 +00:00
move = Constructor.Active.ConstructMove(ptr)!;
2020-05-03 21:34:28 +00:00
_cache.Add(key, move);
return move;
}
public MoveLibrary(ulong defaultCapacity)
2020-05-03 21:34:28 +00:00
{
var ptr = IntPtr.Zero;
AttackLibrary.Construct(ref ptr, defaultCapacity).Assert();
Initialize(ptr);
2020-05-03 21:34:28 +00:00
}
2020-08-10 17:13:17 +00:00
public IEnumerable<MoveData> GetEnumerator()
{
var count = AttackLibrary.GetCount(Ptr);
var ptr = IntPtr.Zero;
for (ulong i = 0; i < count; i++)
{
AttackLibrary.GetAtIndex(Ptr, i, ref ptr).Assert();
if (TryResolvePointer(ptr, out MoveData? move))
yield return move!;
else
yield return Constructor.Active.ConstructMove(ptr)!;
2020-08-10 17:13:17 +00:00
}
}
2020-05-03 21:34:28 +00:00
protected internal override void MarkAsDeleted()
{
base.MarkAsDeleted();
2020-07-18 14:49:11 +00:00
foreach (var moveData in _cache) moveData.Value.MarkAsDeleted();
}
2020-05-03 21:34:28 +00:00
protected override void DeletePtr()
{
AttackLibrary.Destruct(Ptr);
}
}
}