General purpose ring buffer library. RTOS proof, mutex protected.

Dependents:   RingBuffer_RTOS_test

Fork of RingBuffer by Yoji KURODA

Revision:
0:db7fa84ff50e
Child:
1:1c3a10f2eb04
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/RingBuffer.cpp	Fri Aug 31 10:13:15 2012 +0000
@@ -0,0 +1,69 @@
+/*
+ *    ringbuffer.c
+ *
+ *    2009.11.12 ... Y.Kuroda
+ */
+#include "string.h"
+#include "RingBuffer.h"
+
+
+/*
+ *    Machine Independent Area
+ */
+RingBuffer::RingBuffer(int _bufsize)
+:   bufsize(_bufsize)
+{
+    buf = new unsigned char [bufsize+1];
+
+    sp = ep = (unsigned int)buf;
+    memset(buf,0,bufsize);
+}
+
+RingBuffer::~RingBuffer()
+{
+    delete [] buf;
+}
+
+int
+RingBuffer::save(unsigned char c)
+{
+    if( (ep==sp-1)||
+        ((sp==(unsigned int)buf)&&
+            (ep==(unsigned int)buf+bufsize-1)) )    /* buffer full */
+        return 0;
+
+    *(unsigned char*)ep = c;
+    ep++;
+
+    if(ep > (unsigned int)buf+bufsize)
+        ep = (unsigned int)buf;
+    return 1;
+}
+
+unsigned char
+RingBuffer::read(void)
+{
+    unsigned char ret;
+
+    if(sp == ep)
+        return 0;    /* buffer empty */
+
+    ret = *(unsigned char*)sp;
+    *(unsigned char*)sp = 0;
+    sp++;
+
+    if(sp> (unsigned int)buf+bufsize)
+        sp = (unsigned int)buf;
+    return ret;
+}
+
+int
+RingBuffer::check(void)
+{
+    int n = ep-sp;
+    if(n<0)
+        n = bufsize-n;
+
+    return n;
+}
+