using System; using System.Collections; using System.Collections.Generic; namespace Island.StandardLib.Storage { [Serializable] public class StorableDictionary : IStorable, IEnumerable> where TKey : IStorable, new() where TValue : IStorable, new() { Dictionary baseDict; public StorableDictionary() => baseDict = new Dictionary(); public TValue this[TKey key] { get => baseDict[key]; set => baseDict[key] = value; } public void Add(TKey key, TValue val) => baseDict.Add(key, val); public void Remove(TKey key) => baseDict.Remove(key); public int Count => baseDict.Count; public bool ContainsKey(TKey key) => baseDict.ContainsKey(key); public bool ContainsValue(TValue val) => baseDict.ContainsValue(val); public IEnumerator> GetEnumerator() => baseDict.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => baseDict.GetEnumerator(); public bool TryGetValue(TKey key, out TValue value) => baseDict.TryGetValue(key, out value); public void ReadFromData(DataStorage data) { data.Read(out int len); for (int i = 0; i < len; i++) { TKey key = data.Read(); data.Read(out bool hasVal); TValue val = default; if (hasVal) val = data.Read(); baseDict.Add(key, val); } } public void WriteToData(DataStorage data) { data.Write(baseDict.Count); foreach (var tpair in baseDict) { data.Write(tpair.Key); if (tpair.Value == null) data.Write(false); else { data.Write(true); data.Write(tpair.Value); } } } } }