aboutsummaryrefslogtreecommitdiff
path: root/quantum/ring_buffer.h
diff options
context:
space:
mode:
Diffstat (limited to 'quantum/ring_buffer.h')
-rw-r--r--quantum/ring_buffer.h44
1 files changed, 44 insertions, 0 deletions
diff --git a/quantum/ring_buffer.h b/quantum/ring_buffer.h
new file mode 100644
index 000000000..284745ca8
--- /dev/null
+++ b/quantum/ring_buffer.h
@@ -0,0 +1,44 @@
1#pragma once
2
3#include <util/atomic.h>
4#include <stdint.h>
5#include <stdbool.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) { has_data = (rbuf_head != rbuf_tail); }
40 return has_data;
41}
42static inline void rbuf_clear(void) {
43 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { rbuf_head = rbuf_tail = 0; }
44}