#include "ringframe.h"

unsigned short ringframe_in(ringframe_t * p_ringframe, void * p_data,unsigned char data_size)
{
		unsigned char * p;
		if(p_ringframe->freespace < ( data_size + 1 ))return 1;
		p = (unsigned char*)p_ringframe->p_buffer + p_ringframe->front ;        
		* p=data_size;
		p_ringframe->front++;
		p_ringframe->front &= p_ringframe->size-1;
		for(int i=0;i<data_size;i++)
		{
						p = (unsigned char*)p_ringframe->p_buffer + p_ringframe->front ;
						* p=((unsigned char*)p_data)[i];
						p_ringframe->front++;
						p_ringframe->front &= p_ringframe->size-1;
		}
		p_ringframe->freespace -= (data_size+1);
		p_ringframe->element_count++;
		return 0;
}

unsigned short ringframe_out(ringframe_t * p_ringframe, void * p_data,unsigned char * data_size)
{
	unsigned char * p;
	if(p_ringframe->element_count < 1)return 1;
	p = (unsigned char*)p_ringframe->p_buffer + p_ringframe->back ;	
	* data_size = * p;
	p_ringframe->back++;
	p_ringframe->back &= p_ringframe->size-1;
	for(int i=0;i < *data_size;i++)
	{
		p = (unsigned char*)p_ringframe->p_buffer + p_ringframe->back ;
		((unsigned char*)p_data)[i]= * p;
		p_ringframe->back++;
		p_ringframe->back &= p_ringframe->size-1;
	}
	p_ringframe->freespace += (* data_size+1);
	p_ringframe->element_count--;
	return 0;
}

unsigned short ringframe_peek(ringframe_t * p_ringframe, void * p_data,unsigned char * data_size)
{
	unsigned char * p;
	unsigned short temp = p_ringframe->back;
	if(p_ringframe->element_count < 1)return 1;
	p = (unsigned char*)p_ringframe->p_buffer + temp ;	
	* data_size = * p;
	temp++;
	temp &= p_ringframe->size-1;
	for(int i=0;i < *data_size;i++)
	{
		p = (unsigned char*)p_ringframe->p_buffer + temp ;
		((unsigned char*)p_data)[i]= * p;
		temp++;
		temp &= p_ringframe->size-1;
	}
	return 0;
}

unsigned short ringframe_throw(ringframe_t * p_ringframe)
{
	unsigned char * p;
	if(p_ringframe->element_count < 1)return 1;
	p = (unsigned char*)p_ringframe->p_buffer + p_ringframe->back ;	
	p_ringframe->back = p_ringframe->back + * p + 1;
	p_ringframe->back &= p_ringframe->size-1;
	p_ringframe->freespace += (* p +1);
	p_ringframe->element_count--;
	return 0;
}

void ringframe_reset(ringframe_t * p_ringframe)
{
	p_ringframe->back=0;
	p_ringframe->front=0;              
	p_ringframe->element_count=0;	
	p_ringframe->freespace =	p_ringframe->size -1;
}


