chore: Add CircularBuffer class (c#)

This commit is contained in:
John Colvin committed 2025-08-24 13:46:55 -04:00
1 parent fc050f4bd3
commit 03c99cc3df
2 files changed
+268

No files matched your search

@@ -0,0 +1,180 @@
#nullable enable
namespace Spark.Core.Collections;
using bts.utils;
using mbts.utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class CircularBuffer<T> : IList<T>, IReadOnlyList<T> {
readonly int capacity;
T[] items;
int origin;
int count;
public CircularBuffer(int capacity) : this(capacity, capacity) { }
public CircularBuffer(int capacity, int initialCapacity) {
this.capacity = capacity;
ExceptionAssert.Argument.GreaterThanEqualTo(capacity, 0);
items = new T[initialCapacity.within_range(0, capacity)];
}
public T this[int index] {
get => items[getOffsetIndex(index)];
set => items[getOffsetIndex(index)] = value;
}
public int Count => count;
public bool IsReadOnly => false;
public void Add(T item) {
if (capacity == 0) {
return;
}
if (count == capacity) {
items[origin++] = item;
if (origin == items.Length) {
origin = 0;
}
return;
}
var idx = origin + count++;
if (idx >= capacity) {
idx -= capacity;
}
items[idx] = item;
}
public void Clear() {
origin = 0;
count = 0;
Array.Clear(items);
}
public bool Contains(T item) =>
items.Contains(item);
public void CopyTo(T[] array, int arrayIndex) {
Array.Copy(items, origin, array, arrayIndex, count - origin);
Array.Copy(items, 0, array, arrayIndex + count - origin, origin);
}
public IEnumerator<T> GetEnumerator() {
var ct = count;
int i;
for (i = origin; i < ct; i++) {
yield return items[i];
}
for (i = 0; i < origin; i++) {
yield return items[i];
}
}
public int IndexOf(T item) {
var idx = Array.IndexOf(items, item, 0, count);
if (idx == -1) {
return -1;
}
idx -= origin;
if (idx < 0) {
idx += count;
}
return idx;
}
public void Insert(int index, T item) {
// if (count == capacity) {
// throw new InvalidOperationException("Buffer at maximum capacity");
// }
if (index > count) {
throw new IndexOutOfRangeException("Index exceeds Count");
}
if (index == 0 && count == capacity) {
// This is a FIFO buffer. At capacity, inserting an element at the front is a
// no-op.
return;
}
if (items.Length == count) {
// Resize buffer (reset origin to 0 in the process)
var newLength = Math.Min(items.Length * 2, capacity);
var newItems = newLength == items.Length ? items : new T[newLength];
if (index >= count - origin) {
// Copy items[origin:end] to newItems[0:]
Array.Copy(items, origin, newItems, 0, count - origin);
// Copy items[0:index-count-origin] to newItems[count-origin:]
Array.Copy(items, 0, newItems, count - origin, index - (count - origin));
// Copy items[index-count-origin:origin] to newItems[index+1:]
Array.Copy(items, index - (count - origin), newItems, index + 1, count - index);
} else if (index == 0) {
// Copy items[origin:end] to newItems[1:]
Array.Copy(items, origin, newItems, 1, count - origin);
// Copy items[0:origin] to newItems[1 + count - origin:]
Array.Copy(items, 0, newItems, 1 + count - origin, origin);
} else {
// Copy items[origin:idx] to newItems[0:]
Array.Copy(items, origin + 1, newItems, 0, index);
// Copy items[idx:] to newItems[index+1:]
Array.Copy(items, origin + 1 + index, newItems, index + 1, count - origin - index - 1);
// Copy items[0:origin] to newItems[index+count-idx]
Array.Copy(items, 0, newItems, count - origin, origin);
}
newItems[index] = item;
items = newItems;
origin = 0;
} else {
var idx = origin + index;
if (idx >= count) {
idx -= count;
}
var lastIdx = origin - 1;
if (lastIdx < 0) {
lastIdx += count;
}
var lastItem = items[lastIdx];
Array.Copy(items, idx, items, idx + 1, count - idx - origin - 1);
Array.Copy(items, 0, items, 0, idx + origin);
items[lastIdx] = lastItem;
}
}
public bool Remove(T item) {
var idx = Array.IndexOf(items, item, 0, count);
if (idx == -1) {
return false;
}
if (idx < origin) {
origin--;
}
ArrayHelper.remove_at(ref items, ref count, idx);
return true;
}
public void RemoveAt(int index) {
ExceptionAssert.Index.IsValid(index, count);
index += origin;
if (index >= count) {
index -= count;
origin--;
}
ArrayHelper.remove_at(ref items, ref count, index);
}
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
int getOffsetIndex(int index, bool canInsert = false) {
ExceptionAssert.Index.IsValid(index, count, canInsert);
index += origin;
if (index > count || (index == count && !canInsert)) {
index -= count;
}
return index;
}
}
@@ -0,0 +1,88 @@
#nullable enable
namespace Spark.Test;
using bts.collections;
using bts.test;
using Spark.Core.Collections;
using System.Collections.Generic;
using System.Linq;
[TestGroup]
public class CircularBufferTest {
[Test]
public void TestAdd() {
int length = 10;
var nums = Enumerable.Range(0, length).ToList();
var buffer = new CircularBuffer<int>(length);
buffer.AddRange(nums);
Assert.That(buffer.SequenceEqual(nums));
for (int i = 0; i < length; i++) {
buffer.Add(length + i);
Assert.That(buffer.SequenceEqual(Enumerable.Range(i + 1, length)));
}
}
[Test]
public void TestInsert() {
int len = 10;
var nums = Enumerable.Range(0, len).ToList();
const int INS_VAL = -1;
for (int i = 1; i < len; i++) {
var buffer = new CircularBuffer<int>(len);
buffer.AddRange(nums);
buffer.Insert(i, INS_VAL);
var expected = Enumerable.Range(1, i).Append(INS_VAL).Concat(Enumerable.Range(i + 1, len - i - 1));
Assert.That(buffer.SequenceEqual(expected));
}
}
[Test]
public void TestRemove() {
const int LEN = 10;
const int N_EXTRA = LEN / 2;
var nums = Enumerable.Range(0, LEN).ToList();
for (int i = 0; i < LEN; i++) {
var buffer = new CircularBuffer<int>(LEN);
buffer.AddRange(nums);
buffer.RemoveAt(i);
var expected = Enumerable.Range(0, i).Concat(Enumerable.Range(i + 1, LEN - i - 1));
Assert.That(buffer.SequenceEqual(expected));
buffer.AddRange(Enumerable.Range(LEN, N_EXTRA));
buffer.RemoveAt(i);
// We added N_EXTRA elements. The original range began at x=0, so now it begins at
// x=N_EXTRA (CircularBuffer is FIFO). Before that, we removed the element at i. If
// i < N_EXTRA, the resultant gap will have been overwritten by the new elements.
// Otherwise, the gap will still be in the buffer, and the range will be discontinuous.
if (i < N_EXTRA) {
expected = Enumerable.Range(N_EXTRA, i).Concat(Enumerable.Range(N_EXTRA + i + 1, LEN - i - 1));
Assert.That(buffer.SequenceEqual(expected));
} else {
expected = Enumerable.Range(N_EXTRA - 1, i - N_EXTRA + 1)
.Concat(Enumerable.Range(i + 1, N_EXTRA - 1))
.Concat(Enumerable.Range(i + 1 + N_EXTRA, LEN - 1 - i));
Assert.That(buffer.SequenceEqual(expected));
}
}
}
[Test]
public void TestIndexOf() {
int length = 10;
var nums = Enumerable.Range(0, length).ToList();
var buffer = new CircularBuffer<int>(length);
buffer.AddRange(nums);
for (int i = 0; i < length; i++) {
Assert.That(buffer.IndexOf(i) == i);
}
for (int i = 0; i < length; i++) {
buffer.Add(length + i);
// Assert IndexOf works for the first, last, and middle item (if it
// works for those, it's safe to assume it'll work for the rest).
Assert.That(buffer.IndexOf(i + 1) == 0);
Assert.That(buffer.IndexOf(i + length / 2) == length / 2 - 1);
Assert.That(buffer.IndexOf(i + length) == length - 1);
}
}
}