common: Add the ringbuf module.
[gps-watch.git] / src / common / ringbuf.c
diff --git a/src/common/ringbuf.c b/src/common/ringbuf.c
new file mode 100644 (file)
index 0000000..98a4d86
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2016 Tilman Sauerbeck (tilman at code-monkey de)
+ *
+ * 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.
+ */
+
+#include "ringbuf.h"
+
+#define __ACCESS_ONCE(x) ({ \
+       __attribute__ ((__unused__)) typeof(x) __var = ( typeof(x)) 0; \
+       (volatile typeof(x) *) &(x); })
+#define ACCESS_ONCE(x) (*__ACCESS_ONCE(x))
+
+bool
+ringbuf_is_empty (struct ringbuf *rb)
+{
+       uint32_t read_index = ACCESS_ONCE (rb->read_index);
+       uint32_t write_index = ACCESS_ONCE (rb->write_index);
+
+       return read_index == write_index;
+}
+
+bool
+ringbuf_is_full (struct ringbuf *rb)
+{
+       uint32_t read_index = ACCESS_ONCE (rb->read_index);
+       uint32_t write_index = ACCESS_ONCE (rb->write_index);
+
+       return (write_index - read_index) == (rb->size_minus_1 + 1);
+}
+
+void
+ringbuf_write (struct ringbuf *rb, uint8_t value)
+{
+       uint32_t write_index = ACCESS_ONCE (rb->write_index);
+
+       rb->buffer[write_index & rb->size_minus_1] = value;
+
+       /* Ensure we only update rb->write_index _after_ we stored
+        * the data in the array.
+        */
+       __sync_synchronize ();
+
+       ACCESS_ONCE (rb->write_index) = write_index + 1;
+}
+
+uint8_t
+ringbuf_read (struct ringbuf *rb)
+{
+       uint32_t read_index = ACCESS_ONCE (rb->read_index);
+       uint8_t value = rb->buffer[read_index & rb->size_minus_1];
+
+       /* Ensure we only update rb->read_index _after_ we read
+        * the data from the array.
+        */
+       __sync_synchronize ();
+
+       ACCESS_ONCE (rb->read_index) = read_index + 1;
+
+       return value;
+}