From 69f6532b8dbcec0af8799a495fb8f161a2e6b02a Mon Sep 17 00:00:00 2001 From: Geoffrey McRae Date: Mon, 9 Aug 2021 14:06:32 +1000 Subject: [PATCH] [common] ringbuffer: allow reverse iteration --- client/src/overlay/graphs.c | 2 +- common/include/common/ringbuffer.h | 2 +- common/src/ringbuffer.c | 36 +++++++++++++++++++++++------- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/client/src/overlay/graphs.c b/client/src/overlay/graphs.c index 3df640e0..df6ead23 100644 --- a/client/src/overlay/graphs.c +++ b/client/src/overlay/graphs.c @@ -158,7 +158,7 @@ static int graphs_render(void * udata, bool interactive, continue; struct BufferMetrics metrics = {}; - ringbuffer_forEach(graph->buffer, rbCalcMetrics, &metrics); + ringbuffer_forEach(graph->buffer, rbCalcMetrics, &metrics, false); if (metrics.sum > 0.0f) { diff --git a/common/include/common/ringbuffer.h b/common/include/common/ringbuffer.h index 6203d6ac..5d62b98e 100644 --- a/common/include/common/ringbuffer.h +++ b/common/include/common/ringbuffer.h @@ -42,4 +42,4 @@ void ringbuffer_setPreOverwriteFn(RingBuffer rb, RingBufferValueFn fn, typedef bool (*RingBufferIterator)(int index, void * value, void * udata); void ringbuffer_forEach(const RingBuffer rb, RingBufferIterator fn, - void * udata); + void * udata, bool reverse); diff --git a/common/src/ringbuffer.c b/common/src/ringbuffer.c index 4519167e..8a470ee2 100644 --- a/common/src/ringbuffer.c +++ b/common/src/ringbuffer.c @@ -106,16 +106,36 @@ void ringbuffer_setPreOverwriteFn(const RingBuffer rb, RingBufferValueFn fn, rb->preOverwriteUdata = udata; } -void ringbuffer_forEach(const RingBuffer rb, RingBufferIterator fn, void * udata) +void ringbuffer_forEach(const RingBuffer rb, RingBufferIterator fn, void * udata, + bool reverse) { - int index = rb->start; - for(int i = 0; i < rb->count; ++i) + if (reverse) { - void * value = rb->values + index * rb->valueSize; - if (++index == rb->length) - index = 0; + int index = rb->start + rb->count - 1; + if (index >= rb->length) + index -= rb->length; - if (!fn(i, value, udata)) - break; + for(int i = 0; i < rb->count; ++i) + { + void * value = rb->values + index * rb->valueSize; + if (--index == -1) + index = rb->length - 1; + + if (!fn(i, value, udata)) + break; + } + } + else + { + 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; + } } }