Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- namespace Christina.Collections
- {
- public sealed class CircularBuffer<T> : IList<T>
- {
- public int Capacity { get; }
- public bool IsReadOnly => false;
- public int Count => _buffer.Count;
- private IList<T> _buffer;
- public CircularBuffer(int capacity)
- {
- if (capacity <= 0)
- throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be a positive integer.");
- Capacity = capacity;
- _buffer = new List<T>(capacity + 1);
- }
- public CircularBuffer(IEnumerable<T> collection)
- {
- Capacity = collection.Count();
- if (Capacity <= 0)
- throw new ArgumentOutOfRangeException(nameof(collection), "Collection must contain at least one item.");
- _buffer = new List<T>(collection);
- }
- public CircularBuffer(int capacity, IEnumerable<T> collection)
- {
- if (capacity <= 0)
- throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be a positive integer.");
- if (capacity < collection.Count())
- throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity mustn't be smaller than the amount of items in the collection.");
- Capacity = capacity;
- var list = new List<T>(capacity);
- list.AddRange(collection);
- _buffer = list;
- }
- public T this[int index]
- {
- get => _buffer[index];
- set => _buffer[index] = value;
- }
- private void AddInternal(int index, T item)
- {
- _buffer.Insert(index, item);
- if (Count > Capacity)
- _buffer.RemoveAt(Count - 1);
- }
- public void Add(T item)
- => AddInternal(0, item);
- public void Clear()
- => _buffer.Clear();
- public bool Contains(T item)
- => _buffer.Contains(item);
- public void CopyTo(T[] array, int arrayIndex)
- => _buffer.CopyTo(array, arrayIndex);
- public int IndexOf(T item)
- => _buffer.IndexOf(item);
- public void Insert(int index, T item)
- => AddInternal(index, item);
- public bool Remove(T item)
- => _buffer.Remove(item);
- public void RemoveAt(int index)
- => _buffer.RemoveAt(index);
- public IEnumerator<T> GetEnumerator()
- => _buffer.ToList().GetEnumerator();
- IEnumerator IEnumerable.GetEnumerator()
- => GetEnumerator();
- }
- }
Add Comment
Please, Sign In to add comment