using System;
namespace MLAPI.Collections
{
///
/// Queue with a fixed size
///
/// The type of the queue
public sealed class FixedQueue
{
private readonly T[] m_Queue;
private int m_QueueCount = 0;
private int m_QueueStart;
///
/// The amount of enqueued objects
///
public int Count => m_QueueCount;
///
/// Gets the element at a given virtual index
///
/// The virtual index to get the item from
/// The element at the virtual index
public T this[int index] => m_Queue[(m_QueueStart + index) % m_Queue.Length];
///
/// Creates a new FixedQueue with a given size
///
/// The size of the queue
public FixedQueue(int maxSize)
{
m_Queue = new T[maxSize];
m_QueueStart = 0;
}
///
/// Enqueues an object
///
///
///
public bool Enqueue(T t)
{
m_Queue[(m_QueueStart + m_QueueCount) % m_Queue.Length] = t;
if (++m_QueueCount > m_Queue.Length)
{
--m_QueueCount;
return true;
}
return false;
}
///
/// Dequeues an object
///
///
public T Dequeue()
{
if (--m_QueueCount == -1) throw new IndexOutOfRangeException("Cannot dequeue empty queue!");
T res = m_Queue[m_QueueStart];
m_QueueStart = (m_QueueStart + 1) % m_Queue.Length;
return res;
}
///
/// Gets the element at a given virtual index
///
/// The virtual index to get the item from
/// The element at the virtual index
public T ElementAt(int index) => m_Queue[(m_QueueStart + index) % m_Queue.Length];
}
}