CircularBuffer added to my .net Utils Library

I've just updated my .net Utilities Library with a Circular Buffer. Such a buffer (also called Ring buffer) has a given capacity, and when this capacity is reached new entries overwrite old ones. In other words, it is a buffer that holds the last {capacity} items.

The implementation is currently not optimized for speed, this is something I'll tackle soon. (Update: Done, CopyTo and Contains should be much faster) Implementing a circular buffer is relatively simple, but it makes my head spin with off-by-one errors that you encounter when you have to deal with an array that's split at an arbitrary point. It is definitely a nice exercise for a Code Kata though and may teach you a thing or two about Enumerators.

It is not possible to remove items (I don't need that functionality yet for my purposes), I might look into it in the future. The Enumerator works as expected, it starts with the oldest element and returns all elements until the most recently inserted one. Modifying the collection while enumerating throws an Exception, and thread safety is the same as with a List<T>, which means "none at all".

Example usage:

var buffer = new CircularBuffer<int>(3);
buffer.Add(1);
buffer.Add(2);
buffer.Add(3);
buffer.Add(4);
// buffer now holds [2,3,4]

Comments (2)

aaronFebruary 17th, 2012 at 07:38

hey mate, thanks this was really useful. i needed a remove though so I added one. Sadly, I am really under the gun with this project or I'd create a pull request with tests. Here is a gist instead, https://gist.github.com/1851315

mstumFebruary 19th, 2012 at 03:43

Glad you like it, and thanks for the contribution! I've pulled in the change and updated the code on GitHub.