From 23f985576863b39bb8d5562e6419a9497454c56c Mon Sep 17 00:00:00 2001 From: Geoffrey McRae Date: Sat, 10 Jul 2021 14:18:52 +1000 Subject: [PATCH] [common] ringbuffer: add forEach iterator --- common/include/common/ringbuffer.h | 5 +++++ common/src/ringbuffer.c | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/common/include/common/ringbuffer.h b/common/include/common/ringbuffer.h index c568c997..0c521196 100644 --- a/common/include/common/ringbuffer.h +++ b/common/include/common/ringbuffer.h @@ -19,6 +19,7 @@ */ #include +#include typedef struct RingBuffer * RingBuffer; @@ -31,3 +32,7 @@ int ringbuffer_getLength(const RingBuffer rb); int ringbuffer_getStart (const RingBuffer rb); int ringbuffer_getCount (const RingBuffer rb); void * ringbuffer_getValues(const RingBuffer rb); + +typedef bool (*RingBufferIterator)(int index, void * value, void * udata); +void ringbuffer_forEach(const RingBuffer rb, RingBufferIterator fn, + void * udata); diff --git a/common/src/ringbuffer.c b/common/src/ringbuffer.c index ee2ca8cf..89bfca2d 100644 --- a/common/src/ringbuffer.c +++ b/common/src/ringbuffer.c @@ -88,3 +88,17 @@ void * ringbuffer_getValues(const RingBuffer rb) { return rb->values; } + +void ringbuffer_forEach(const RingBuffer rb, RingBufferIterator fn, void * udata) +{ + int index = rb->start; + for(int i = 0; i < rb->count; ++i) + { + void * value = rb->values + index * rb->valueSize; + if (++index == rb->length) + index = 0; + + if (!fn(i, value, udata)) + break; + } +}