Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created August 19, 2011 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/1156583 to your computer and use it in GitHub Desktop.
Save jmcd/1156583 to your computer and use it in GitHub Desktop.
A fixed capacity buffer that allows adding of items beyond the capacity by discarding earlier items. Adding is O(1), rather than O(N) because the internal representation is overwritten rather than actually moved.
public class FixedCapacityMovingBuffer<T>
{
private readonly int _capacity;
private readonly T[] _buffer;
private int _addCount;
public FixedCapacityMovingBuffer(int capacity)
{
_capacity = capacity;
_buffer = new T[capacity];
_addCount = 0;
}
public void Add(T item)
{
_buffer[_addCount%_capacity] = item;
_addCount++;
}
public T[] GetBuffer()
{
var result = new T[_capacity];
var head = _addCount > _capacity ? (_addCount - _capacity)%_capacity : 0;
Array.Copy(_buffer, head, result, 0, _capacity - head);
Array.Copy(_buffer, 0, result, _capacity - head, head);
return result;
}
}
using System;
using NUnit.Framework;
[TestFixture]
public class FixedCapacityBufferTests
{
[Test]
public void OverflowingCapacityMovesBuffer()
{
const int capacity = 3;
var buffer = new FixedCapacityMovingBuffer<int>(capacity);
for (var i = 1; i < 10; i++)
{
buffer.Add(i);
var items = buffer.GetBuffer();
var lim = Math.Min(i, capacity);
for (var itemIndex = 0; itemIndex < lim; itemIndex++)
{
var expected = i + itemIndex + 1 - lim;
Assert.AreEqual(expected, items[itemIndex]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment