FIFO.h
Go to the documentation of this file.
1 /* $Id: FIFO.h 1151 2011-06-06 21:13:05Z bhagman $
2 ||
3 || @author Alexander Brevig <abrevig@wiring.org.co>
4 || @url http://wiring.org.co/
5 || @contribution Brett Hagman <bhagman@wiring.org.co>
6 ||
7 || @description
8 || | A simple FIFO class, mostly for primitive types but can be used with
9 || | classes if assignment to int is allowed.
10 || | This FIFO is not dynamic, so be sure to choose an appropriate size for it.
11 || |
12 || | Wiring Common API
13 || #
14 ||
15 || @license Please see cores/Common/License.txt.
16 ||
17 */
18 
19 #ifndef FIFO_H
20 #define FIFO_H
21 
22 #include "Countable.h"
23 
24 template<typename T, int rawSize>
25 class FIFO : public Countable<T>
26 {
27  public:
28  const int size; // speculative feature, in case it's needed
29 
30  FIFO();
31 
32  T dequeue(); // get next element
33  bool enqueue(T element); // add an element
34  T peek() const; // get the next element without releasing it from the FIFO
35  void flush(); // reset to default state
36 
37  //how many elements are currently in the FIFO?
38  unsigned int count() const override
39  {
40  return numberOfElements;
41  }
42 
43  bool full() const
44  {
45  return (count() >= rawSize);
46  }
47 
48  const T &operator[](unsigned int index) const override
49  {
50  return raw[index]; /* unsafe */
51  }
52 
53  T &operator[](unsigned int index) override
54  {
55  return raw[index]; /* unsafe */
56  }
57 
58  protected:
59  volatile int numberOfElements;
60  int nextIn;
61  int nextOut;
62  T raw[rawSize];
63 };
64 
65 template<typename T, int rawSize>
67 {
68  flush();
69 }
70 
71 template<typename T, int rawSize>
73 {
74  if (full())
75  {
76  return false;
77  }
79  raw[nextIn] = element;
80  if (++nextIn >= rawSize) // advance to next index, wrap if needed
81  nextIn = 0;
82  return true;
83 }
84 
85 template<typename T, int rawSize>
87 {
88  T item;
90  item = raw[nextOut];
91  if (++nextOut >= rawSize) // advance to next index, wrap if needed
92  nextOut = 0;
93  return item;
94 }
95 
96 template<typename T, int rawSize>
98 {
99  return raw[nextOut];
100 }
101 
102 template<typename T, int rawSize>
104 {
106 }
107 
108 #endif
109 // FIFO_H
volatile int numberOfElements
Definition: FIFO.h:59
Definition: Countable.h:20
unsigned int count() const override
Definition: FIFO.h:38
int nextOut
Definition: FIFO.h:61
const int size
Definition: FIFO.h:28
T raw[rawSize]
Definition: FIFO.h:62
FIFO()
Definition: FIFO.h:66
T dequeue()
Definition: FIFO.h:86
bool full() const
Definition: FIFO.h:43
T peek() const
Definition: FIFO.h:97
int nextIn
Definition: FIFO.h:60
T & operator[](unsigned int index) override
Definition: FIFO.h:53
bool enqueue(T element)
Definition: FIFO.h:72
Definition: FIFO.h:25
const T & operator[](unsigned int index) const override
Definition: FIFO.h:48
void flush()
Definition: FIFO.h:103