Guest User

Untitled

a guest
May 20th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. namespace Christina.Collections
  7. {
  8. public sealed class CircularBuffer<T> : IList<T>
  9. {
  10. public int Capacity { get; }
  11.  
  12. public bool IsReadOnly => false;
  13.  
  14. public int Count => _buffer.Count;
  15.  
  16. private IList<T> _buffer;
  17.  
  18. public CircularBuffer(int capacity)
  19. {
  20. if (capacity <= 0)
  21. throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be a positive integer.");
  22.  
  23. Capacity = capacity;
  24. _buffer = new List<T>(capacity + 1);
  25. }
  26.  
  27. public CircularBuffer(IEnumerable<T> collection)
  28. {
  29. Capacity = collection.Count();
  30.  
  31. if (Capacity <= 0)
  32. throw new ArgumentOutOfRangeException(nameof(collection), "Collection must contain at least one item.");
  33.  
  34. _buffer = new List<T>(collection);
  35. }
  36.  
  37. public CircularBuffer(int capacity, IEnumerable<T> collection)
  38. {
  39. if (capacity <= 0)
  40. throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be a positive integer.");
  41.  
  42. if (capacity < collection.Count())
  43. throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity mustn't be smaller than the amount of items in the collection.");
  44.  
  45. Capacity = capacity;
  46. var list = new List<T>(capacity);
  47. list.AddRange(collection);
  48. _buffer = list;
  49. }
  50.  
  51. public T this[int index]
  52. {
  53. get => _buffer[index];
  54. set => _buffer[index] = value;
  55. }
  56.  
  57. private void AddInternal(int index, T item)
  58. {
  59. _buffer.Insert(index, item);
  60.  
  61. if (Count > Capacity)
  62. _buffer.RemoveAt(Count - 1);
  63. }
  64.  
  65. public void Add(T item)
  66. => AddInternal(0, item);
  67.  
  68. public void Clear()
  69. => _buffer.Clear();
  70.  
  71. public bool Contains(T item)
  72. => _buffer.Contains(item);
  73.  
  74. public void CopyTo(T[] array, int arrayIndex)
  75. => _buffer.CopyTo(array, arrayIndex);
  76.  
  77. public int IndexOf(T item)
  78. => _buffer.IndexOf(item);
  79.  
  80. public void Insert(int index, T item)
  81. => AddInternal(index, item);
  82.  
  83. public bool Remove(T item)
  84. => _buffer.Remove(item);
  85.  
  86. public void RemoveAt(int index)
  87. => _buffer.RemoveAt(index);
  88.  
  89. public IEnumerator<T> GetEnumerator()
  90. => _buffer.ToList().GetEnumerator();
  91.  
  92. IEnumerator IEnumerable.GetEnumerator()
  93. => GetEnumerator();
  94. }
  95. }
Add Comment
Please, Sign In to add comment