
#include "base_core_user.h"
#include "base_core.h"
#include "platform.h"


/*
队列初始化*/
void queue_init(struct fifo_queue_STR *queue,unsigned char **data,unsigned short node_size,unsigned char data_len)	
{		
	queue->pdata =data;
	queue->front = queue->rear;
	queue->count =0;
}


/*
将数据存储到队列尾部*/
unsigned char queue_in(struct fifo_queue_STR *queue,const elem_type* data,unsigned short node_size,unsigned char data_len)	
{
	unsigned char retval;	//modify by Gavin 20200407,避免node_size越界造成溢出!!!
	PLATFORM_DISABLE_IRQ();//platform.disable_interrupt();
	if( (queue->front ==queue->rear)&&(queue->count >= node_size) )//if( (queue->front ==queue->rear)&&(queue->count == node_size) )
		retval=0;
	else{
		mem_cpy(data, (unsigned char*)(queue->pdata)+ queue->rear *data_len,data_len);
		queue->rear = (queue->rear +1)% node_size;
		queue->count += 1;
		retval=1;
	}
	PLATFORM_ENABLE_IRQ();//platform.enable_interrupt();
	return retval;
}


/*
从队列头读取数据，并且删除*/
unsigned char queue_out(struct fifo_queue_STR *queue,elem_type* data,unsigned short node_size,unsigned char data_len)	
{	
	unsigned char retval;
	PLATFORM_DISABLE_IRQ();//platform.disable_interrupt();
	if( (queue->front ==queue->rear)&&(queue->count == 0) )
		retval= 0;
	else{
		mem_cpy((unsigned char*)(queue->pdata)+ queue->front *data_len,data,data_len);
		queue->front = (queue->front +1)% node_size;
		queue->count -= 1;
		retval= 1;
	}
	PLATFORM_ENABLE_IRQ();//platform.enable_interrupt();
	return retval;
}


/*------------------------------------ 以上是通用fifo处理函数， 以下是处理投票数据专用函数 ----------------------------------------------------
队列头数据第一字节读取(type),与输入的type比对
如果队列是空 return 0
如果队列中的type与目标type不相等，不读取数据并return 2
如果两个type相等，return 1*/
unsigned char queue_out_special(struct fifo_queue_STR *queue,elem_type* data,unsigned short node_size,unsigned char data_len,unsigned char type)	
{
	unsigned char retval;	
	PLATFORM_DISABLE_IRQ();//platform.disable_interrupt();
	if( (queue->front ==queue->rear)&&(queue->count == 0) )
		retval= 0;
	else{				
		if( *((unsigned char*)(queue->pdata)+ queue->front*data_len) !=type) retval= 2;
		else{
			mem_cpy((unsigned char*)(queue->pdata)+ queue->front *data_len,data,data_len);
			queue->front = (queue->front +1)% node_size;
			queue->count -= 1;
			retval= 1;
		}
	}	
  PLATFORM_ENABLE_IRQ();//platform.enable_interrupt();	
	return retval;
}


/*
取出队列头的第一个字节(type)
如果队列为空 return0
否则 return 队列头中的type*/
unsigned char queue_out_get_type(struct fifo_queue_STR *queue,unsigned char data_len)
{
	unsigned char retval;	
  PLATFORM_DISABLE_IRQ();//platform.disable_interrupt();	
	if( (queue->front ==queue->rear)&&(queue->count == 0) )
		retval= 0;
	else{
		retval = *((unsigned char*)(queue->pdata)+ queue->front*data_len);
	}	
  PLATFORM_ENABLE_IRQ();//platform.enable_interrupt();	
	return retval;
}


