using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SKMC.Api.Common.Types
{
///
/// 包含时间戳的数据集
///
public class TimestampSet
{
private readonly int capacity;
private readonly (long Ticks, int Value)[] buffer;
private int currentIndex;
private long oldestTicks;
private readonly object _lock = new object();
public TimestampSet(int capacity)
{
this.capacity = capacity;
buffer = new (long, int)[capacity];
currentIndex = 0;
oldestTicks = long.MaxValue;
}
///
/// 添加与时间戳相关的数据
///
///
///
public void Add(long ticks, int value)
{
lock (_lock)
{
buffer[currentIndex] = (ticks, value);
currentIndex = (currentIndex + 1) % capacity;
if (currentIndex == 0)
{
oldestTicks = buffer[currentIndex].Ticks;
}
}
}
///
/// 添加当前"时间戳"的数据, 该"时间戳"为简化版: ticks/10000
///
///
public void Add(int value)
{
Add(DateTime.Now.Ticks / 10000, value);
}
///
/// 获取最新的一个数值
///
///
public int Take() => (currentIndex > 0) ? buffer[currentIndex - 1].Value : buffer[capacity - 1].Value;
///
/// 获取某个时间戳之后的所有数据
///
/// 该"时间戳"为简化版: ticks/10000
///
public List GetDataAfter(long ticks)
{
List result = new List();
lock (_lock)
{
for (int i = 0; i < capacity; i++)
{
var entry = buffer[i];
if (entry.Ticks > ticks)
{
result.Add(entry.Value);
}
}
}
return result;
}
}
}