rokojori_action_library/Runtime/Structures/RingBuffer.cs

73 lines
1.3 KiB
C#

using System.Collections.Generic;
using Rokojori.Extensions;
namespace Rokojori;
public class RingBuffer<T>
{
protected readonly T[] _buffer;
protected int _head;
protected int _count;
public RingBuffer( int capacity )
{
_buffer = new T[capacity];
}
public int count => _count;
public int capacity => _buffer.Length;
public void ForEach( System.Action<T> callback )
{
for ( int i = 0; i < _count; i++ )
{
callback( this[ i ] );
}
}
public int CountItems( System.Predicate<T> predicate )
{
var num = 0;
for ( int i = 0; i < _count; i++ )
{
if ( predicate( this[ i ] ) )
{
num ++;
}
}
return num;
}
public void Add( T item )
{
int index = (_head + _count) % capacity;
_buffer[index] = item;
if (_count == capacity)
{
_head = (_head + 1) % capacity;
}
else
{
_count ++;
}
}
public T this[int index]
{
get
{
if ( (uint)index >= (uint)_count )
{
throw new System.ArgumentOutOfRangeException( nameof( index ) );
}
return _buffer[ ( _head + index ) % capacity ];
}
}
}