一个简单高效的循环缓冲区的管理代码

一个简单高效的循环缓冲区的管理代码,与平台无关,可以方便在各种场合使用。

-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;   
}   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值