-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRingBuffer.cs
107 lines (92 loc) · 2.74 KB
/
RingBuffer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace KCB2
{
public class RingBuffer<T> : IEnumerable<T>
{
/// <summary>
/// データを覚えておく配列
/// </summary>
private T[] _buffer;
/// <summary>
/// 最新のデータが有る場所
/// </summary>
private int _pos = -1;
/// <summary>
/// Enum中にアイテム追加されたことを検出
/// </summary>
private long _revision = 0 ;
/// <summary>
/// リング長
/// </summary>
public int Capacity { get; private set; }
/// <summary>
/// リング中に存在するデータ数。最大Capacityまで
/// </summary>
private int _avail = 0;
/// <summary>
/// データ末尾。iter用
/// </summary>
private int _tail = 0;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="capacity">収納可能な</param>
public RingBuffer(int capacity)
{
_buffer = new T[capacity];
Capacity = capacity;
}
/// <summary>
/// リングにアイテムを追加
/// </summary>
/// <param name="item"></param>
public void Add(T item)
{
int npos = (_pos + 1) % Capacity;
_buffer[npos] = item;
_pos = npos;
if (_avail < Capacity)
_avail++;
else
_tail = (_tail + 1) % Capacity;
_revision++;
}
/// <summary>
/// バッファをクリア
/// </summary>
public void Clear()
{
for (int i = 0; i < Capacity; i++)
_buffer[i] = default(T);
_pos = -1;
_avail = 0;
_tail = 0;
_revision++;
}
/// <summary>
/// 中身を列挙する
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
long revision = _revision;
for (int i = 0; i < _avail ; i++)
{
if (revision != _revision)
throw new InvalidOperationException("列挙中にデータが変更された");
int index = (_tail + i ) % Capacity;
yield return _buffer[index];
}
}
/// <summary>
/// 非GenericなGetEnumeratorの実装
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ return this.GetEnumerator(); }
}
}