PkmnLibSharp/PkmnLibSharp/Library/Items/ItemLibrary.cs

95 lines
2.9 KiB
C#
Raw Normal View History

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