[common] ringbuffer: allow reverse iteration

This commit is contained in:
Geoffrey McRae 2021-08-09 14:06:32 +10:00
parent 91d1b8d2cd
commit 69f6532b8d
3 changed files with 30 additions and 10 deletions

View File

@ -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)
{

View File

@ -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);

View File

@ -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;
}
}
}