Stack.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. private int _capacity;
  10. public Stack(int initialCapacity = _defaultCapacity)
  11. {
  12. _capacity = initialCapacity;
  13. _stack = UnsafeType.Stack<T>.Create(_capacity);
  14. IsDisposed = false;
  15. }
  16. public int Count => _stack->Count;
  17. public void Dispose()
  18. {
  19. if (IsDisposed)
  20. {
  21. return;
  22. }
  23. if (_stack != null)
  24. {
  25. _stack->Dispose();
  26. NativeMemoryHelper.Free(_stack);
  27. NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.Stack<T>>());
  28. IsDisposed = true;
  29. }
  30. }
  31. public void Clear()
  32. {
  33. _stack->Clear();
  34. }
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. public bool Contains(in T obj)
  37. {
  38. return _stack->Contains(obj);
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public T Peak()
  42. {
  43. return _stack->Peak();
  44. }
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public T Pop()
  47. {
  48. return _stack->Pop();
  49. }
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public bool TryPop(out T result)
  52. {
  53. var returnValue = _stack->TryPop(out result);
  54. return returnValue;
  55. }
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. public void Push(in T obj)
  58. {
  59. _stack->Push(obj);
  60. }
  61. ~Stack()
  62. {
  63. Dispose();
  64. }
  65. public void ReInit()
  66. {
  67. if (IsDisposed)
  68. {
  69. _stack = UnsafeType.Stack<T>.Create(_capacity);
  70. IsDisposed = false;
  71. }
  72. }
  73. public bool IsDisposed { get; private set; }
  74. }
  75. }