Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal class FastQueue<T> where T : struct
- {
- public T[] items;
- public int mask;
- public uint tail, head;
- public FastQueue(int capacity = 16)
- {
- capacity = 1 << (int) Math.Ceiling(Math.Log(capacity, 2)); // calculate closest power of two
- items = new T[capacity];
- mask = capacity - 1;
- tail = head = 0;
- }
- public int Count
- {
- get { return (int) (tail - head); }
- }
- public void Enqueue(T item)
- {
- if (tail - head == items.Length)
- {
- DoubleCapacity();
- }
- items[tail++ & mask] = item;
- }
- public void FastEnqueue(T item)
- {
- items[tail++ & mask] = item;
- }
- public T Dequeue()
- {
- return items[head++ & mask];
- }
- private void DoubleCapacity()
- {
- var capacity = items.Length << 1;
- if ((head & mask) == 0)
- {
- Array.Resize(ref items, capacity);
- }
- else
- {
- int size = items.Length;
- var items2 = new T[capacity];
- int length = (int) (size - head & mask);
- Array.Copy(items, head & mask, items2, 0, length);
- Array.Copy(items, 0, items2, length, size - length);
- items = items2;
- head = 0;
- tail = (uint) size;
- }
- mask = capacity - 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement