c言語が難しい-キューの実現
2521 ワード
Talk is cheap, show you the fucking source code.
#define NULL 0
#define FALUSE -1
struct queue_def
{
unsigned char *head;
unsigned char *tail;
unsigned char *buffer;
unsigned char block_size;
unsigned char block_deep;
};
/*
* @bief :
* @input : struct queue_def *queue : input queue
* unsigned int buffer_deep : queue deep
* unsigned char block_size : operator buffer unit
* @output: FALSE :queue is fully
* NULL :pop sucess
* @data : 2018.12.19
* @author: martin
*/
void queue_init(struct queue_def *queue,
unsigned int buffer_deep,
unsigned int block_size)
{
queue->block_size = block_size;
queue->buffer = (unsigned char*)malloc(buffer_deep*block_size);
queue->head = queue->buffer;
queue->tail = queue->tail;
queue->block_deep = block_deep;
}
/*
* @bief :
* @input : struct queue_def *queue : input queue
* unsigned char *dest : operator array
* unsigned char buffer_size : operator array lenght
* @output: FALSE :queue is empty
* NULL :pop sucess
* @data : 2018.12.19
* @author: martin
*/
int queue_push(struct queue_def *queue,unsigned char *dest,unsigned char buffer_size)
{
if((queue->block_size == (&queue->tail-&queue->head))
|| (&queue->tail == (&queue->buffer+queue->block_deep*queue->block_size))
|| (buffer_size > queue->block_size)){
return FALSE;
}else{
/* critical segment */
queue->tial += queue->block_size;
if (&queue->tail == (&queue->buffer+queue->block_deep*queue->block_siz))
queue->tail = queue->buffer;
/* critical segment */
memset(queue->tail,0,queue->buffer_size);
memcpy(queue->tail,dest,buffer_size);
}
return NULL;
}
/*
* @bief :
* @input : struct queue_def *queue : input queue
* @output: FALSE :queue is empty
* NULL :pop sucess
* @data : 2018.12.19
* @author: martin
*/
int queue_pop(struct queue_def *queue,unsigned char *source,unsigned char buffer_size)
{
if(&queue->tail == &queue->head)
return FALSE;
}else{
memcpy(source,queue->head,buffer_size);
/* critical segment */
queue->head += queue->block_size;
if (&queue->head == (&queue->buffer+queue->block_deep*queue->block_siz))
queue->head = queue->buffer;
/* critical segment */
}
return NULL;
}