Skip to content

Instantly share code, notes, and snippets.

@LambdaSix
Created January 26, 2024 22:20
Show Gist options
  • Save LambdaSix/444bb96caa7cbbe92135d503d89d9998 to your computer and use it in GitHub Desktop.
Save LambdaSix/444bb96caa7cbbe92135d503d89d9998 to your computer and use it in GitHub Desktop.
/// <summary>
/// A first in last out queue
/// </summary>
/// <typeparam name="T"></typeparam>
public class RollingQueue<T> : IEnumerable<T>
{
private T[] _stack;
private int _stackReadIdx = 0;
private int _stackWriteIdx = 0;
public int Length;
public RollingQueue(int stackSize = 5)
{
_stack = new T[stackSize];
Length = stackSize;
}
/// <summary>
/// Return the next element, looping back to the beginning if at the end
/// </summary>
/// <returns></returns>
public T Next()
{
if (_stackReadIdx > _stack.Length-1)
_stackReadIdx = 0;
return _stack[_stackReadIdx++];
}
/// <summary>
/// Query the next item in the stack without moving the index
/// </summary>
/// <returns></returns>
public T Peek()
{
return _stack[Math.Min(_stackReadIdx, _stack.Length - 1)];
}
/// <summary>
/// Add an element to the stack, looping back to the beginning if the stack is full
/// </summary>
/// <returns></returns>
public void Add(T item)
{
if (_stackWriteIdx > _stack.Length-1)
_stackWriteIdx = 0;
_stack[_stackWriteIdx++] = item;
}
public IEnumerator<T> GetEnumerator()
{
return _stack.AsEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _stack.GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment