MultiMap.cs 2.3 KB

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