HashSet.cs 2.2 KB

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