CircularBuffer.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 T this[int idx]
  9. {
  10. get
  11. {
  12. int realIdx = (this.startIdx + idx) % this.Capacity;
  13. return this.buffer[realIdx];
  14. }
  15. set
  16. {
  17. int realIdx = (this.startIdx + idx) % this.Capacity;
  18. this.buffer[realIdx] = value;
  19. }
  20. }
  21. private T[] buffer;
  22. private int startIdx;
  23. private int endIdx;
  24. public CircularBuffer(int capacity)
  25. {
  26. this.Capacity = capacity;
  27. }
  28. public void Add(T element)
  29. {
  30. if (this.buffer == null)
  31. this.buffer = new T[this.Capacity];
  32. this.buffer[this.endIdx] = element;
  33. this.endIdx = (this.endIdx + 1) % this.Capacity;
  34. if (this.endIdx == this.startIdx)
  35. this.startIdx = (this.startIdx + 1) % this.Capacity;
  36. this.Count = Math.Min(this.Count + 1, this.Capacity);
  37. }
  38. public void Clear()
  39. {
  40. this.startIdx = this.endIdx = 0;
  41. }
  42. }
  43. }