1 Star 1 Fork 1

marenan/Ring-Buffer

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ringbuffer.c 1.97 KB
一键复制 编辑 原始数据 按行查看 历史
5ooo 提交于 2020-04-10 16:02 . Fix functions return type
#include "ringbuffer.h"
/**
* @file
* Implementation of ring buffer functions.
*/
void ring_buffer_init(ring_buffer_t *buffer) {
buffer->tail_index = 0;
buffer->head_index = 0;
}
void ring_buffer_queue(ring_buffer_t *buffer, char data) {
/* Is buffer full? */
if(ring_buffer_is_full(buffer)) {
/* Is going to overwrite the oldest byte */
/* Increase tail index */
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK);
}
/* Place data in buffer */
buffer->buffer[buffer->head_index] = data;
buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK);
}
void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) {
/* Add bytes; one by one */
ring_buffer_size_t i;
for(i = 0; i < size; i++) {
ring_buffer_queue(buffer, data[i]);
}
}
uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) {
if(ring_buffer_is_empty(buffer)) {
/* No items */
return 0;
}
*data = buffer->buffer[buffer->tail_index];
buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK);
return 1;
}
ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) {
if(ring_buffer_is_empty(buffer)) {
/* No items */
return 0;
}
char *data_ptr = data;
ring_buffer_size_t cnt = 0;
while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) {
cnt++;
data_ptr++;
}
return cnt;
}
uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) {
if(index >= ring_buffer_num_items(buffer)) {
/* No items at index */
return 0;
}
/* Add index to pointer */
ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK);
*data = buffer->buffer[data_index];
return 1;
}
extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer);
extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer);
extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/marenan_admin/Ring-Buffer.git
[email protected]:marenan_admin/Ring-Buffer.git
marenan_admin
Ring-Buffer
Ring-Buffer
master

搜索帮助