StorableDictionary.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Island.StandardLib.Storage
  5. {
  6. [Serializable]
  7. public class StorableDictionary<TKey, TValue> : IStorable, IEnumerable<KeyValuePair<TKey, TValue>> where TKey : IStorable, new() where TValue : IStorable, new()
  8. {
  9. Dictionary<TKey, TValue> baseDict;
  10. public StorableDictionary() => baseDict = new Dictionary<TKey, TValue>();
  11. public TValue this[TKey key]
  12. {
  13. get => baseDict[key];
  14. set => baseDict[key] = value;
  15. }
  16. public void Add(TKey key, TValue val) => baseDict.Add(key, val);
  17. public void Remove(TKey key) => baseDict.Remove(key);
  18. public int Count => baseDict.Count;
  19. public bool ContainsKey(TKey key) => baseDict.ContainsKey(key);
  20. public bool ContainsValue(TValue val) => baseDict.ContainsValue(val);
  21. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => baseDict.GetEnumerator();
  22. IEnumerator IEnumerable.GetEnumerator() => baseDict.GetEnumerator();
  23. public bool TryGetValue(TKey key, out TValue value) => baseDict.TryGetValue(key, out value);
  24. public void ReadFromData(DataStorage data)
  25. {
  26. data.Read(out int len);
  27. for (int i = 0; i < len; i++)
  28. {
  29. TKey key = data.Read<TKey>();
  30. data.Read(out bool hasVal);
  31. TValue val = default;
  32. if (hasVal) val = data.Read<TValue>();
  33. baseDict.Add(key, val);
  34. }
  35. }
  36. public void WriteToData(DataStorage data)
  37. {
  38. data.Write(baseDict.Count);
  39. foreach (var tpair in baseDict)
  40. {
  41. data.Write(tpair.Key);
  42. if (tpair.Value == null) data.Write(false);
  43. else
  44. {
  45. data.Write(true);
  46. data.Write(tpair.Value);
  47. }
  48. }
  49. }
  50. }
  51. }