-
-
Save INTERNALINTERFERENCE/631cb0d715de0dd06806c5992d983990 to your computer and use it in GitHub Desktop.
FixedSizeQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FixedSizeQueue<T> | |
: IReadOnlyCollection<T> | |
{ | |
private readonly T[] _items; | |
private int _tail; | |
public FixedSizeQueue(int capacity) | |
{ | |
if (capacity <= 0) | |
throw new ArgumentOutOfRangeException(nameof(capacity)); | |
_items = new T[capacity]; | |
} | |
public FixedSizeQueue( | |
IEnumerable<T> collection, | |
int capacity) | |
{ | |
if (collection == null) | |
throw new ArgumentNullException(nameof(collection)); | |
_items = new T[capacity]; | |
foreach (var item in collection) | |
Push(item); | |
} | |
public int Count { get; private set; } | |
public bool IsEmpty => Count == 0; | |
private int Capacity => _items.Length; | |
private T this[int index] => index >= Count | |
? throw new ArgumentOutOfRangeException(nameof(index)) | |
: _items[(_tail + index) % Capacity]; | |
public void Clear() | |
{ | |
Array.Clear(_items, 0, Count); | |
Count = 0; | |
_tail = 0; | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
for (var i = 0; i < Count; i++) | |
yield return this[i]; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
=> GetEnumerator(); | |
public T Peek() | |
{ | |
if ( Count == 0 ) | |
throw new InvalidOperationException(); | |
return _items[(_tail + Count) % Capacity]; | |
} | |
public void Push(T item) | |
{ | |
_items[(_tail + Count) % Capacity] = item; | |
if (Count < Capacity) | |
Count++; | |
else | |
_tail = (_tail + 1) % Capacity; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment