summaryrefslogtreecommitdiff
path: root/src/shared/container/ring.c
diff options
context:
space:
mode:
authordzwdz2022-04-10 17:14:10 +0200
committerdzwdz2022-04-10 17:14:10 +0200
commit7022f39e10551d7ab325d196884de301ddb3087e (patch)
treed48ca9522bea004b1cd241988d689bfdd48843af /src/shared/container/ring.c
parent194a91faf70ef66d663c370135bb84804bdcd57b (diff)
shared: implement a basic ring buffer
Diffstat (limited to 'src/shared/container/ring.c')
-rw-r--r--src/shared/container/ring.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/shared/container/ring.c b/src/shared/container/ring.c
new file mode 100644
index 0000000..525fade
--- /dev/null
+++ b/src/shared/container/ring.c
@@ -0,0 +1,35 @@
+#include <shared/container/ring.h>
+#include <stdbool.h>
+// TODO use memcpy
+
+static bool at_end(ring_t *r) {
+ return r->_head + 1 == r->_tail
+ || (r->_head + 1 == r->capacity && r->_tail == 0);
+}
+
+size_t ring_size(ring_t *r) {
+ if (r->_head >= r->_tail)
+ return r->_head - r->_tail;
+ else
+ return r->_head + r->capacity - r->_tail;
+}
+
+void ring_put(ring_t *r, void *buf, size_t len) {
+ for (size_t i = 0; i < len; i++)
+ ring_put1b(r, ((uint8_t*)buf)[i]);
+}
+
+void ring_put1b(ring_t *r, uint8_t byte) {
+ if (at_end(r)) return;
+ ((uint8_t*)r->buf)[r->_head++] = byte;
+ if (r->_head >= r->capacity) r->_head = 0;
+}
+
+size_t ring_get(ring_t *r, void *buf, size_t len) {
+ for (size_t i = 0; i < len; i++) {
+ if (at_end(r)) return i;
+ ((uint8_t*)buf)[i] = ((uint8_t*)r->buf)[r->_tail++];
+ if (r->_tail >= r->capacity) r->_tail = 0;
+ }
+ return len;
+}