v1.0

Dependencies:   SDFileSystem mbed

RingBuffer/RingBuffer.cpp

Committer:
jehoon
Date:
2016-05-09
Revision:
0:0073c8def9f1

File content as of revision 0:0073c8def9f1:

#include <RingBuffer.h>

RingBuffer::RingBuffer()
{
    
}

RingBuffer::RingBuffer(int length)
{
  this->buffer = (byte *)malloc(length);
  this->max = length;
  this->fill = 0;
  this->ptr = 0;
}

RingBuffer::~RingBuffer()
{
  free (this->buffer);
}

void RingBuffer::init(int length)
{
  this->buffer = (byte *)malloc(length);
  this->max = length;
  this->fill = 0;
  this->ptr = 0;
}

void RingBuffer::clear()
{
  this->fill = 0;
}

bool RingBuffer::isFull()
{
  return (this->max == this->fill);
}

bool RingBuffer::hasData()
{
  return (this->fill != 0);
}

bool RingBuffer::addByte(byte b)
{
  if (this->max == this->fill)
    return false;

  int idx = (this->ptr + this->fill) % this->max;
  this->buffer[idx] = b;
  this->fill++;
  return true;
}

byte RingBuffer::consumeByte()
{
  if (this->fill == 0)
    return 0;
  
  byte ret = this->buffer[this->ptr];
  this->fill--;
  this->ptr++;
  this->ptr %= this->max;
  return ret;
}

byte RingBuffer::peek(int idx)
{
  byte p = (this->ptr + idx) % this->max;
  return this->buffer[p];
}

int RingBuffer::findBuf(char * str)
{
    int i=0;
    int cnt = 0;
    int len = strlen(str);
    byte *tmp = (byte *) str;
    
    if( this->fill == 0 )
        return -1;
    
    for( i=0; i<this->fill; i++ )
    {
        if( peek(i) == *tmp )
        {
            tmp++;
            cnt++;
            
            if(cnt == len)
            {
                return (i - len + 1);
            }
        }
        else
        {   
            tmp = (byte *)str;
            cnt=0;
        }
    }
    
    return -1;
}


int RingBuffer::count()
{
  return this->fill;
}