Advertisement
Guest User

FastQueue

a guest
Oct 12th, 2012
683
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. internal class FastQueue<T> where T : struct
  2. {
  3.     public T[] items;
  4.     public int mask;
  5.     public uint tail, head;
  6.  
  7.     public FastQueue(int capacity = 16)
  8.     {
  9.         capacity = 1 << (int) Math.Ceiling(Math.Log(capacity, 2)); // calculate closest power of two
  10.         items = new T[capacity];
  11.         mask = capacity - 1;
  12.         tail = head = 0;
  13.     }
  14.  
  15.     public int Count
  16.     {
  17.         get { return (int) (tail - head); }
  18.     }
  19.  
  20.     public void Enqueue(T item)
  21.     {
  22.         if (tail - head == items.Length)
  23.         {
  24.             DoubleCapacity();
  25.         }
  26.  
  27.         items[tail++ & mask] = item;
  28.     }
  29.  
  30.     public void FastEnqueue(T item)
  31.     {
  32.         items[tail++ & mask] = item;
  33.     }
  34.  
  35.     public T Dequeue()
  36.     {
  37.         return items[head++ & mask];
  38.     }
  39.  
  40.     private void DoubleCapacity()
  41.     {
  42.         var capacity = items.Length << 1;
  43.  
  44.         if ((head & mask) == 0)
  45.         {
  46.             Array.Resize(ref items, capacity);
  47.         }
  48.         else
  49.         {
  50.             int size = items.Length;
  51.             var items2 = new T[capacity];
  52.             int length = (int) (size - head & mask);
  53.             Array.Copy(items, head & mask, items2, 0, length);
  54.             Array.Copy(items, 0, items2, length, size - length);
  55.  
  56.             items = items2;
  57.             head = 0;
  58.             tail = (uint) size;
  59.         }
  60.  
  61.         mask = capacity - 1;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement