// Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2023 Kybernetik //
using System.Collections.Generic;
namespace Animancer
{
/// A simple stack implementation that tracks an active index without actually adding or removing objects.
/// https://kybernetik.com.au/animancer/api/Animancer/LazyStack_1
///
public class LazyStack where T : new()
{
/************************************************************************************************************************/
/// The underlying collection of objects.
///
/// This is not a because that class comes from a different assembly that might not
/// otherwise need to be included in builds, so using a can slightly reduce build size.
///
private readonly List Stack;
/// The index of the object in the .
private int _CurrentIndex = -1;
/// The object currently on the top of the stack.
public T Current { get; private set; }
/************************************************************************************************************************/
/// Creates a new with a default internal list capacity of 16.
public LazyStack()
{
Stack = new List();
}
/// Creates a new with the specified internal list capacity.
public LazyStack(int capacity)
{
Stack = new List(capacity);
for (int i = 0; i < capacity; i++)
Stack[i] = new T();
}
/************************************************************************************************************************/
/// Moves to the next object in the stack.
public T Increment()
{
_CurrentIndex++;
if (_CurrentIndex == Stack.Count)
{
Current = new T();
Stack.Add(Current);
}
else
{
Current = Stack[_CurrentIndex];
}
return Current;
}
/************************************************************************************************************************/
/// Moves to the previous object in the stack.
public void Decrement()
{
_CurrentIndex--;
if (_CurrentIndex >= 0)
Current = Stack[_CurrentIndex];
else
Current = default;
}
/************************************************************************************************************************/
}
}