/* FIFOバッファ */

#include "bootpack.h"

void fifo_init(struct fifo *fifo, struct task *task, int *buf, int size)
{
	fifo->task = task;
	fifo->size = size;
	fifo->free = size;
	fifo->buf = buf;
	fifo->flag = FIFO_NONE;
	fifo->nextr = 0;
	fifo->nextw = 0;
	return;
}

int fifo_put(struct fifo *fifo, int data)
{
	if(fifo->free == 0) {	/* バッファオーバーラン */
		fifo->flag |= FIFO_OVERRUN;
		return -1;
	}
	fifo->buf[fifo->nextw] = data;
	fifo->nextw++;
	if(fifo->nextw == fifo->size) {
		fifo->nextw = 0;
	}
	fifo->free--;
	if(fifo->task != 0) {
		if(fifo->task->flag != TASK_RUNNING) {
			task_run(fifo->task, -1, 0);
		}
	}
	return 0;
}

int fifo_get(struct fifo *fifo)
{
	int data;

	if(fifo->free == fifo->size) {	/* 空 */
		return -1;
	}
	data = fifo->buf[fifo->nextr];
	fifo->nextr++;
	if(fifo->nextr == fifo->size) {
		fifo->nextr = 0;
	}
	fifo->free++;
	return data;
}

int fifo_stat(struct fifo *fifo)
{
	return fifo->size - fifo->free;
}
