[common] ringbuffer: add forEach iterator

This commit is contained in:
Geoffrey McRae 2021-07-10 14:18:52 +10:00
parent 2e76c874cc
commit 23f9855768
2 changed files with 19 additions and 0 deletions

View File

@ -19,6 +19,7 @@
*/
#include <stddef.h>
#include <stdbool.h>
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);

View File

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