COSA
An Object-Oriented Platform for Arduino Programming
Queue.hh
Go to the documentation of this file.
1 
21 #ifndef COSA_QUEUE_HH
22 #define COSA_QUEUE_HH
23 
24 #include "Cosa/Types.h"
25 #include "Cosa/Power.hh"
26 
34 template <class T, uint8_t NMEMB>
35 class Queue {
36  static_assert(NMEMB && !(NMEMB & (NMEMB - 1)), "NMEMB should be power of 2");
37 public:
42  Queue() :
43  m_put(0),
44  m_get(0)
45  {}
46 
51  uint8_t available() const
52  __attribute__((always_inline))
53  {
54  return ((NMEMB + m_put - m_get) & MASK);
55  }
56 
61  uint8_t room() const
62  __attribute__((always_inline))
63  {
64  return ((NMEMB - m_put + m_get - 1) & MASK);
65  }
66 
76  bool enqueue(T* data);
77 
87  bool enqueue_P(const T* data);
88 
99  bool dequeue(T* data);
100 
108  void await(T* data);
109 
110 private:
111  static const uint8_t MASK = (NMEMB - 1);
112  volatile uint8_t m_put;
113  volatile uint8_t m_get;
114  T m_buffer[NMEMB];
115 };
116 
117 template <class T, uint8_t NMEMB>
118 bool
120 {
121  synchronized {
122  uint8_t next = (m_put + 1) & MASK;
123  if (UNLIKELY(next == m_get)) return (false);
124  m_buffer[next] = *data;
125  m_put = next;
126  }
127  return (true);
128 }
129 
130 template <class T, uint8_t NMEMB>
131 bool
133 {
134  synchronized {
135  uint8_t next = (m_put + 1) & MASK;
136  if (UNLIKELY(next == m_get)) return (false);
137  memcpy_P(&m_buffer[next], data, sizeof(T));
138  m_put = next;
139  }
140  return (true);
141 }
142 
143 template <class T, uint8_t NMEMB>
144 bool
146 {
147  synchronized {
148  if (UNLIKELY(m_get == m_put)) return (false);
149  uint8_t next = (m_get + 1) & MASK;
150  m_get = next;
151  *data = m_buffer[next];
152  }
153  return (true);
154 }
155 
156 template <class T, uint8_t NMEMB>
157 void
159 {
160  while (!dequeue(data)) yield();
161 }
162 
163 #endif
bool dequeue(T *data)
Definition: Queue.hh:145
uint8_t room() const
Definition: Queue.hh:61
bool enqueue(T *data)
Definition: Queue.hh:119
Definition: Queue.hh:35
bool enqueue_P(const T *data)
Definition: Queue.hh:132
void await(T *data)
Definition: Queue.hh:158
#define static_assert(condition, message)
Definition: Types.h:266
void(* yield)()
uint8_t available() const
Definition: Queue.hh:51
Queue()
Definition: Queue.hh:42
#define UNLIKELY(x)
Definition: Types.h:153