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

Dependents:   RingBuffer_RTOS_test

Fork of RingBuffer by Yoji KURODA

RingBuffer.cpp

Committer:
ykuroda
Date:
2012-08-31
Revision:
0:db7fa84ff50e
Child:
1:1c3a10f2eb04

File content as of revision 0:db7fa84ff50e:

/*
 *    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;
}