FILO.h
Go to the documentation of this file.
1 /* $Id: FILO.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 FILO / stack class, mostly for primitive types but can be used
9 || | with classes if assignment to int is allowed.
10 || | This FILO 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 #pragma once
20 
21 #include "Countable.h"
22 
23 template <typename T, int rawSize> class FILO : public Countable<T>
24 {
25 public:
26  const int size; // speculative feature, in case it's needed
27 
28  FILO();
29 
30  T pop(); // get next element
31  bool push(T element); // add an element
32  T peek() const; // get the next element without releasing it from the FILO
33  void flush(); // reset to default state
34 
35  bool empty() const
36  {
37  return numberOfElements == 0;
38  }
39 
40  bool full() const
41  {
42  return numberOfElements >= rawSize;
43  }
44 
45  // how many elements are currently in the FILO?
46  unsigned int count() const override
47  {
48  return numberOfElements;
49  }
50 
51  const T& operator[](unsigned int index) const override
52  {
53  return raw[index]; /* unsafe */
54  }
55 
56  T& operator[](unsigned int index) override
57  {
58  return raw[index]; /* unsafe */
59  }
60 
61 private:
62  volatile int numberOfElements;
63  int nextIn;
64  int nextOut;
65  T raw[rawSize];
66 };
67 
68 template <typename T, int rawSize> FILO<T, rawSize>::FILO() : size(rawSize)
69 {
70  flush();
71 }
72 
73 template <typename T, int rawSize> bool FILO<T, rawSize>::push(T element)
74 {
75  if(count() >= rawSize) {
76  return false;
77  }
78  raw[numberOfElements++] = element;
79  return true;
80 }
81 
82 template <typename T, int rawSize> T FILO<T, rawSize>::pop()
83 {
84  if(numberOfElements > 0) {
85  return raw[--numberOfElements];
86  }
87  return raw[0];
88 }
89 
90 template <typename T, int rawSize> T FILO<T, rawSize>::peek() const
91 {
92  if(numberOfElements > 0) {
93  return raw[numberOfElements - 1];
94  }
95  return raw[0];
96 }
97 
98 template <typename T, int rawSize> void FILO<T, rawSize>::flush()
99 {
100  nextIn = nextOut = numberOfElements = 0;
101 }
Definition: Countable.h:20
Definition: FILO.h:24
unsigned int count() const override
Definition: FILO.h:46
bool push(T element)
Definition: FILO.h:73
T peek() const
Definition: FILO.h:90
const int size
Definition: FILO.h:26
void flush()
Definition: FILO.h:98
FILO()
Definition: FILO.h:68
const T & operator[](unsigned int index) const override
Definition: FILO.h:51
bool empty() const
Definition: FILO.h:35
T pop()
Definition: FILO.h:82
bool full() const
Definition: FILO.h:40
T & operator[](unsigned int index) override
Definition: FILO.h:56