/*********************************************************************************
|
* Copyright: (C) 2023 LingYun IoT System Studio.
|
* All rights reserved.
|
*
|
* Filename: ringbuf.c
|
* Description: This file is common ring buffer API functions
|
*
|
* Version: 1.0.0(11/08/23)
|
* Author: Guo Wenxue <guowenxue@gmail.com>
|
* ChangeLog: 1, Release initial version on "11/08/23 16:18:43"
|
*
|
********************************************************************************/
|
|
#include <string.h>
|
#include <assert.h>
|
#include "ringbuf.h"
|
|
void rb_init (struct ring_buffer *ring, unsigned char* buff, int size)
|
{
|
memset (ring, 0, sizeof (struct ring_buffer));
|
ring->rd_pointer = 0;
|
ring->wr_pointer = 0;
|
ring->buffer= buff;
|
ring->size = size;
|
}
|
|
|
int rb_write (struct ring_buffer *rb, unsigned char * buf, int len)
|
{
|
int total;
|
int i;
|
|
/* total = len = min(space, len) */
|
total = rb_free_size(rb);
|
if(len > total)
|
len = total;
|
else
|
total = len;
|
|
i = rb->wr_pointer;
|
if(i + len > rb->size)
|
{
|
memcpy(rb->buffer + i, buf, rb->size - i);
|
buf += rb->size - i;
|
len -= rb->size - i;
|
i = 0;
|
}
|
|
memcpy(rb->buffer + i, buf, len);
|
rb->wr_pointer = i + len;
|
return total;
|
}
|
|
|
int rb_free_size (struct ring_buffer *rb)
|
{
|
return (rb->size - 1 - rb_data_size(rb));
|
}
|
|
|
int rb_read (struct ring_buffer *rb, unsigned char * buf, int max)
|
{
|
int total;
|
int i;
|
|
/* total = len = min(used, len) */
|
total = rb_data_size(rb);
|
|
if(max > total)
|
max = total;
|
else
|
total = max;
|
|
|
i = rb->rd_pointer;
|
if(i + max > rb->size)
|
{
|
memcpy(buf, rb->buffer + i, rb->size - i);
|
buf += rb->size - i;
|
max -= rb->size - i;
|
i = 0;
|
}
|
|
memcpy(buf, rb->buffer + i, max);
|
rb->rd_pointer = i + max;
|
|
return total;
|
}
|
|
int rb_data_size (struct ring_buffer *rb)
|
{
|
return ((rb->wr_pointer - rb->rd_pointer) & (rb->size-1));
|
}
|
|
void rb_clear (struct ring_buffer *rb)
|
{
|
memset(rb->buffer,0,rb->size);
|
rb->rd_pointer=0;
|
rb->wr_pointer=0;
|
}
|
|
unsigned char rb_peek(struct ring_buffer* rb, int index)
|
{
|
assert(index < rb_data_size(rb));
|
|
return rb->buffer[((rb->rd_pointer + index) % rb->size)];
|
}
|