--- /dev/null
+//\r
+// © Copyright Henrik Ravn 2004\r
+//\r
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0. \r
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r
+//\r
+\r
+using System;\r
+using System.Diagnostics;\r
+\r
+namespace DotZLib\r
+{\r
+\r
+ /// <summary>\r
+ /// This class implements a circular buffer\r
+ /// </summary>\r
+ internal class CircularBuffer\r
+ {\r
+ #region Private data\r
+ private int _capacity;\r
+ private int _head;\r
+ private int _tail;\r
+ private int _size;\r
+ private byte[] _buffer;\r
+ #endregion\r
+\r
+ public CircularBuffer(int capacity)\r
+ { \r
+ Debug.Assert( capacity > 0 );\r
+ _buffer = new byte[capacity];\r
+ _capacity = capacity;\r
+ _head = 0;\r
+ _tail = 0;\r
+ _size = 0;\r
+ }\r
+\r
+ public int Size { get { return _size; } }\r
+\r
+ public int Put(byte[] source, int offset, int count)\r
+ {\r
+ Debug.Assert( count > 0 );\r
+ int trueCount = Math.Min(count, _capacity - Size);\r
+ for (int i = 0; i < trueCount; ++i)\r
+ _buffer[(_tail+i) % _capacity] = source[offset+i];\r
+ _tail += trueCount;\r
+ _tail %= _capacity;\r
+ _size += trueCount;\r
+ return trueCount;\r
+ }\r
+\r
+ public bool Put(byte b)\r
+ {\r
+ if (Size == _capacity) // no room\r
+ return false;\r
+ _buffer[_tail++] = b;\r
+ _tail %= _capacity;\r
+ ++_size;\r
+ return true;\r
+ }\r
+\r
+ public int Get(byte[] destination, int offset, int count)\r
+ {\r
+ int trueCount = Math.Min(count,Size);\r
+ for (int i = 0; i < trueCount; ++i)\r
+ destination[offset + i] = _buffer[(_head+i) % _capacity];\r
+ _head += trueCount;\r
+ _head %= _capacity;\r
+ _size -= trueCount;\r
+ return trueCount;\r
+ }\r
+\r
+ public int Get()\r
+ {\r
+ if (Size == 0)\r
+ return -1;\r
+\r
+ int result = (int)_buffer[_head++ % _capacity];\r
+ --_size;\r
+ return result;\r
+ }\r
+\r
+ }\r
+}\r