Map.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using NativeCollection.UnsafeType;
  6. namespace NativeCollection
  7. {
  8. public unsafe class Map<T, K> : IEnumerable<MapPair<T, K>>, INativeCollectionClass
  9. where T : unmanaged, IEquatable<T>, IComparable<T> where K : unmanaged, IEquatable<K>
  10. {
  11. private const int _defaultPoolBlockSize = 64;
  12. private int _poolBlockSize;
  13. private UnsafeType.Map<T, K>* _map;
  14. public Map(int poolBlockSize = _defaultPoolBlockSize)
  15. {
  16. _poolBlockSize = poolBlockSize;
  17. _map = UnsafeType.Map<T, K>.Create(_poolBlockSize);
  18. IsDisposed = false;
  19. }
  20. public K this[T key]
  21. {
  22. get => (*_map)[key];
  23. set => (*_map)[key] = value;
  24. }
  25. public int Count => _map->Count;
  26. IEnumerator<MapPair<T, K>> IEnumerable<MapPair<T, K>>.GetEnumerator()
  27. {
  28. return GetEnumerator();
  29. }
  30. IEnumerator IEnumerable.GetEnumerator()
  31. {
  32. return GetEnumerator();
  33. }
  34. public void Dispose()
  35. {
  36. if (IsDisposed) return;
  37. if (_map != null)
  38. {
  39. _map->Dispose();
  40. NativeMemoryHelper.Free(_map);
  41. NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.Map<T, K>>());
  42. IsDisposed = true;
  43. }
  44. }
  45. public void ReInit()
  46. {
  47. if (IsDisposed)
  48. {
  49. _map = UnsafeType.Map<T, K>.Create(_poolBlockSize);
  50. IsDisposed = false;
  51. }
  52. }
  53. public bool IsDisposed { get; private set; }
  54. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  55. public void Add(T key, K value)
  56. {
  57. _map->Add(key, value);
  58. }
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. public bool Remove(T key)
  61. {
  62. return _map->Remove(key);
  63. }
  64. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  65. public void Clear()
  66. {
  67. _map->Clear();
  68. }
  69. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  70. public UnsafeType.SortedSet<MapPair<T, K>>.Enumerator GetEnumerator()
  71. {
  72. return _map->GetEnumerator();
  73. }
  74. ~Map()
  75. {
  76. Dispose();
  77. }
  78. }
  79. }