MIDI interpreter using mbed

Dependencies:   MIDI TextLCD mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers RingBuffer.h Source File

RingBuffer.h

00001 #include <stdint.h>
00002 
00003 #ifndef __RINGBUFFER_H_
00004 #define __RINGBUFFER_H_
00005 
00006 template <class T>
00007 class RingBuffer {
00008 public:  // For experiment use
00009     uint32_t readPos;
00010     uint32_t writePos;
00011     uint32_t itemCount;
00012     uint32_t length;
00013     T* buffer;
00014     
00015 public:
00016     RingBuffer(uint32_t);
00017     ~RingBuffer();
00018     uint32_t items();
00019     bool isWritable();
00020     bool isReadable();
00021     bool write(T&);
00022     T* read();
00023     T* peek();
00024     void flush();
00025     int find(T);
00026 };
00027 
00028 
00029 template <class T>
00030 RingBuffer<T>::RingBuffer(uint32_t len) {
00031     length = len;
00032     buffer = new T[length];
00033     readPos = 0;
00034     writePos = 0;
00035     itemCount = 0;
00036 }
00037 
00038 template <class T>
00039 RingBuffer<T>::~RingBuffer() {
00040     delete[] buffer;
00041 }
00042 
00043 template <class T>
00044 uint32_t RingBuffer<T>::items() {
00045     return itemCount;
00046 }
00047 
00048 template <class T>
00049 bool RingBuffer<T>::isWritable() {
00050     return itemCount < length;
00051 }
00052 
00053 template <class T>
00054 bool RingBuffer<T>::isReadable() {
00055     return itemCount > 0;
00056 }
00057 
00058 template <class T>
00059 bool RingBuffer<T>::write(T& n) {
00060     if (!isWritable()) {
00061         return false;
00062     }
00063     buffer[writePos++] = n;
00064     if (writePos == length) {
00065         writePos = 0;
00066     }
00067     itemCount++;
00068     return true;
00069 }
00070 
00071 template <class T>
00072 T* RingBuffer<T>::read() {
00073     uint32_t readPosTemp = readPos;
00074     
00075     if (!isReadable()) {
00076         return NULL;
00077     }
00078     readPos++;
00079     if (readPos == length) {
00080         readPos = 0;
00081     }
00082     itemCount--;
00083     return &buffer[readPosTemp];
00084 }
00085 
00086 template <class T>
00087 T* RingBuffer<T>::peek() {
00088     if (!isReadable()) {
00089         return NULL;
00090     }
00091     return &buffer[readPos];
00092 }
00093 
00094 template <class T>
00095 void RingBuffer<T>::flush() {
00096     itemCount = 0;
00097     readPos = writePos;
00098 }
00099 
00100 template <class T>
00101 int RingBuffer<T>::find(T key) {
00102     uint32_t p = readPos;
00103     
00104     for (uint32_t i = 0; i < itemCount; i++) {
00105         if (buffer[p] == key) {
00106             return i;
00107         }
00108         p++;
00109         if (p == length) p = 0;
00110     }
00111     return -1;
00112 }
00113 
00114 #endif