From: Bastian Dehn Date: Sun, 24 Apr 2022 14:46:56 +0000 (+0200) Subject: add: value counter X-Git-Url: https://gitweb.hhaalo.de/?a=commitdiff_plain;h=8e58e0feb08ec02fbb47db8e3d494cc429d2502f;p=ringbuffer.git add: value counter --- diff --git a/ringbuffer.c b/ringbuffer.c index fb94bc5..f9e8e1e 100644 --- a/ringbuffer.c +++ b/ringbuffer.c @@ -4,6 +4,7 @@ void initRingbuffer(ringbuffer *buf, int size) { + buf->count = 0; buf->tail = 0; buf->head = 0; buf->max = size; @@ -18,21 +19,28 @@ void freeRingbuffer(ringbuffer *buf) void addValue(ringbuffer *buf, int value) { + if (buf->count >= buf->max) + buf->count = buf->max; + if (buf->head >= buf->max) buf->head = 0; buf->position[buf->head] = value; buf->head++; - + buf->count++; } int getValue(ringbuffer *buf) { + if (buf->count < 0) + return -1; + if (buf->tail >= buf->max) buf->tail = 0; int value = buf->position[buf->tail]; buf->tail++; + buf->count--; return value; } diff --git a/ringbuffer.h b/ringbuffer.h index e79292c..f16e67b 100644 --- a/ringbuffer.h +++ b/ringbuffer.h @@ -2,6 +2,7 @@ #define RINGBUFFER_H typedef struct { + int count; int tail; int head; int max;