RingBuffer.h

/* [<][>]
[^][v][top][bottom][index][help] */

FUNCTIONS

This source file includes following functions.
  1. RingBuffer
  2. bufInit
  3. isEmpty
  4. isFull
  5. inBufSize
  6. maxBufSize
  7. Capacity
  8. Show
  9. Get
  10. Put

#ifndef _RINGBUFFER_H
#define _RINGBUFFER_H

#include <stdio.h>
#include <string.h>


#define _RINGBUFFER_DEBUG 0

template <typename T>
class RingBuffer{
/* [<][>][^][v][top][bottom][index][help] */
private:
  int bufsize;
  int rpos;
  int wpos;
  int inlen;
  T* buf;

public:

  RingBuffer(int size = 1024) : buf(0){
    bufInit(size);
  }
  void bufInit(int newsize){
/* [<][>][^][v][top][bottom][index][help] */
    if(buf) delete[] buf;
    bufsize = newsize;
    buf = new T[bufsize];
    rpos = wpos = 0;
    inlen = 0;
  }
  int isEmpty(){ return inlen == 0; }
/* [<][>][^][v][top][bottom][index][help] */
  int isFull() { return inlen == bufsize; }
/* [<][>][^][v][top][bottom][index][help] */
  int inBufSize() { return inlen; }
/* [<][>][^][v][top][bottom][index][help] */
  int maxBufSize() { return bufsize; }
/* [<][>][^][v][top][bottom][index][help] */
  int Capacity() { return inlen * 100 / bufsize; }
/* [<][>][^][v][top][bottom][index][help] */
  void Show(){
/* [<][>][^][v][top][bottom][index][help] */
#if _RINGBUFFER_DEBUG
    fprintf(stderr, "size = %d, inlen = %d, rpos = %d, wpos = %d\n", bufsize, inlen, rpos, wpos);
#endif
  }
  int Get(T* outbuf, int size){
/* [<][>][^][v][top][bottom][index][help] */
    int retlen = size;
    int remain, nowlen, dstofs;
    if(retlen > inlen) retlen = inlen;
    for(remain = retlen, dstofs = 0; remain >0;){
      nowlen = remain;
      if(rpos + nowlen > bufsize) nowlen = bufsize - rpos;
      memcpy(outbuf + dstofs, buf + rpos, nowlen * sizeof(T));
      dstofs += nowlen;
      rpos += nowlen; if(rpos == bufsize) rpos = 0;
      remain -= nowlen;
    }
    inlen -= retlen;
    Show();
    return retlen;
  }
  int Put(T* inbuf, int size){
/* [<][>][^][v][top][bottom][index][help] */
    int retlen = size;
    int remain, nowlen, srcofs;
    if(retlen > bufsize - inlen) retlen = bufsize - inlen;
    for(remain = retlen, srcofs = 0; remain >0;){
      nowlen = remain;
      if(wpos + nowlen > bufsize) nowlen = bufsize - wpos;
      memcpy(buf + wpos, inbuf + srcofs, nowlen * sizeof(T));
      srcofs += nowlen;
      wpos += nowlen; if(wpos == bufsize) wpos = 0;
      remain -= nowlen;
    }
    inlen += retlen;
    Show();
    return retlen;
  }
};


#endif

/* [<][>][^][v][top][bottom][index][help] */