74 lines
1.1 KiB
C#
74 lines
1.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
|
|
namespace BitStrap
|
|
{
|
|
public class CircularBuffer<T> : IEnumerable<T>, IEnumerable
|
|
{
|
|
private T[] elements;
|
|
|
|
private int tail;
|
|
|
|
public int Count { get; private set; }
|
|
|
|
public T Current
|
|
{
|
|
get
|
|
{
|
|
return elements[tail];
|
|
}
|
|
}
|
|
|
|
public T this[int index]
|
|
{
|
|
get
|
|
{
|
|
return elements[(tail + index) % Count];
|
|
}
|
|
set
|
|
{
|
|
elements[(tail + index) % Count] = value;
|
|
}
|
|
}
|
|
|
|
public CircularBuffer(int capacity)
|
|
{
|
|
elements = new T[capacity];
|
|
Count = 0;
|
|
tail = 0;
|
|
}
|
|
|
|
public void Add(T element)
|
|
{
|
|
elements[tail] = element;
|
|
int num = elements.Length;
|
|
Count = ((Count >= num) ? num : (Count + 1));
|
|
tail = (tail + 1) % num;
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
Count = 0;
|
|
tail = 0;
|
|
}
|
|
|
|
public IEnumerator<T> GetEnumerator()
|
|
{
|
|
int count = Count;
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
yield return this[i];
|
|
}
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
{
|
|
int count = Count;
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
yield return this[i];
|
|
}
|
|
}
|
|
}
|
|
}
|