CircularBuffer.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // © Copyright Henrik Ravn 2004
  3. //
  4. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. using System;
  8. using System.Diagnostics;
  9. namespace DotZLib
  10. {
  11. /// <summary>
  12. /// This class implements a circular buffer
  13. /// </summary>
  14. internal class CircularBuffer
  15. {
  16. #region Private data
  17. private int _capacity;
  18. private int _head;
  19. private int _tail;
  20. private int _size;
  21. private byte[] _buffer;
  22. #endregion
  23. public CircularBuffer(int capacity)
  24. {
  25. Debug.Assert( capacity > 0 );
  26. _buffer = new byte[capacity];
  27. _capacity = capacity;
  28. _head = 0;
  29. _tail = 0;
  30. _size = 0;
  31. }
  32. public int Size { get { return _size; } }
  33. public int Put(byte[] source, int offset, int count)
  34. {
  35. Debug.Assert( count > 0 );
  36. int trueCount = Math.Min(count, _capacity - Size);
  37. for (int i = 0; i < trueCount; ++i)
  38. _buffer[(_tail+i) % _capacity] = source[offset+i];
  39. _tail += trueCount;
  40. _tail %= _capacity;
  41. _size += trueCount;
  42. return trueCount;
  43. }
  44. public bool Put(byte b)
  45. {
  46. if (Size == _capacity) // no room
  47. return false;
  48. _buffer[_tail++] = b;
  49. _tail %= _capacity;
  50. ++_size;
  51. return true;
  52. }
  53. public int Get(byte[] destination, int offset, int count)
  54. {
  55. int trueCount = Math.Min(count,Size);
  56. for (int i = 0; i < trueCount; ++i)
  57. destination[offset + i] = _buffer[(_head+i) % _capacity];
  58. _head += trueCount;
  59. _head %= _capacity;
  60. _size -= trueCount;
  61. return trueCount;
  62. }
  63. public int Get()
  64. {
  65. if (Size == 0)
  66. return -1;
  67. int result = (int)_buffer[_head++ % _capacity];
  68. --_size;
  69. return result;
  70. }
  71. }
  72. }