aboutsummaryrefslogtreecommitdiffstats
path: root/libmaple/ring_buffer.h
diff options
context:
space:
mode:
Diffstat (limited to 'libmaple/ring_buffer.h')
-rw-r--r--libmaple/ring_buffer.h30
1 files changed, 21 insertions, 9 deletions
diff --git a/libmaple/ring_buffer.h b/libmaple/ring_buffer.h
index a44088e..3b5d4e7 100644
--- a/libmaple/ring_buffer.h
+++ b/libmaple/ring_buffer.h
@@ -13,21 +13,20 @@
extern "C"{
#endif
-/* The buffer is empty when head == tail.
+/**
+ * Ring buffer type.
+ *
+ * The buffer is empty when head == tail.
*
* The buffer is full when the head is one byte in front of the tail,
* modulo buffer length.
*
* One byte is left free to distinguish empty from full. */
typedef struct ring_buffer {
- /** Buffer items are stored into */
- volatile uint8 *buf;
- /** Index of the next item to remove */
- uint16 head;
- /** Index where the next item will get inserted */
- uint16 tail;
- /** Buffer capacity minus one */
- uint16 size;
+ volatile uint8 *buf; /**< Buffer items are stored into */
+ uint16 head; /**< Index of the next item to remove */
+ uint16 tail; /**< Index where the next item will get inserted */
+ uint16 size; /**< Buffer capacity minus one */
} ring_buffer;
/**
@@ -66,6 +65,11 @@ static inline int rb_is_full(ring_buffer *rb) {
(rb->tail == rb->size && rb->head == 0);
}
+/** Return true if and only if the ring buffer is empty. */
+static inline int rb_is_empty(ring_buffer *rb) {
+ return rb->head == rb->tail;
+}
+
/** Append element onto the end of the ring buffer. */
static inline void rb_insert(ring_buffer *rb, uint8 element) {
rb->buf[rb->tail] = element;
@@ -80,6 +84,14 @@ static inline uint8 rb_remove(ring_buffer *rb) {
}
/**
+ * If the ring buffer is nonempty, removes and returns its first item.
+ * If it is empty, does nothing and returns a negative value.
+ */
+static inline int16 rb_safe_remove(ring_buffer *rb) {
+ return rb_is_empty(rb) ? -1 : rb_remove(rb);
+}
+
+/**
* If rb is not full, appends element and returns true; otherwise,
* does nothing and returns false. */
static inline int rb_safe_insert(ring_buffer *rb, uint8 element) {