纯C开发环形缓冲区,经过大量的测试,很实用的模块。可以在任意C编译器下编译,用于任意嵌入式单片机。
int RingBuffWrite( RingBuff_t * const obj, const unsigned char * const item, const int cnt )
{
int offset;
int cpyCntUp;
int cpyCntDown;
int writeCnt;
do
{
writeCnt = RingBuffFreeSize( obj );
if ( writeCnt == 0 || item == 0 || cnt <= 0 )
{
break;
}
if ( writeCnt > cnt )
writeCnt = cnt;
if ( obj->tailIdx >= obj->headIdx )
{
offset = writeCnt obj->tailIdx;
if ( offset >= obj->size )
{
cpyCntUp = offset - obj->size;
cpyCntDown = obj->size - obj->tailIdx;
memcpy( obj->buff obj->tailIdx, item, cpyCntDown );
if ( cpyCntUp > 0 )
memcpy( obj->buff, item cpyCntDown, cpyCntUp );
obj->tailIdx = cpyCntUp;
break;
}
else
{
memcpy( obj->buff obj->tailIdx, item, writeCnt );
obj->tailIdx = writeCnt;
break;
}
}
else
{
memcpy( obj->buff obj->tailIdx, item, writeCnt );
obj->tailIdx = writeCnt;
break;
}
} while ( 0 );
return writeCnt;
}
int RingBuffRead( RingBuff_t * const obj, unsigned char * const item, const int cnt )
{
int offset;
int cpyCntUp;
int cpyCntDown;
int readCnt;
do
{
readCnt = RingBuffDataSize( obj );
if ( readCnt == 0 || item == 0 || cnt <= 0 )
{
readCnt = 0;
break;
}
if ( cnt < readCnt )
readCnt = cnt;
if ( obj->tailIdx > obj->headIdx )
{
memcpy( item, obj->buff obj->headIdx, readCnt );
obj->headIdx = readCnt;
break;
}
else
{
offset = readCnt obj->headIdx;
if ( offset >= obj->size )
{
cpyCntUp = obj->size - obj->headIdx;
cpyCntDown = offset - obj->size;
memcpy( item, obj->buff obj->headIdx, cpyCntUp );
if ( cpyCntDown > 0 )
memcpy( item cpyCntUp, obj->buff, cpyCntDown );
obj->headIdx = cpyCntDown;
break;
}
else
{
memcpy( item, obj->buff obj->headIdx, readCnt );
obj->headIdx = readCnt;
break;
}
}
} while ( 0 );
return readCnt;
}
评论