#include "cfifo.h"
 
 
/*环形CFIFO初始化*/
void CfifoBuffInit(CfifoBuff* cfifoPointer)
{
   //初始化相关信息
   cfifoPointer->Head = 0;
   cfifoPointer->Tail = 0;
   cfifoPointer->Lenght = 0;
   memset(cfifoPointer->BUFF,'\0',CFIFO_SIZE);  //环形CFIFO缓存区初始化
}
 
/*环形CFIFO数据清除*/
void CfifoBuffClear(CfifoBuff* cfifoPointer)
{
   //清除相关信息
   cfifoPointer->Head = 0;
   cfifoPointer->Tail = 0;
   cfifoPointer->Lenght = 0;
   memset(cfifoPointer->BUFF,'\0',CFIFO_SIZE); //环形CFIFO缓存区清除
}
 
 
 
/*环形CFIFO数据写入*/
/*
*参数说明:
*         Cfifo_pointer————环形CFIFO结构体
*         User_buff————待写入数据
*         num————写入数据长度
*
*返回值说明：正确写入到FIFO缓存区中的数据长度
*
*功能说明：将User_buff中的数据写入到环形CFIFO缓存区
*
*/
int16_t CfifoBuffWrite(CfifoBuff* cfifoPointer, char* userBuff, int32_t num)
{
	int16_t i , writeNum;
	
    if(cfifoPointer->Lenght >= CFIFO_SIZE) //判断缓存区是否已满
    {
		 writeNum = -1;
         return writeNum;       //数据溢出
    }
		
    if(cfifoPointer->Lenght + num < CFIFO_SIZE)  //判断写入的数据长度是否超出当前可写入的最大值
	{
		writeNum = num;
	}
	else
	{
		writeNum = CFIFO_SIZE - cfifoPointer->Lenght;	  
	}
		
	for(i=0; i<writeNum; i++)
	{
	    cfifoPointer->BUFF[cfifoPointer->Tail] = *(userBuff+i);
			
		cfifoPointer->Tail = (cfifoPointer->Tail+1) % CFIFO_SIZE;//防止越界非法访问
	}	
		
    cfifoPointer->Lenght += writeNum;
		
    return writeNum;  //返回正确写入的数据长度
}
 
 
/*环形CFIFO读取*/
/*
*参数说明:
*         Cfifo_pointer————环形CFIFO结构体
*         User_buff————读取数据存放地
*         num————读取数据长度
*
*返回值说明：正确读取到User_buff的数据长度
*
*功能说明：将环形CFIFO缓存区的数据读取到User_buff
*
*/
int16_t CfifoBuffRead(CfifoBuff* cfifoPointer, char* userBuff, int32_t num)
{
	int16_t i , readNum;
	
    if(cfifoPointer->Lenght == 0) //判断非空
    {
        readNum = -1;
		 
        return readNum;       //没有数据
    }	
	
   if( cfifoPointer->Lenght - num >= 0)       //判断读取的数据长度是否超出当前可读取的最大值
   {
		readNum = num;
   }
   else
   {
    	readNum = cfifoPointer->Lenght;	  
   }
		
   for(i=0; i<readNum; i++)
   {
	    *(userBuff+i) = cfifoPointer->BUFF[cfifoPointer->Head];
			
		cfifoPointer->Head = (cfifoPointer->Head+1) % CFIFO_SIZE;//防止越界非法访问
   }	
		
    cfifoPointer->Lenght -= readNum;
	
    return readNum;  //返回正确写入的数据长度 
}
 
 
