typedef struct { unsigned char *Buff; unsigned int Head; unsigned int Tail; unsigned int Len; unsigned int VaildLen; unsigned int InvaildLen; }QUEUE_S; char USER_QueueInit(QUEUE_S *pq, unsigned long buff_size);//初始化队列 void USER_QueueDestroy( QUEUE_S* pq ); //销毁队列 char USER_QueuePush( QUEUE_S* pq, const unsigned char* dat, unsigned int len );//入队 unsigned int USER_QueueGetTop(QUEUE_S *pq, unsigned char *rtval, unsigned int len);//获取队头的值,但不删除,返回从队列中读取的字节数 void USER_QueuePop(QUEUE_S *pq, unsigned int len);//出队 unsigned int USER_QueueGetVaildLenght(QUEUE_S* pq); char USER_QueueIsFull(QUEUE_S *pq); char USER_QueueIsEmpty(QUEUE_S *pq); char USER_QueueInit( QUEUE_S* pq, unsigned long buff_size ) //初始化队列 { pq->Buff = ( HI_U8* )malloc( sizeof( HI_U8 ) * buff_size ); if ( NULL == pq->Buff ) { printf( "%s: malloc failed!\n", __FUNCTION__ ); return -1; } pq->Head = 0; pq->Tail = 0; pq->Len = buff_size; pq->VaildLen = 0; pq->InvaildLen = buff_size - 1; //队列头前面一个字节不能存放数据,如果存了,头跟尾指向同一个地方 return 0; } void USER_QueueDestroy( QUEUE_S* pq ) //销毁队列 { free(pq->Buff); } char USER_QueuePush( QUEUE_S* pq, const unsigned char* dat, unsigned int len ) //入队 { unsigned int i; if ( ( USER_QueueIsFull( pq ) ) || ( pq->InvaildLen < len ) ) { return -1; } for( i = 0; i < len; i++ ) { pq->Buff[pq->Tail] = dat[i]; pq->Tail = ( pq->Tail + 1 ) % pq->Len; } pq->VaildLen += len; pq->InvaildLen = pq->InvaildLen - len; return 0; } unsigned int USER_QueueGetTop( QUEUE_S* pq, unsigned char *rtval, unsigned int len ) //获取队头的值,但不删除 { unsigned int temp, i; unsigned int temp_Head = pq->Head; if ( USER_QueueIsEmpty( pq ) ) { return 0; } if( ( pq->Len - pq->InvaildLen - 1) < len ) { temp = pq->Len - pq->InvaildLen -1; } else { temp = len; } for( i = 0; i < temp; i++ ) { rtval[i] = pq->Buff[temp_Head]; temp_Head = ( temp_Head + 1 ) % pq->Len; } return temp; } void USER_QueuePop( QUEUE_S* pq, unsigned int len ) //出队 { if ( USER_QueueIsEmpty( pq ) ) { return; } if( pq->VaildLen <= len ) { pq->Head = pq->Tail; pq->VaildLen = 0; //队列头前面一个字节不能存放数据,如果存了,头跟尾指向同一个地方 pq->InvaildLen = pq->Len-1; } else { pq->Head = ( pq->Head + len ) % pq->Len; pq->VaildLen -= len; pq->InvaildLen += len; } } unsigned int USER_QueueGetVaildLenght(QUEUE_S* pq) { return pq->VaildLen; } char USER_QueueIsFull( QUEUE_S* pq ) { return ( pq->Tail + 1 ) % pq->Len == pq->Head; } char USER_QueueIsEmpty( QUEUE_S* pq ) { return pq->Tail == pq->Head;; }