OpenModem/util/FIFO.h

86 lines
1.7 KiB
C
Raw Normal View History

2014-12-02 17:10:06 -07:00
#ifndef UTIL_FIFO_H
#define UTIL_FIFO_H
#include <stddef.h>
#include <util/atomic.h>
typedef struct FIFOBuffer
{
unsigned char *begin;
unsigned char *end;
unsigned char * volatile head;
unsigned char * volatile tail;
} FIFOBuffer;
inline bool fifo_isempty(const FIFOBuffer *f) {
return f->head == f->tail;
}
inline bool fifo_isfull(const FIFOBuffer *f) {
return ((f->head == f->begin) && (f->tail == f->end)) || (f->tail == f->head - 1);
}
inline void fifo_push(FIFOBuffer *f, unsigned char c) {
*(f->tail) = c;
if (f->tail == f->end) {
f->tail = f->begin;
} else {
f->tail++;
}
}
inline unsigned char fifo_pop(FIFOBuffer *f) {
if(f->head == f->end) {
f->head = f->begin;
return *(f->end);
} else {
return *(f->head++);
}
}
inline void fifo_flush(FIFOBuffer *f) {
f->head = f->tail;
}
2015-10-02 15:44:24 -06:00
static inline bool fifo_isempty_locked(const FIFOBuffer *f) {
2014-12-02 17:10:06 -07:00
bool result;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
result = fifo_isempty(f);
}
return result;
}
2015-10-02 15:44:24 -06:00
static inline bool fifo_isfull_locked(const FIFOBuffer *f) {
2014-12-02 17:10:06 -07:00
bool result;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
result = fifo_isfull(f);
}
return result;
}
2015-10-02 15:44:24 -06:00
static inline void fifo_push_locked(FIFOBuffer *f, unsigned char c) {
2014-12-02 17:10:06 -07:00
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
fifo_push(f, c);
}
}
2015-10-02 15:44:24 -06:00
static inline unsigned char fifo_pop_locked(FIFOBuffer *f) {
2014-12-02 17:10:06 -07:00
unsigned char c;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
c = fifo_pop(f);
}
return c;
}
inline void fifo_init(FIFOBuffer *f, unsigned char *buffer, size_t size) {
f->head = f->tail = f->begin = buffer;
2020-06-01 05:05:09 -06:00
f->end = buffer + size;
2014-12-02 17:10:06 -07:00
}
inline size_t fifo_len(FIFOBuffer *f) {
return f->end - f->begin;
}
2015-10-02 15:44:24 -06:00
#endif