優れたring bufferまたはcycle bufferの実装コード
6567 ワード
#define CIRCLE_BUFFSIZE 1024 * 1024
#define min(x, y) ((x) < (y) ? (x) : (y))
struct cycle_buffer {
unsigned char *buf;
unsigned int size;
unsigned int in;
unsigned int out;
pthread_mutex_t lock;
};
static struct cycle_buffer *fifo = NULL;
static int init_cycle_buffer(void)
{
int size = CIRCLE_BUFFSIZE, ret;
ret = size & (size - 1);
if (ret)
return ret;
fifo = (struct cycle_buffer *) malloc(sizeof(struct cycle_buffer));
if (!fifo)
return -1;
memset(fifo, 0, sizeof(struct cycle_buffer));
fifo->size = size;
fifo->in = fifo->out = 0;
pthread_mutex_init(&fifo->lock, NULL);
fifo->buf = (unsigned char *) malloc(size);
if (!fifo->buf)
free(fifo);
else
memset(fifo->buf, 0, size);
return 0;
}
static int uninit_cycle_buffer(void)
{
if(!fifo)
return -1;
pthread_mutex_destroy(&fifo->lock);
if(fifo->buf)
free(fifo->buf);
free(fifo);
}
unsigned int fifo_get(unsigned char *buf, unsigned int len)
{
unsigned int l;
len = min(len, fifo->in - fifo->out);
if(len <= 0)
return 0;
l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
memcpy(buf, fifo->buf + (fifo->out & (fifo->size - 1)), l);
memcpy(buf + l, fifo->buf, len - l);
fifo->out += len;
return len;
}
unsigned int fifo_put(unsigned char *buf, unsigned int len)
{
unsigned int l;
len = min(len, fifo->size - fifo->in + fifo->out);
l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
memcpy(fifo->buf + (fifo->in & (fifo->size - 1)), buf, l);
memcpy(fifo->buf, buf + l, len - l);
fifo->in += len;
return len;
}
この実現は比較的優秀で、自分でjavaの実現に変えることができます.