/*
 * fifo.h
 *
 *  Created on: 2023/04/29
 *      Author: T.Uemitsu
 */

#ifndef FIFO_H_
#define FIFO_H_

typedef struct {
    struct {
        uint8_t *buf;
        uint16_t wp;
        volatile uint16_t rp;
        uint16_t maxlen;
    } tx;
    struct {
        uint8_t *buf;
        volatile uint16_t wp;
        uint16_t rp;
        uint16_t maxlen;
    } rx;
} TFIFO;

#define FIFO_INIT(f,b,s){ f.buf = b; f.maxlen = s; f.wp = f.rp = 0; }
#define FIFO_RESET(f)   { f.wp = f.rp = 0; }
#define FIFO_EMPTY(f)   (f.rp == f.wp)
#define FIFO_WAIT(f)    { volatile int t; t = ((int)f.wp + 1) % f.maxlen; while (t == f.rp) ; }
#define FIFO_FULL(f)    ((((int)f.wp + 1) % f.maxlen) == f.rp)
#define FIFO_BUFF(f,s)  { if ((s = ((int)f.wp - (int)f.rp)) < 0) s += f.maxlen; }
#define FIFO_WD(f,c)    { volatile int t = ((int)f.wp + 1) % f.maxlen; if (t != f.rp) { f.buf[f.wp] = c; if (t != f.rp) { __DMB(); f.wp = t; } } }
#define FIFO_RD(f,c)    { c = f.buf[f.rp++]; __DMB(); f.rp %= f.maxlen; }


#endif /* FIFO_H_ */
