sharp-extensions/HistoryValue.cs

102 lines
1.6 KiB
C#

using System;
using System.Security.Policy;
using System.Linq;
namespace sharp.extensions
{
public class HistoryValue<T>
{
T[] values;
int p;
public HistoryValue()
{
this.values = new T[0];
this.p = 0;
}
public HistoryValue(int len)
{
this.values = new T[len];
}
public void Add(T value)
{
this.p = (++this.p) % this.values.Length;
this.values[p] = value;
}
public T this[int i]
{
get
{
if (i < 0)
{
i += this.values.Length;
}
if ((i < 0) || (i >= this.values.Length))
{
throw new IndexOutOfRangeException();
}
i += p;
i %= this.values.Length;
return this.values[i];
}
set
{
if (i < 0)
{
i += this.values.Length;
}
if ((i < 0) || (i >= this.values.Length))
{
throw new IndexOutOfRangeException();
}
i += p;
i %= this.values.Length;
this.values[i] = value;
}
}
public int Count {
get { return this.values.Length; }
}
public T[] History {
get {
T[] pre, post;
if (p == this.values.Length-1){
return this.values.Segment<T>(0);
} else {
pre = this.values.Segment<T>(p + 1);
post = this.values.Segment<T>(0, p + 1);
return pre.Combine<T>(post);
}
}
set {
this.values = value.Segment<T>(0);
this.p = this.values.Length - 1;
}
}
public HistoryValue<T> Clone(){
HistoryValue<T> clone = new HistoryValue<T>();
clone.p = this.p;
clone.values = this.values.Segment<T>(0);
return clone;
}
public static HistoryValue<T> operator +(HistoryValue<T> hvalue,T value){
hvalue.Add(value);
return hvalue;
}
}
}