diff --git a/src/ShipInventoryUpdated/Helpers/API/ItemIdentifier.cs b/src/ShipInventoryUpdated/Helpers/API/ItemIdentifier.cs index f9dd9ae..12b83e1 100644 --- a/src/ShipInventoryUpdated/Helpers/API/ItemIdentifier.cs +++ b/src/ShipInventoryUpdated/Helpers/API/ItemIdentifier.cs @@ -1,10 +1,15 @@ -using ShipInventoryUpdated.Dependencies.LethalLib; +using System.Security.Cryptography; +using System.Text; +using ShipInventoryUpdated.Dependencies.LethalLib; +using Unity.Collections; namespace ShipInventoryUpdated.Helpers.API; internal static class ItemIdentifier { private const string INVALID_ITEM_ID = "InvalidItem"; + private static readonly Dictionary ItemToHash = new(); + private static readonly Dictionary HashToItem = new(); /// /// Fetches the generic ID of the given item @@ -14,15 +19,27 @@ public static string GetID(Item? item) if (item == null) return INVALID_ITEM_ID; + if (ItemToHash.TryGetValue(item, out var hashedId)) + return hashedId; + + string? id = null; + if (Dependency.Enabled) - { - var moddedID = Dependency.GetID(item); + id = Dependency.GetID(item); - if (moddedID != null) - return moddedID; - } + id ??= item.itemName; - return $"Vanilla/{item.itemName}"; + using var sha256Hash = SHA256.Create(); + + var rawData = Encoding.Default.GetBytes(id); + var hashedData = sha256Hash.ComputeHash(rawData); + hashedId = Encoding.Default.GetString(hashedData); + hashedId = new FixedString32Bytes(hashedId).ToString(); + + ItemToHash.Add(item, hashedId); + HashToItem.TryAdd(hashedId, item); + + return hashedId; } /// @@ -33,22 +50,24 @@ public static string GetID(Item? item) if (id == INVALID_ITEM_ID) return null; + if (HashToItem.TryGetValue(id, out var item)) + return item; + if (Dependency.Enabled) - { - var moddedItem = Dependency.GetItem(id); + item = Dependency.GetItem(id); - if (moddedItem != null) - return moddedItem; + if (item == null) + { + var itemList = StartOfRound.Instance?.allItemsList?.itemsList ?? []; + item = itemList.FirstOrDefault(i => GetID(i) == id); } - foreach (var item in StartOfRound.Instance?.allItemsList?.itemsList ?? []) - { - var currentId = GetID(item); + if (item == null) + return null; - if (currentId == id) - return item; - } + HashToItem.Add(id, item); + ItemToHash.TryAdd(item, id); - return null; + return item; } } \ No newline at end of file