Dependencies:   ChaNFSSD mbed BMP085 SHT2x

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers tringbuffer.h Source File

tringbuffer.h

00001 /*
00002  * Copyright (c) 2011 Toshihisa T
00003  * Released under the MIT License: http://mbed.org/license/mit
00004  */
00005 
00006 #ifndef __TRINGBUFFER_H
00007 #define __TRINGBUFFER_H
00008 
00009 #include "tversion.h"
00010 
00011 namespace libT {
00012 
00013 template <class T>
00014 class tRingBuffer : public tVersion
00015 {
00016 public:
00017 
00018     tRingBuffer(void) : tVersion(0x20100721/* 2010-07-21 */,0x00000001UL),wp(0),rp(0) {}
00019 
00020     inline void reset(void){wp = rp = 0;}
00021 
00022     inline int writable(void) const
00023     {
00024         return (inc(wp) != rp) ? 1 : 0;
00025     }
00026 
00027     inline int write(T _c)
00028     {
00029         int retval = -1;    /* Ringbuffer FULL */
00030         if(writable()){
00031             array[wp] = _c;
00032             wp = inc(wp);
00033             retval = 0;    /* OK */
00034         }
00035         return retval;
00036     }
00037 
00038     inline int readable(void) const
00039     {
00040         return (rp != wp) ? 1 : 0;
00041     }
00042 
00043     inline int read(T *_c)
00044     {
00045         int retval = -1;    /* Ringbuffer empty or _c is invalid*/
00046         if((readable()) && (_c != 0)){
00047             *_c = array[rp];
00048             rp = inc(rp);
00049             retval = 0;    /* OK */
00050         }
00051         return retval;
00052     }
00053 
00054 private:
00055     enum {TRINGBUFFER_SIZE=0x2000};
00056     inline unsigned short inc(unsigned short _p) const
00057     {
00058         return static_cast<unsigned short>(static_cast<unsigned short>(_p + 1) & (sizeof(array)-1));
00059     }
00060     volatile unsigned short wp;
00061     volatile unsigned short rp;
00062     volatile T array[TRINGBUFFER_SIZE];
00063 };
00064 
00065 };
00066 
00067 #endif /* __TRINGBUFFER_H */
00068