embkernel
 All Classes Functions Variables Typedefs Groups Pages
LibFifo.hpp
1 //------------------------------------------------------------------------------
2 //This file is part of milkLib.
3 //See license.txt for the full license governing this code.
4 //------------------------------------------------------------------------------
5 
6 #ifndef LIB_FIFO_HPP_
7 #define LIB_FIFO_HPP_
8 
9 template<class T, int N>
10 class LibFifo {
11 public:
12  LibFifo();
13  ~LibFifo();
14 
15  bool give(T& item);
16  bool take(T& item);
17 
18 private:
19  T mArray[N];
20 
21  int mCurrentCount;
22  int mIdxIn;
23  int mIdxOut;
24 };
25 
26 template<class T, int N>
27 LibFifo<T, N>::LibFifo() {
28  mCurrentCount = 0;
29  mIdxIn = 0;
30  mIdxOut = 0;
31 }
32 
33 template<class T, int N>
34 LibFifo<T, N>::~LibFifo() {
35 
36 }
37 
38 template<class T, int N>
39 bool LibFifo<T, N>::give(T& item) {
40  if (mCurrentCount >= N) {
41  return false;
42  }
43  mArray[mIdxIn++] = item;
44  if (mIdxIn >= N) {
45  mIdxIn = 0;
46  }
47  mCurrentCount++;
48  return true;
49 }
50 
51 template<class T, int N>
52 bool LibFifo<T, N>::take(T& item) {
53  if (mCurrentCount <= 0) {
54  return false;
55  }
56  item = mArray[mIdxOut++];
57  if (mIdxOut >= N) {
58  mIdxOut = 0;
59  }
60  mCurrentCount--;
61  return true;
62 }
63 
64 #endif /* LIB_FIFO_HPP_ */