MultiMap.cs 2.4 KB

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