Parent directory

ring_buffer.h

1139 bytes
 1#pragma once
 2
 3#include <stdint.h>
 4#include <stdbool.h>
 5#include "atomic_util.h"
 6
 7#ifndef RBUF_SIZE
 8#    define RBUF_SIZE 32
 9#endif
10
11static uint8_t     rbuf[RBUF_SIZE];
12static uint8_t     rbuf_head = 0;
13static uint8_t     rbuf_tail = 0;
14static inline bool rbuf_enqueue(uint8_t data) {
15    bool ret = false;
16    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
17        uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
18        if (next != rbuf_tail) {
19            rbuf[rbuf_head] = data;
20            rbuf_head       = next;
21            ret             = true;
22        }
23    }
24    return ret;
25}
26static inline uint8_t rbuf_dequeue(void) {
27    uint8_t val = 0;
28    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
29        if (rbuf_head != rbuf_tail) {
30            val       = rbuf[rbuf_tail];
31            rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
32        }
33    }
34
35    return val;
36}
37static inline bool rbuf_has_data(void) {
38    bool has_data;
39    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
40        has_data = (rbuf_head != rbuf_tail);
41    }
42    return has_data;
43}
44static inline void rbuf_clear(void) {
45    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
46        rbuf_head = rbuf_tail = 0;
47    }
48}