Buffer for general purpose use. Templated for most datatypes

Dependents:   BufferedSoftSerial 09_PT1000 10_PT1000 11_PT1000 ... more

Example

 #include "mbed.h"
 #include "Buffer.h"

 Buffer <char> buf;

 int main()
 {
     buf = 'a';
     buf.put('b');
     char *head = buf.head();
     puts(head);

     char whats_in_there[2] = {0};
     int pos = 0;

     while(buf.available())
     {   
         whats_in_there[pos++] = buf;
     }
     printf("%c %c\n", whats_in_there[0], whats_in_there[1]);
     buf.clear();
     error("done\n\n\n");
 }

Files at this revision

API Documentation at this revision

Comitter:
sam_grove
Date:
Fri May 10 18:34:16 2013 +0000
Child:
1:490224f41c09
Commit message:
First version - implements basic functionality and overloaded members

Changed in this revision

Buffer.cpp Show annotated file Show diff for this revision Revisions of this file
Buffer.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Buffer.cpp	Fri May 10 18:34:16 2013 +0000
@@ -0,0 +1,74 @@
+
+#include "Buffer.h"
+
+template <class T>
+Buffer<T>::Buffer(BUFFER_SIZE size)
+{
+    _buf = new T [size];
+    _size = size;
+    clear();
+    
+    return;
+}
+
+template <class T>
+Buffer<T>::~Buffer()
+{
+    delete [] _buf;
+    
+    return;
+}
+
+template <class T>
+void Buffer<T>::put(T data)
+{
+    _buf[_wloc++] = data;
+    _wloc &= (_size-1);
+    
+    return;
+}
+
+template <class T>
+T Buffer<T>::get(void)
+{
+    T data_pos = _buf[_rloc++];
+    _rloc &= (_size-1);
+    
+    return data_pos;
+}
+
+template <class T>
+T *Buffer<T>::head(void)
+{
+    T *data_pos = &_buf[0];
+    
+    return data_pos;
+}
+
+template <class T>
+void Buffer<T>::clear(void)
+{
+    memset(_buf, 0, _size);
+    _wloc = 0;
+    _rloc = 0;
+    
+    return;
+}
+
+template <class T>
+uint32_t Buffer<T>::available(void)
+{
+    return (_wloc == _rloc) ? 0 : 1;
+}
+
+template class Buffer<uint8_t>;
+template class Buffer<int8_t>;
+template class Buffer<uint16_t>;
+template class Buffer<int16_t>;
+template class Buffer<uint32_t>;
+template class Buffer<int32_t>;
+template class Buffer<uint64_t>;
+template class Buffer<int64_t>;
+template class Buffer<char>;
+template class Buffer<wchar_t>;
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Buffer.h	Fri May 10 18:34:16 2013 +0000
@@ -0,0 +1,33 @@
+
+#ifndef BUFFER_H
+#define BUFFER_H
+
+#include <stdint.h>
+#include <string.h>
+
+template <typename T>
+class Buffer
+{
+private:
+    T           *_buf;
+    uint32_t     _wloc;
+    uint32_t     _rloc;
+    uint32_t     _size;
+    
+    enum BUFFER_SIZE{SMALL = 0x100, MEDIUM = 0x400, LARGE = 0x1000};
+
+public:
+    Buffer(BUFFER_SIZE size = Buffer::SMALL);
+    ~Buffer();
+    
+    void put(T data);
+    T get(void);
+    T *head(void);
+    void clear(void);
+    Buffer &operator= (T data){put(data);return *this;}
+    uint32_t available(void);
+    
+};
+
+#endif
+