CircularBuffer.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. namespace Best.HTTP.Shared.Extensions
  3. {
  4. public sealed class CircularBuffer<T>
  5. {
  6. public int Capacity { get; private set; }
  7. public int Count { get; private set; }
  8. public int StartIdx { get { return this.startIdx; } }
  9. public int EndIdx { get { return this.endIdx; } }
  10. public T this[int idx]
  11. {
  12. get
  13. {
  14. int realIdx = (this.startIdx + idx) % this.Capacity;
  15. return this.buffer[realIdx];
  16. }
  17. set
  18. {
  19. int realIdx = (this.startIdx + idx) % this.Capacity;
  20. this.buffer[realIdx] = value;
  21. }
  22. }
  23. private T[] buffer;
  24. private int startIdx;
  25. private int endIdx;
  26. public CircularBuffer(int capacity)
  27. {
  28. this.Capacity = capacity;
  29. }
  30. public void Add(T element)
  31. {
  32. if (this.buffer == null)
  33. this.buffer = new T[this.Capacity];
  34. this.buffer[this.endIdx] = element;
  35. this.endIdx = (this.endIdx + 1) % this.Capacity;
  36. if (this.endIdx == this.startIdx)
  37. this.startIdx = (this.startIdx + 1) % this.Capacity;
  38. this.Count = Math.Min(this.Count + 1, this.Capacity);
  39. }
  40. public void Clear()
  41. {
  42. this.Count = this.startIdx = this.endIdx = 0;
  43. }
  44. public override string ToString()
  45. {
  46. var sb = PlatformSupport.Text.StringBuilderPool.Get(2);
  47. sb.Append("[");
  48. int idx = this.startIdx;
  49. while (idx != this.endIdx)
  50. {
  51. sb.Append(this.buffer[idx].ToString());
  52. idx = (idx + 1) % this.Capacity;
  53. if (idx != this.endIdx)
  54. sb.Append("; ");
  55. }
  56. sb.Append("]");
  57. return sb.ToString();
  58. }
  59. }
  60. }