Advertisement
plaYer2k

Generic fixed-size FIFO array implementation

Apr 4th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.30 KB | None | 0 0
  1. public class FIFO<T>
  2. {
  3.     private T[] _array;
  4.     private int _offset, _storage;
  5.  
  6.     public int Length { get { return this._array.Length; }}
  7.  
  8.     public FIFO(int size)
  9.     {
  10.         this._array = new T[size];
  11.         this._offset = 0;
  12.         this._storage = 0;
  13.     }
  14.  
  15.     public T GetAt(int position, out bool checkValue)
  16.     {
  17.         checkValue = false;
  18.         if(this._storage <= position)
  19.             return default(T);
  20.  
  21.         checkValue = true;
  22.         return this._array[(this._offset + position)%this._array.Length];
  23.     }
  24.  
  25.     // Push a new value into the FIFO
  26.     // @return true if an old value got dropped in the process
  27.     public bool Push(T value)
  28.     {
  29.         bool ret = false;
  30.         this._array[(this._offset + this._storage++) % this._array.Length] = value;
  31.         if(this._storage > this._array.Length)
  32.         {
  33.             this._storage = this._array.Length;
  34.             this._offset = (this._offset + 1 ) % this._array.Length;
  35.             ret = true;
  36.         }
  37.  
  38.         return ret;
  39.     }
  40.  
  41.     // Pops the oldest value from the FIFO
  42.     // @param checkValue true if successful and false if the FIFO is empty
  43.     // @return default(T) if the FIFI is empty
  44.     public T Pop(out bool checkValue)
  45.     {
  46.         checkValue = false;
  47.         if(this._storage <= 0)
  48.             return default(T);
  49.  
  50.         checkValue = true;
  51.         T val = this._array[this._offset++];
  52.         this._offset = this._offset % this._array.Length;
  53.         this._storage--;
  54.         return val;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement