InfiniTime.git

ref: fc5424cb72e477c5f1bbfaeddb5c50b851a965ae

src/utility/StaticStack.h


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <array>
#include <cstddef>

namespace Pinetime {
  namespace Utility {
    template <typename T, size_t N>
    class StaticStack {
    public:
      T Pop();
      void Push(T element);
      void Reset();
      T Top();

    private:
      std::array<T, N> elementArray;
      // Number of elements in stack, points to the next empty slot
      size_t stackPointer = 0;
    };

    // Returns random data when popping from empty array.
    template <typename T, size_t N>
    T StaticStack<T, N>::Pop() {
      if (stackPointer > 0) {
        stackPointer--;
      }
      return elementArray[stackPointer];
    }

    template <typename T, size_t N>
    void StaticStack<T, N>::Push(T element) {
      if (stackPointer < elementArray.size()) {
        elementArray[stackPointer] = element;
        stackPointer++;
      }
    }

    template <typename T, size_t N>
    void StaticStack<T, N>::Reset() {
      stackPointer = 0;
    }

    template <typename T, size_t N>
    T StaticStack<T, N>::Top() {
      return elementArray[stackPointer - 1];
    }
  }
}