This code is used to sort out the FIFO buffer from the 30-day self-made operating system p135.
Well written, so record it (added a function named fifo8_free to query the remaining capacity, which is useful ). The author implements a char buffer, but can replace it with any struct you want to transmit ~~~
Fifo8.h
/* Overflow flag: 0-normal, -1-overflow */# define flags_overrun 0x0001/* Buf-buffer address size-size free-free capacity putp-next data write location getp-next data alone location */struct required o8 {unsigned char * Buf; int putp, getp, size, free, flags;}; void implements o8_init (struct implements o8 * FIFO, int size, unsigned char * BUF); int implements o8_put (struct implements o8 * FIFO, unsigned char data); int random o8_get (struct serial o8 * FIFO); int random o8_status (struct serial o8 * FIFO); int random o8_free (struct serial O7 * FIFO );
Fifo8.c
# Include "audio o8.h" Void audio o8_init (struct audio o8 * FIFO, int size, unsigned char * BUF)/* initialization */{FIFO-> Buf = Buf; FIFO-> flags = 0; FIFO-> free = size; FIFO-> size = size; FIFO-> putp = 0; FIFO-> getp = 0; return ;} int writable o8_putput (struct writable o8 * FIFO, unsigned char data)/* write data to FIFO */{If (FIFO-> free = 0) {FIFO-> flags | = flags_overrun; Return-1;} FIFO-> Buf [FIFO-> putp] = data; FIFO-> putp ++; // cyclic queue buffer if (FIFO-> putp = FIFO-> size) {FIFO-> putp = 0;} FIFO-> free --; return 0 ;} int writable o8_get (struct writable o8 * FIFO)/* retrieve a data from FIFO */{int data; If (FIFO-> free = FIFO-> size) {return-1;} DATA = FIFO-> getp; FIFO-> getp ++; If (FIFO-> getp = FIFO-> size) {// used to implement cyclic FIFO-> getp = 0;} FIFO-> free ++; return data;} int ready o8_status (struct ready o8 * FIFO) /* buffer used capacity */{return FIFO-> size-FIFO-> free;} int ready o8_free (struct ready o8 * FIFO) /* remaining buffer capacity */{return FIFO-> free ;}
Learning: return can be returned when the return value is void; the structure of the circular buffer; overflow flag setting;