Nerfed/Nerfed.Runtime/Util/BoundedQueue.cs

73 lines
1.5 KiB
C#
Raw Normal View History

using System.Collections;
namespace Nerfed.Runtime;
public class BoundedQueue<T> : IEnumerable<T>, ICollection, IReadOnlyCollection<T>
{
private readonly Queue<T> queue = null;
private readonly int maxSize = 10;
private T lastAddedElement;
public BoundedQueue(int maxSize)
{
this.maxSize = maxSize;
queue = new Queue<T>(maxSize);
}
public void Enqueue(T item)
{
queue.Enqueue(item);
if (queue.Count > maxSize)
{
queue.Dequeue(); // Remove the oldest element
}
lastAddedElement = item;
}
public T Dequeue()
{
return queue.Dequeue();
}
public T Peek()
{
return queue.Peek();
}
public T LastAddedElement()
{
return lastAddedElement;
}
public void Clear()
{
queue.Clear();
}
public bool Contains(T item)
{
return queue.Contains(item);
}
public IEnumerator<T> GetEnumerator()
{
return queue.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return queue.GetEnumerator();
}
public void CopyTo(Array array, int index)
{
((ICollection)queue).CopyTo(array, index);
}
public int Count => queue.Count;
public int Capacity => maxSize;
public bool IsSynchronized => ((ICollection)queue).IsSynchronized;
public object SyncRoot => ((ICollection)queue).SyncRoot;
int IReadOnlyCollection<T>.Count => queue.Count;
}