-
Notifications
You must be signed in to change notification settings - Fork 968
/
RingBuffer.cs
572 lines (472 loc) · 10 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Define this to use simple synchronisation rather than events.
// They are about the same in terms of speed.
#define SimpleSynch
using NUnit.Framework;
using System;
using System.Threading;
namespace ICSharpCode.SharpZipLib.Tests.TestSupport
{
/// <summary>
/// A fixed size buffer of bytes. Both reading and writing are supported.
/// Reading from an empty buffer will wait until data is written. Writing to a full buffer
/// will wait until data is read.
/// </summary>
public class ReadWriteRingBuffer
{
#region Constructors
/// <summary>
/// Create a new RingBuffer with a specified size.
/// </summary>
/// <param name="size">The size of the ring buffer to create.</param>
public ReadWriteRingBuffer(int size, CancellationToken? token = null)
{
if (size <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
array_ = new byte[size];
lockObject_ = new object();
token_ = token;
#if SimpleSynch
waitSpan_ = TimeSpan.FromMilliseconds(1);
#else
notEmptyEvent_ = new ManualResetEvent(false);
notFullEvent_ = new ManualResetEvent(true);
#endif
}
#endregion Constructors
/// <summary>
/// Clear the buffer contents.
/// </summary>
public void Clear()
{
tail_ = 0;
head_ = 0;
count_ = 0;
Array.Clear(array_, 0, array_.Length);
#if !SimpleSynch
notFullEvent_.Set();
notEmptyEvent_.Reset();
#endif
}
/// <summary>
/// Close the buffer for writing.
/// </summary>
/// <remarks>A Read when the buffer is closed and there is no data will return -1.</remarks>
public void Close()
{
isClosed_ = true;
#if !SimpleSynch
notEmptyEvent_.Set();
#endif
}
/// <summary>
/// Write adds a byte to the head of the RingBuffer.
/// </summary>
/// <param name="value">The value to add.</param>
public void WriteByte(byte value)
{
if (isClosed_)
{
throw new ApplicationException("Buffer is closed");
}
#if SimpleSynch
while (IsFull)
{
Thread.Sleep(waitSpan_);
token_?.ThrowIfCancellationRequested();
}
#else
notFullEvent_.WaitOne();
#endif
lock (lockObject_)
{
array_[head_] = value;
head_ = (head_ + 1) % array_.Length;
#if !SimpleSynch
bool setEmpty = (count_ == 0);
#endif
count_ += 1;
#if !SimpleSynch
if (IsFull)
{
notFullEvent_.Reset();
}
if (setEmpty)
{
notEmptyEvent_.Set();
}
#endif
}
bytesWritten_++;
}
public void Write(byte[] buffer, int index, int count)
{
if (isClosed_)
{
throw new ApplicationException("Buffer is closed");
}
while (count > 0)
{
#if SimpleSynch
while (IsFull)
{
Thread.Sleep(waitSpan_);
token_?.ThrowIfCancellationRequested();
}
#else
notFullEvent_.WaitOne();
#endif
// Gauranteed to not be full at this point, however readers may sill read
// from the buffer first.
lock (lockObject_)
{
int bytesToWrite = Length - Count;
if (count < bytesToWrite)
{
bytesToWrite = count;
}
#if !SimpleSynch
bool setEmpty = (count_ == 0);
#endif
while (bytesToWrite > 0)
{
array_[head_] = buffer[index];
index++;
head_ = (head_ + 1) % array_.Length;
bytesToWrite--;
bytesWritten_++;
count--;
count_++;
}
#if !SimpleSynch
if (IsFull)
{
notFullEvent_.Reset();
}
if (setEmpty)
{
notEmptyEvent_.Set();
}
#endif
}
}
}
/// <summary>
/// Read a byte from the buffer.
/// </summary>
/// <returns></returns>
public int ReadByte()
{
int result = -1;
#if SimpleSynch
while (!isClosed_ && IsEmpty)
{
Thread.Sleep(waitSpan_);
token_?.ThrowIfCancellationRequested();
}
#else
notEmptyEvent_.WaitOne();
#endif
if (!IsEmpty)
{
lock (lockObject_)
{
result = array_[tail_];
tail_ = (tail_ + 1) % array_.Length;
#if !SimpleSynch
bool setFull = IsFull;
#endif
count_ -= 1;
#if !SimpleSynch
if (!isClosed_ && (count_ == 0))
{
notEmptyEvent_.Reset();
}
if (setFull)
{
notFullEvent_.Set();
}
#endif
}
}
bytesRead_++;
return result;
}
public int Read(byte[] buffer, int index, int count)
{
int result = 0;
while (count > 0)
{
#if SimpleSynch
while (!isClosed_ && IsEmpty)
{
Thread.Sleep(waitSpan_);
token_?.ThrowIfCancellationRequested();
}
#else
notEmptyEvent_.WaitOne();
#endif
if (IsEmpty)
{
count = 0;
}
else
{
lock (lockObject_)
{
int toRead = Count;
if (toRead > count)
{
toRead = count;
}
result += toRead;
#if !SimpleSynch
bool setFull = IsFull;
#endif
while (toRead > 0)
{
buffer[index] = array_[tail_];
index++;
tail_ = (tail_ + 1) % array_.Length;
count--;
count_--;
toRead--;
bytesRead_++;
}
#if !SimpleSynch
if (!isClosed_ && (count_ == 0))
{
notEmptyEvent_.Reset();
}
if (setFull)
{
notFullEvent_.Set();
}
#endif
}
}
}
return result;
}
#region Properties
/// <summary>
/// Gets a value indicating wether the buffer is empty or not.
/// </summary>
public bool IsEmpty
{
get { return count_ == 0; }
}
public bool IsFull
{
get
{
return (count_ == array_.Length);
}
}
public bool IsClosed
{
get { return isClosed_; }
}
/// <summary>
/// Gets the number of elements in the buffer.
/// </summary>
public int Count
{
get
{
return count_;
}
}
public int Length
{
get { return array_.Length; }
}
public long BytesWritten
{
get { return bytesWritten_; }
}
public long BytesRead
{
get { return bytesRead_; }
}
/// <summary>
/// Indexer - Get an element from the tail of the RingBuffer.
/// </summary>
public byte this[int index]
{
get
{
if ((index < 0) || (index >= array_.Length))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return array_[(tail_ + index) % array_.Length];
}
}
#endregion Properties
#region Instance Variables
/// <summary>
/// Flag indicating the buffer is closed.
/// </summary>
private bool isClosed_;
/// <summary>
/// Index for the head of the buffer.
/// </summary>
/// <remarks>Its the index of the next byte to be <see cref="Write">written</see>.</remarks>
private int head_;
/// <summary>
/// Index for the tail of the buffer.
/// </summary>
/// <remarks>Its the index of the next byte to be <see cref="Read">written</see>.</remarks>
private int tail_;
/// <summary>
/// The total number of elements added to the buffer.
/// </summary>
private int count_;
/// <summary>
/// Storage for the ring buffer contents.
/// </summary>
private byte[] array_;
private long bytesWritten_;
private long bytesRead_;
private object lockObject_;
private CancellationToken? token_;
private TimeSpan waitSpan_;
#if !SimpleSynch
ManualResetEvent notEmptyEvent_;
ManualResetEvent notFullEvent_;
#endif
#endregion Instance Variables
}
[TestFixture]
[Explicit("Meta tests (for ringbuffer)")]
public class ExerciseBuffer
{
[Test]
public void Basic()
{
const int Size = 64;
buffer_ = new ReadWriteRingBuffer(Size);
Assert.IsFalse(buffer_.IsFull);
Assert.IsTrue(buffer_.IsEmpty);
buffer_.WriteByte(1);
Assert.IsFalse(buffer_.IsFull);
Assert.IsFalse(buffer_.IsEmpty);
Assert.AreEqual(1, buffer_.Count);
Assert.AreEqual(1, buffer_.ReadByte());
Assert.IsFalse(buffer_.IsFull);
Assert.IsTrue(buffer_.IsEmpty);
for (int i = 0; i < buffer_.Length; ++i)
{
buffer_.WriteByte(unchecked((byte)(i & 0xff)));
}
Assert.IsTrue(buffer_.IsFull);
Assert.IsFalse(buffer_.IsEmpty);
buffer_.Close();
Assert.IsTrue(buffer_.IsClosed);
bool caught = false;
try
{
buffer_.WriteByte(1);
}
catch
{
caught = true;
}
Assert.IsTrue(caught);
int count = Size;
int expected = 0;
while (count != 0)
{
Assert.AreEqual(count, buffer_.Count);
Assert.AreEqual(expected, buffer_.ReadByte());
count--;
expected = (expected + 1) & 0xff;
}
Assert.IsTrue(buffer_.IsEmpty);
Assert.AreEqual(-1, buffer_.ReadByte());
}
[Test]
public void Buffered()
{
const int Size = 64;
buffer_ = new ReadWriteRingBuffer(Size);
byte[] writeBuffer = new byte[16];
for (int i = 0; i < 16; ++i)
{
writeBuffer[i] = (byte)i;
}
buffer_.Write(writeBuffer, 0, 3);
Assert.AreEqual(3, buffer_.Count);
byte[] readBuffer = new byte[16];
Assert.AreEqual(3, buffer_.Read(readBuffer, 0, 3));
for (int i = 0; i < 3; ++i)
{
Assert.AreEqual(i, readBuffer[i]);
}
}
[Test]
public void Threaded()
{
buffer_ = new ReadWriteRingBuffer(8);
readTarget_ = writeTarget_ = 16384;
var reader = new Thread(Reader);
reader.Start();
var writer = new Thread(Writer);
writer.Start();
writer.Join();
reader.Join();
}
private void Reader()
{
var r = new Random(Utils.DefaultSeed);
byte nextValue = 0;
while (readTarget_ > 0)
{
int thisTime = r.Next(16);
if (thisTime > readTarget_)
{
thisTime = readTarget_;
}
while (thisTime > 0)
{
int readValue = buffer_.ReadByte();
Assert.AreEqual(nextValue, readValue);
nextValue = (byte)((nextValue + 1) & 0xff);
thisTime--;
readTarget_--;
}
Thread.Sleep(r.Next(10));
}
int last = buffer_.ReadByte();
Assert.AreEqual(-1, last);
Assert.IsTrue(buffer_.IsClosed);
}
private void Writer()
{
var r = new Random(Utils.DefaultSeed);
byte nextValue = 0;
while (writeTarget_ > 0)
{
int thisTime = r.Next(16);
if (thisTime > writeTarget_)
{
thisTime = writeTarget_;
}
while (thisTime > 0)
{
buffer_.WriteByte(nextValue);
nextValue = (byte)((nextValue + 1) & 0xff);
thisTime--;
writeTarget_--;
}
Thread.Sleep(r.Next(10));
}
buffer_.Close();
}
private int readTarget_;
private int writeTarget_;
private ReadWriteRingBuffer buffer_;
}
}