RingBuffer——LwRB库(纯C)

LwRB (lightweight ring buffer) 是一个轻量级的环形缓冲区,功能强大、高效。

纯C编写,3.0以上版本使用了C11(用到了stdatomic.h),因此版本要求VS2019和Win10,Install C11 and C17 support in Visual Studio | Microsoft Learn

若想使用VS2015,使用2版本。

使用方法:将h和c文件直接添加到项目里

 函数讲解(里边讲了经典的使用组合)通用环形缓冲区 LwRB 使用指南-CSDN博客

简单案例:

    uint8_t buff_data[8+1];    //数组容器。可容纳8字节。环形队列需多留1个字节。
    lwrb_t buff;            //用于操作数组容器
    lwrb_init(&buff, buff_data, sizeof(buff_data));    //初始化

    size_t count_w = lwrb_get_free(&buff);    //8个字节可写
    size_t count_r = lwrb_get_full(&buff);    //0个字节可读

    lwrb_write(&buff, "0123", 4);            //写入4个字节

    //读2个字节
    uint8_t data[2];
    size_t len;
    /* Read until len == 0, when buffer is empty */
    while ((len = lwrb_read(&buff, data, sizeof(data))) > 0) {
        printf("Successfully read %d bytes\r\n", (int)len);
        printf("count_r %d bytes\r\n", (int)lwrb_get_full(&buff));
    }

 先窥读后扔掉,即先lwrb_peek后lwrb_skip。更改上述案例的while部分

    while ((len = lwrb_peek(&buff, 0, data,sizeof(data))) > 0) {
        printf("Successfully read %d bytes\r\n", (int)len);
        printf("count_r %d bytes\r\n", (int)lwrb_get_full(&buff));
        lwrb_skip(&buff, sizeof(data));        //peek后skip,相当于队列的peek后pop
    }

 

posted @ 2024-07-03 11:22  夕西行  阅读(34)  评论(0编辑  收藏  举报