CircularBuffer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. namespace BestHTTP.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 = new System.Text.StringBuilder("[");
  47. int idx = this.startIdx;
  48. while (idx != this.endIdx)
  49. {
  50. sb.Append(this.buffer[idx].ToString());
  51. idx = (idx + 1) % this.Capacity;
  52. if (idx != this.endIdx)
  53. sb.Append("; ");
  54. }
  55. sb.Append("]");
  56. return sb.ToString();
  57. }
  58. }
  59. }