From 0ed51a1b7bd35102099e5c27f042b27631649f0b Mon Sep 17 00:00:00 2001 From: Michael Hope Date: Sun, 10 Oct 2010 20:06:05 +1300 Subject: Mark head and tail as volatile as a ring buffer works accross threads/interrupts. Add comments. --- libmaple/ring_buffer.h | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to 'libmaple/ring_buffer.h') diff --git a/libmaple/ring_buffer.h b/libmaple/ring_buffer.h index 6a54747..9628005 100644 --- a/libmaple/ring_buffer.h +++ b/libmaple/ring_buffer.h @@ -14,12 +14,22 @@ extern "C"{ * The total buffer size must be a power of two * One byte is left free to distinguish empty from full */ typedef struct ring_buffer { - uint32 head; - uint32 tail; + /** Index of the next item to remove */ + volatile uint32 head; + /** Index where the next item will get inserted */ + volatile uint32 tail; + /** Buffer capacity */ uint8 size; - uint8 *buf; + /** Buffer items are stored into */ + volatile uint8 *buf; } ring_buffer; +/** Initialise a ring buffer. + + @param rb instance to initialise + @param size number of items in the buffer + @param buf buffer to store items into +*/ static inline void rb_init(ring_buffer *rb, uint8 size, uint8 *buf) { ASSERT(IS_POWER_OF_TWO(size)); rb->head = 0; @@ -28,11 +38,13 @@ static inline void rb_init(ring_buffer *rb, uint8 size, uint8 *buf) { rb->buf = buf; } +/** Append an item onto the end of the ring buffer */ static inline void rb_insert(ring_buffer *rb, uint8 element) { rb->buf[(rb->tail)++] = element; rb->tail &= (rb->size - 1); } +/** Remove and return the first item from the ring buffer */ static inline uint8 rb_remove(ring_buffer *rb) { uint8 ch = rb->buf[rb->head++]; rb->head &= (rb->size - 1); @@ -40,9 +52,11 @@ static inline uint8 rb_remove(ring_buffer *rb) { } static inline uint32 rb_full_count(ring_buffer *rb) { + /* PENDING: Broken */ return rb->tail - rb->head; } +/** Discard all items from the buffer */ static inline void rb_reset(ring_buffer *rb) { rb->tail = rb->head; } -- cgit v1.2.3