From 88cb4cea69a1eee8091f6560457d77bf3c4b3cf3 Mon Sep 17 00:00:00 2001 From: Luis Alves Date: Mon, 27 May 2019 02:25:04 +0100 Subject: [PATCH] ringbuffer: fix rb_get_bytes_used (modulo overflow) --- ringbuffer.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ringbuffer.c b/ringbuffer.c index b0605ac..df4106a 100644 --- a/ringbuffer.c +++ b/ringbuffer.c @@ -27,7 +27,10 @@ int rb_init(struct ringbuffer_t *rb) int rb_get_bytes_used(struct ringbuffer_t* rb) { - return((rb->tail - rb->head) % sizeof(rb->buf)); + if (rb->tail >= rb->head) + return (rb->tail - rb->head); + else + return (rb->tail - rb->head) + sizeof(rb->buf); } int rb_read(struct ringbuffer_t *rb, uint8_t* buf, int count) @@ -81,7 +84,7 @@ int rb_write(struct ringbuffer_t *rb, uint8_t* buf, int count) { int to_copy; - int bytes_used = (rb->tail - rb->head) % sizeof(rb->buf); + int bytes_used = rb_get_bytes_used(rb); //fprintf(stderr,"bytes_used = %d\n",bytes_used); if (bytes_used + count >= (int)sizeof(rb->buf)) {