using System;
namespace UnityEngine.XR.Interaction.Toolkit.Utilities.Collections
{
///
/// A simple circular buffer implementation for efficient data storage and access.
///
/// The type of elements stored in the buffer.
internal class CircularBuffer
{
readonly T[] m_Buffer;
int m_Start;
int m_Count;
///
/// Initializes a new instance of the class.
///
/// The maximum number of elements the buffer can hold.
public CircularBuffer(int capacity)
{
m_Buffer = new T[capacity];
m_Start = 0;
m_Count = 0;
}
///
/// Gets the number of elements currently in the buffer.
///
public int count => m_Count;
///
/// Gets the maximum number of elements the buffer can hold.
///
public int capacity => m_Buffer.Length;
///
/// Adds an item to the buffer, overwriting the oldest item if the buffer is full.
///
/// The item to add to the buffer.
public void Add(T item)
{
int index = (m_Start + m_Count) % m_Buffer.Length;
m_Buffer[index] = item;
if (m_Count < m_Buffer.Length)
m_Count++;
else
m_Start = (m_Start + 1) % m_Buffer.Length;
}
///
/// Gets the item at the specified index in the buffer.
///
/// The index of the item to retrieve.
/// The item at the specified index.
/// Throws if is less than 0 or equal to or greater than .
public T this[int index]
{
get
{
if (index < 0 || index >= m_Count)
throw new IndexOutOfRangeException();
return m_Buffer[(m_Start + index) % m_Buffer.Length];
}
}
///
/// Clears all items from the buffer.
///
public void Clear()
{
m_Start = 0;
m_Count = 0;
}
}
}