Cosmetics
[opentx.git] / radio / src / fifo.h
blob9aff60f57259c2dad801ddd72998a7a28c59e536
1 /*
2 * Copyright (C) OpenTX
4 * Based on code named
5 * th9x - http://code.google.com/p/th9x
6 * er9x - http://code.google.com/p/er9x
7 * gruvin9x - http://code.google.com/p/gruvin9x
9 * License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
21 #ifndef _FIFO_H_
22 #define _FIFO_H_
24 #include <inttypes.h>
26 template <class T, int N>
27 class Fifo
29 static_assert((N > 1) & !(N & (N - 1)), "Fifo size must be a power of two!");
31 public:
32 Fifo():
33 widx(0),
34 ridx(0)
38 void clear()
40 widx = ridx = 0;
43 void push(T element)
45 uint32_t next = nextIndex(widx);
46 if (next != ridx) {
47 fifo[widx] = element;
48 widx = next;
52 void skip()
54 ridx = nextIndex(ridx);
57 bool pop(T & element)
59 if (isEmpty()) {
60 return false;
62 else {
63 element = fifo[ridx];
64 ridx = nextIndex(ridx);
65 return true;
69 bool isEmpty() const
71 return (ridx == widx);
74 bool isFull()
76 uint32_t next = nextIndex(widx);
77 return (next == ridx);
80 uint32_t size() const
82 return (N + widx - ridx) & (N - 1);
85 uint32_t hasSpace(uint32_t n) const
87 return (N > (size() + n));
90 bool probe(T & element) const
92 if (isEmpty()) {
93 return false;
95 else {
96 element = fifo[ridx];
97 return true;
101 protected:
102 T fifo[N];
103 volatile uint32_t widx;
104 volatile uint32_t ridx;
106 inline uint32_t nextIndex(uint32_t idx)
108 return (idx + 1) & (N - 1);
112 #endif // _FIFO_H_