ECE 4180 - Final Project Team / Mbed 2 deprecated WalkieTalkie

Dependencies:   mbed 4DGL-uLCD-SE mbed-rtos nRF24L01P

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers CircularBuf.cpp Source File

CircularBuf.cpp

00001 #include "CircularBuf.h"
00002 #include "stdio.h"
00003 
00004 template <typename T>
00005 CircularBuf<T>::CircularBuf(unsigned int size) : _size(size), _head(0), _tail(0) {
00006     _data = (T*)malloc(sizeof(T) * size);
00007 }
00008 
00009 template <typename T>
00010 CircularBuf<T>::~CircularBuf() {
00011     free(_data);
00012 }
00013 
00014 template <typename T>
00015 unsigned int CircularBuf<T>::push(T* data, unsigned int size) {
00016     unsigned int cnt = 0;
00017     
00018     for (int i = 0; i < size; i++) {
00019         unsigned int next = _head + 1;
00020         
00021         if (next >= _size)
00022             next = 0;
00023             
00024         if (next ==  _tail)
00025             return cnt;
00026             
00027         _data[next] = data[cnt];
00028         _head = next;
00029         cnt++;
00030     }
00031     
00032     return cnt;
00033 }
00034 
00035 template <typename T>
00036 unsigned int CircularBuf<T>::pop(T* data, unsigned int size) {
00037     unsigned int cnt = 0;
00038     
00039     for (int i = 0; i < size; i++) {
00040         unsigned int next = _tail + 1;
00041         
00042         if (next >= _size) {
00043             next = 0;
00044         }
00045         
00046         if (_tail == _head)
00047             return cnt;
00048             
00049         data[cnt] = _data[next];
00050         _tail = next;
00051         cnt++;
00052     }
00053     
00054     return cnt;
00055 }
00056 
00057 template <typename T>
00058 unsigned int CircularBuf<T>::size() {
00059     int s = _head - _tail;
00060     
00061     // If buffer overlaps end
00062     if (s < 0)
00063         s += _size;
00064         
00065     return s;
00066 }
00067 
00068 template <typename T>
00069 void CircularBuf<T>::clear() {
00070     _head = 0;
00071     _tail = 0;
00072 }