Stack.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. namespace NativeCollection
  4. {
  5. public unsafe class Stack<T> : INativeCollectionClass where T : unmanaged
  6. {
  7. private const int _defaultCapacity = 10;
  8. private UnsafeType.Stack<T>* _stack;
  9. public Stack(int initialCapacity = _defaultCapacity)
  10. {
  11. _stack = UnsafeType.Stack<T>.Create(initialCapacity);
  12. IsDisposed = false;
  13. }
  14. public int Count => _stack->Count;
  15. public void Dispose()
  16. {
  17. if (IsDisposed)
  18. {
  19. return;
  20. }
  21. if (_stack != null)
  22. {
  23. _stack->Dispose();
  24. NativeMemoryHelper.Free(_stack);
  25. GC.RemoveMemoryPressure(Unsafe.SizeOf<UnsafeType.Stack<T>>());
  26. IsDisposed = true;
  27. }
  28. }
  29. public void Clear()
  30. {
  31. _stack->Clear();
  32. }
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. public bool Contains(in T obj)
  35. {
  36. return _stack->Contains(obj);
  37. }
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public T Peak()
  40. {
  41. return _stack->Peak();
  42. }
  43. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  44. public T Pop()
  45. {
  46. return _stack->Pop();
  47. }
  48. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  49. public bool TryPop(out T result)
  50. {
  51. var returnValue = _stack->TryPop(out result);
  52. return returnValue;
  53. }
  54. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  55. public void Push(in T obj)
  56. {
  57. _stack->Push(obj);
  58. }
  59. ~Stack()
  60. {
  61. Dispose();
  62. }
  63. public void ReInit()
  64. {
  65. if (IsDisposed)
  66. {
  67. _stack = UnsafeType.Stack<T>.Create(_defaultCapacity);
  68. IsDisposed = false;
  69. }
  70. }
  71. public bool IsDisposed { get; private set; }
  72. }
  73. }