MultiMap.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 MultiMap<T, K> : IEnumerable<MultiMapPair<T, K>>, INativeCollectionClass
  9. where T : unmanaged, IEquatable<T>, IComparable<T> where K : unmanaged, IEquatable<K>
  10. {
  11. private UnsafeType.MultiMap<T, K>* _multiMap;
  12. private const int _defaultPoolBlockSize = 64;
  13. private const int _defaultListPoolSize = 200;
  14. private int _poolBlockSize;
  15. private int _listPoolSize;
  16. public MultiMap(int listPoolSize = _defaultListPoolSize,int nodePoolBlockSize = _defaultPoolBlockSize)
  17. {
  18. _poolBlockSize = nodePoolBlockSize;
  19. _listPoolSize = listPoolSize;
  20. _multiMap = UnsafeType.MultiMap<T, K>.Create(_poolBlockSize,_listPoolSize);
  21. IsDisposed = false;
  22. }
  23. public Span<K> this[T key] => (*_multiMap)[key];
  24. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  25. public void Add(T key, K value)
  26. {
  27. _multiMap->Add(key,value);
  28. }
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public bool Remove(T key, K value)
  31. {
  32. return _multiMap->Remove(key, value);
  33. }
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public bool Remove(T key)
  36. {
  37. return _multiMap->Remove(key);
  38. }
  39. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  40. public void Clear()
  41. {
  42. _multiMap->Clear();
  43. }
  44. public int Count => _multiMap->Count;
  45. IEnumerator<MultiMapPair<T, K>> IEnumerable<MultiMapPair<T, K>>. GetEnumerator()
  46. {
  47. return GetEnumerator();
  48. }
  49. IEnumerator IEnumerable.GetEnumerator()
  50. {
  51. return GetEnumerator();
  52. }
  53. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  54. public UnsafeType.SortedSet<MultiMapPair<T, K>>.Enumerator GetEnumerator()
  55. {
  56. return _multiMap->GetEnumerator();
  57. }
  58. public void Dispose()
  59. {
  60. if (IsDisposed)
  61. {
  62. return;
  63. }
  64. if (_multiMap!=null)
  65. {
  66. _multiMap->Dispose();
  67. NativeMemoryHelper.Free(_multiMap);
  68. NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.MultiMap<T,K>>());
  69. IsDisposed = true;
  70. }
  71. }
  72. public void ReInit()
  73. {
  74. if (IsDisposed)
  75. {
  76. _multiMap = UnsafeType.MultiMap<T, K>.Create(_poolBlockSize,_listPoolSize);
  77. IsDisposed = false;
  78. }
  79. }
  80. public bool IsDisposed { get; private set; }
  81. ~MultiMap()
  82. {
  83. Dispose();
  84. }
  85. }
  86. }