如何优雅地实现环形缓冲区?
扫描二维码
随时随地手机看文章
https://github.com/barraq/BRBrain/blob/master/firmware/CBUF.h
CBUF.h 模块使用宏实现循环缓冲区,具体源码如下所示;#if !defined( CBUF_H )
#define CBUF_H /**< Include Guard */
/* ---- Include Files ---------------------------------------------------- */
/* ---- Constants and Types ---------------------------------------------- */
/**
* Initializes the circular buffer for use.
*/
#define CBUF_Init( cbuf ) cbuf.m_getIdx = cbuf.m_putIdx = 0
/**
* Returns the number of elements which are currently contained in the
* circular buffer.
*/
#define CBUF_Len( cbuf ) ((typeof( cbuf.m_putIdx ))(( cbuf.m_putIdx ) - ( cbuf.m_getIdx )))
/**
* Appends an element to the end of the circular buffer
*/
#define CBUF_Push( cbuf, elem ) (cbuf.m_entry)[ cbuf.m_putIdx