EE445M RTOS
Taken at the University of Texas Spring 2015
bufferpp.hpp
Go to the documentation of this file.
1 /* -*- mode: c++; c-basic-offset: 4; -*- */
2 #ifndef __bufferpp__
3 #define __bufferpp__
4 
5 #include <stdint.h>
6 
7 #include "semaphorepp.hpp"
8 
13 #define DEFAULT_BUFFER_LENGTH 64
14 
15 template <typename T, uint32_t N>
16 class buffer {
17 private:
18 
19 public:
20  buffer() {
21 
22  init();
23  }
24 
27 
28  this->sem = sem;
29  *(this->sem) = semaphore();
30  init();
31  }
32 
33  void clear() {
34 
35  while(pos>0) {
36  buf[--pos] = 0;
37  }
38  }
39 
40  void init() {
41  error_overflow = 0;
42  error_underflow = 0;
43  pos = 0;
44  len = N;
45  clear();
46  }
47 
48  void notify(const T data) {
49 
50  if (add(data)) {
51  sem->post();
52  }
53  }
54 
56  bool add(const T data) {
57 
58  if (full()) {
60  return false;
61  }
62  buf[pos++] = (T) data;
63  return true;
64  }
65 
66  T peek() {
67 
68  if (pos == 0) {
69  return buf[len-1];
70  } else {
71  return buf[pos-1];
72  }
73  }
74 
76  T get(bool &ok) {
77 
78  /* base case */
79  if (pos <= 0) {
81  ok = false;
82  return 0;
83  }
84 
85  /* normal operation */
86  ok = true;
87 
88  T ret = buf[--pos];
89 
90  /*buf is always null-terminated*/
91  buf[pos] = 0;
92 
93  return ret;
94  }
95 
96  bool full() {
97 
98  return pos == len;
99  }
100 
101  bool empty() {
102 
103  return pos == 0;
104  }
105 
106  uint32_t length() {
107 
108  return pos;
109  }
110 
111  /* Points ahead of last valid T */
112  uint32_t pos;
113  uint32_t len;
115  T buf[N];
116 
117  uint32_t error_overflow;
118  uint32_t error_underflow;
119 };
120 
121 #endif
122 
void clear()
Definition: bufferpp.hpp:33
void init()
Definition: bufferpp.hpp:40
buffer()
Definition: bufferpp.hpp:20
buffer(semaphore *sem)
Definition: bufferpp.hpp:26
void post(void)
Definition: semaphorepp.cpp:45
void notify(const T data)
Definition: bufferpp.hpp:48
uint32_t error_underflow
Definition: bufferpp.hpp:118
T buf[N]
Definition: bufferpp.hpp:115
uint32_t len
Definition: bufferpp.hpp:113
bool full()
Definition: bufferpp.hpp:96
bool add(const T data)
Definition: bufferpp.hpp:56
semaphore * sem
Definition: bufferpp.hpp:114
uint32_t error_overflow
Definition: bufferpp.hpp:117
T peek()
Definition: bufferpp.hpp:66
uint32_t pos
Definition: bufferpp.hpp:112
bool empty()
Definition: bufferpp.hpp:101
uint32_t length()
Definition: bufferpp.hpp:106