Peeking beyond either end of the ring buffer must return EOF. We
first compute the index, then check whether it's in range.
Unfortunately, the index computation r->prod - -n can wrap around
while r->prod is still <= RING_SIZE. If it happens, ring_peek()
returns r->buf[(r->prod - -n) % RING_SIZE] instead of EOF.
Currently harmless, because no caller peeks out of range.
Signed-off-by: Markus Armbruster <armbru@pond.sub.org>
* ringbuf.c: Simple ring buffer
*
* Known contributors to this file:
- * Markus Armbruster, 2007-2009
+ * Markus Armbruster, 2007-2015
*/
#include <config.h>
assert(-RING_SIZE - 1 <= n && n <= RING_SIZE);
- idx = n >= 0 ? r->cons + n : r->prod - -n;
- if (idx < r->cons && idx >= r->prod)
- return EOF;
+ if (n >= 0) {
+ idx = r->cons + n;
+ if (idx >= r->prod)
+ return EOF;
+ } else {
+ /* Beware, r->prod - -n can wrap around, avoid that */
+ if (r->prod < r->cons + -n)
+ return EOF;
+ idx = r->prod - -n;
+ }
+
return r->buf[idx % RING_SIZE];
}