76 lines
1.5 KiB
C
76 lines
1.5 KiB
C
/* ================================================================
|
|
* jb_ringbuffer.c — 环形缓冲区实现
|
|
* ================================================================
|
|
*/
|
|
#include "jb_ringbuffer.h"
|
|
|
|
/* ── 初始化 ── */
|
|
void jbRbInit(jb_ringbuffer_t *rb)
|
|
{
|
|
if (!rb)
|
|
{
|
|
return;
|
|
}
|
|
rb->write = rb->read = rb->count = 0;
|
|
}
|
|
|
|
/* ── 压入一个字节 ── */
|
|
void jbRbPush(jb_ringbuffer_t *rb, uint8_t byte)
|
|
{
|
|
if (!rb)
|
|
{
|
|
return;
|
|
}
|
|
if (rb->count >= JB_RB_CAPACITY)
|
|
{
|
|
return; /* 已满 — 丢弃 */
|
|
}
|
|
rb->buf[rb->write] = byte;
|
|
rb->write = (rb->write + 1) % JB_RB_CAPACITY;
|
|
rb->count++;
|
|
}
|
|
|
|
/* ── 弹出一个字节 ── */
|
|
uint8_t jbRbPop(jb_ringbuffer_t *rb)
|
|
{
|
|
if (!rb || rb->count == 0)
|
|
{
|
|
return 0;
|
|
}
|
|
uint8_t byte = rb->buf[rb->read];
|
|
rb->read = (rb->read + 1) % JB_RB_CAPACITY;
|
|
rb->count--;
|
|
return byte;
|
|
}
|
|
|
|
/* ── 查看指定偏移字节(不消费)── */
|
|
uint8_t jbRbPeek(const jb_ringbuffer_t *rb, uint16_t offset)
|
|
{
|
|
if (!rb || offset >= rb->count)
|
|
{
|
|
return 0;
|
|
}
|
|
uint16_t idx = (rb->read + offset) % JB_RB_CAPACITY;
|
|
return rb->buf[idx];
|
|
}
|
|
|
|
/* ── 可读字节数 ── */
|
|
uint16_t jbRbAvailable(const jb_ringbuffer_t *rb)
|
|
{
|
|
if (!rb)
|
|
{
|
|
return 0;
|
|
}
|
|
return rb->count;
|
|
}
|
|
|
|
/* ── 清空缓冲区 ── */
|
|
void jbRbClear(jb_ringbuffer_t *rb)
|
|
{
|
|
if (!rb)
|
|
{
|
|
return;
|
|
}
|
|
rb->write = rb->read = rb->count = 0;
|
|
}
|