92 lines
2.9 KiB
C#
92 lines
2.9 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Collections.Immutable;
|
|
using System.Data;
|
|
using System.Linq;
|
|
|
|
using BCG;
|
|
|
|
using bts.collections;
|
|
|
|
using Bts.DataStreamCore;
|
|
|
|
namespace bts {
|
|
public class CircularBufferTable : IBlueRowCollection {
|
|
readonly ImmutableList<IBlueRow> orderedRows;
|
|
readonly ImmutableDictionary<int, IBlueRow> rowIndex;
|
|
private int _buffer_sz;
|
|
public CircularBufferTable(IBlueTableSchema schema, int buffer_sz)
|
|
: this(schema, buffer_sz, ImmutableList<IBlueRow>.Empty, ImmutableDictionary<int, IBlueRow>.Empty) { }
|
|
|
|
CircularBufferTable(IBlueTableSchema schema, int bufferSize, ImmutableList<IBlueRow> orderedRows, ImmutableDictionary<int, IBlueRow> rowIndex) {
|
|
this.schema = schema;
|
|
_buffer_sz = bufferSize;
|
|
this.orderedRows = orderedRows;
|
|
this.rowIndex = rowIndex;
|
|
}
|
|
|
|
public CircularBufferTable Add(IBlueRow row) =>
|
|
Add(row, out _);
|
|
|
|
// returns the row that might need to be deleted to keep
|
|
// the circular buffer intact
|
|
public CircularBufferTable Add(IBlueRow row, out IBlueRow oldRow) {
|
|
int id = row.Id();
|
|
var rowIndexBd = rowIndex.ToBuilder();
|
|
var orderedRowsBd = orderedRows.ToBuilder();
|
|
if (rowIndexBd.TryGetValue(id, out oldRow)) {
|
|
Log.assert(orderedRowsBd.RemoveFirst(r => r.Id() == id));
|
|
} else if (rowIndexBd.Count > _buffer_sz) {
|
|
oldRow = orderedRowsBd[0];
|
|
rowIndexBd.Remove(oldRow.Id());
|
|
orderedRowsBd.RemoveAt(0);
|
|
}
|
|
rowIndexBd[id] = row;
|
|
orderedRowsBd.Add(row);
|
|
return new(schema, _buffer_sz, orderedRowsBd.ToImmutable(), rowIndexBd.ToImmutable());
|
|
}
|
|
|
|
public IBlueRow this[int id] {
|
|
get {
|
|
return orderedRows[id];
|
|
}
|
|
}
|
|
public IBlueTableSchema schema { get; }
|
|
public bool containsID(int id) {
|
|
return rowIndex.ContainsKey(id);
|
|
}
|
|
|
|
public void CopyTo(Array array, int index) {
|
|
foreach (var row in orderedRows) {
|
|
array.SetValue(row, index++);
|
|
}
|
|
}
|
|
public int Count => rowIndex.Count;
|
|
public bool IsSynchronized { get { return false; } }
|
|
public object SyncRoot { get { return this; } }
|
|
public IEnumerator<IBlueRow> GetEnumerator() =>
|
|
orderedRows.GetEnumerator();
|
|
|
|
public IList<object> GetColumn(int index) =>
|
|
orderedRows.WrapSelector(r => r[index], null);
|
|
|
|
public IBlueRow GetRow(int index) =>
|
|
orderedRows[index];
|
|
|
|
public int IndexOf(IBlueRow item) {
|
|
int id = item.Id();
|
|
if (rowIndex.TryGetValue(id, out var row) && BlueRowEqualityComparer.Equals(item, row)) {
|
|
int i = 0;
|
|
foreach (var r in orderedRows) {
|
|
if (r.Id() == id) {
|
|
return i;
|
|
}
|
|
i++;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
}
|
|
}
|