using System;
namespace Robust.Shared.Utility
{
// Based on Box2D's b2GrowableStack.
///
/// This is a growable LIFO stack with an initial capacity of N.
/// If the stack size exceeds the initial capacity, the heap is used
/// to increase the size of the stack.
///
/// The type of elements in the stack.
internal ref struct GrowableStack where T : unmanaged
{
private Span _stack;
private int _count;
private int _capacity;
///
/// Creates the growable stack with the allocated space as stack space.
///
public GrowableStack(Span stackSpace)
{
_stack = stackSpace;
_capacity = stackSpace.Length;
_count = 0;
}
internal ref T this[int index] => ref _stack[index];
public void Push(in T element)
{
if (_count == _capacity)
{
_capacity *= 2;
var oldStack = _stack;
_stack = GC.AllocateUninitializedArray(_capacity);
oldStack.CopyTo(_stack);
}
_stack[_count] = element;
++_count;
}
public T Pop()
{
--_count;
return _stack[_count];
}
public int GetCount()
{
return _count;
}
}
}