/*
 * fifo.h
 *
 *  Created on: 2023/06/09
 */

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2023 Takayoshi Uemitsu (BestTechnology CO.,LTD.)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#ifndef FIFO_H_
#define FIFO_H_

#include <stdint.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_ */
