一个简单高效的循环缓冲区的管理代码,与平台无关,可以方便在各种场合使用。
-A simple and efficient management of the cycle of the buffer zone code, and platform-independent, it will be convenient to use on various occasions.
#ifndef LOOP_INCLUDED
#define LOOP_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
struct LoopBuffCtl{
unsigned char * buffer;
unsigned int size;
unsigned int reader;
unsigned int writer;
};
void LoopBuffInit( struct LoopBuffCtl * pLoopCtl, unsigned int size, unsigned char * buffer );
unsigned short LoopBuffDataLength( struct LoopBuffCtl * pLoopCtl );
unsigned short LoopBuffFreeSpace( struct LoopBuffCtl * pLoopCtl );
unsigned short LoopBuffWrite( struct LoopBuffCtl *, unsigned char * , unsigned short );
unsigned short LoopBuffRead( struct LoopBuffCtl *, unsigned char *, unsigned short );
#ifdef __cplusplus
}
#endif
#endif
#include "LoopBuff.h"
#define min(a,b) ((a)>(b)) ? (b) : (a)
unsigned short LoopBuffFreeSpace( struct LoopBuffCtl * pLoopCtl )
{
return ( pLoopCtl->reader + pLoopCtl->size - pLoopCtl->writer - 1 ) & ( pLoopCtl->size - 1 );
}
unsigned short LoopBuffDataLength( struct LoopBuffCtl * pLoopCtl )
{
return ( pLoopCtl->writer + pLoopCtl->size - pLoopCtl->reader ) & ( pLoopCtl->size - 1 );
}
void LoopBuffInit( struct LoopBuffCtl * pLoopCtl, unsigned int size, unsigned char * buffer )
{
pLoopCtl->reader = pLoopCtl->writer = 0;
pLoopCtl->size = size;
pLoopCtl->buffer = buffer;
}
unsigned short LoopBuffWrite( struct LoopBuffCtl * pLoopCtl, unsigned char * buffer , unsigned short len )
{
unsigned short l;
len = min( len, pLoopCtl->size - ( pLoopCtl->writer - pLoopCtl->reader ));
l = min( len, pLoopCtl->size - ( pLoopCtl->writer & ( pLoopCtl->size - 1 )));
memcpy( pLoopCtl->buffer + ( pLoopCtl->writer & ( pLoopCtl->size - 1 )), buffer, l );
memcpy( pLoopCtl->buffer, buffer + l, len - l );
pLoopCtl->writer += len;
return len;
}
unsigned short LoopBuffRead( struct LoopBuffCtl * pLoopCtl, unsigned char * buffer , unsigned short len )
{
unsigned short l;
len = min( len, pLoopCtl->reader - pLoopCtl->writer );
l = min( len, pLoopCtl->size - ( pLoopCtl->reader & ( pLoopCtl->size - 1 )));
if( buffer != 0 )
{
memcpy( buffer, pLoopCtl->buffer + ( pLoopCtl->reader & ( pLoopCtl->size - 1 )), l );
memcpy( buffer + l, pLoopCtl->buffer, len - l );
}
pLoopCtl->reader += len;
return len;
}