#include "circle_buffer.h"

/**
 * 初始化环形缓冲区
 */
void circle_buf_init(p_circle_buf pCircleBuf, uint32_t len, uint8_t *buf) 
{
    if (!pCircleBuf || !buf || len == 0) {
        return;  // 避免非法初始化
    }
    pCircleBuf->r = pCircleBuf->w = 0;
    pCircleBuf->len = len;
    pCircleBuf->buf = buf;
}

/**
 * 读取数据
 * @return 0 成功, -1 失败（缓冲区为空）
 */
int circle_buf_read(p_circle_buf pCircleBuf, uint8_t *pVal) 
{
    if (!pCircleBuf || !pVal) {
        return -1;  // 空指针检查
    }
    if (pCircleBuf->r == pCircleBuf->w) {
        return -1;  // 缓冲区为空
    }

    *pVal = pCircleBuf->buf[pCircleBuf->r];  // 读取数据
    pCircleBuf->r = (pCircleBuf->r + 1) % pCircleBuf->len;  // 更新读指针
    return 0;
}
/*
int circle_buf_read_2(p_circle_buf_2 pCircleBuf, uint8_t *pVal) 
{
    if (!pCircleBuf || !pVal) {
        return -1;  // 空指针检查
    }
    if (pCircleBuf->r == pCircleBuf->w) {
        return -1;  // 缓冲区为空
    }

    *pVal = pCircleBuf->buf[pCircleBuf->r];  // 读取数据
    pCircleBuf->r = (pCircleBuf->r + 1) % pCircleBuf->len;  // 更新读指针
    return 0;
}
*/
/**
 * 写入数据（支持覆盖最旧数据）
 * @return 0 成功
 */
int circle_buf_write(p_circle_buf pCircleBuf, uint8_t val) 
{
    if (!pCircleBuf || !pCircleBuf->buf || pCircleBuf->len == 0) {
        return -1;  // 空指针/长度检查
    }

    uint32_t next_w = (pCircleBuf->w + 1) % pCircleBuf->len;

    if (next_w == pCircleBuf->r) {
        // 缓冲区满，覆盖最旧的数据
        pCircleBuf->r = (pCircleBuf->r + 1) % pCircleBuf->len;
    }

    pCircleBuf->buf[pCircleBuf->w] = val;
    pCircleBuf->w = next_w;
    return 0;
}

/**
 * 获取当前缓冲区中的数据长度
 */
uint32_t circle_buf_size(p_circle_buf pCircleBuf) 
{
    if (!pCircleBuf) {
        return 0;
    }
    if (pCircleBuf->w >= pCircleBuf->r) {
        return pCircleBuf->w - pCircleBuf->r;
    } else {
        return pCircleBuf->len - (pCircleBuf->r - pCircleBuf->w);
    }
}

/**
 * 清空缓冲区
 */
void circle_buf_clear(p_circle_buf pCircleBuf) 
{
    if (pCircleBuf) {
        pCircleBuf->r = pCircleBuf->w = 0;
    }
}

/**
 * 复制环形缓冲区
 */
/*
void copy_circle_buf(circle_buf_t *src, circle_buf_t_2 *dst)
{
    uint32_t readable_len;
    if (src->w >= src->r)
    {
        readable_len = src->w - src->r;
        memcpy(dst->buf, &src->buf[src->r], readable_len);
    }
    else
    {
        readable_len = src->len - src->r + src->w;
        memcpy(dst->buf, &src->buf[src->r], src->len - src->r);
        memcpy(dst->buf + (src->len - src->r), src->buf, src->w);
    }

    dst->r = 0;
    dst->w = readable_len;
    dst->len = src->len;

}
*/
