From 74c82648f21d11acc04eafc1844d832b5c071a8d Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Tue, 30 Apr 2013 17:28:32 +0930 Subject: [PATCH] Fix rotbuf_advance(), add rotbuf_remain() --- rotbuf.h | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/rotbuf.h b/rotbuf.h index 3a2472c1..5351084c 100644 --- a/rotbuf.h +++ b/rotbuf.h @@ -109,6 +109,20 @@ __ROTBUF_INLINE size_t rotbuf_position(struct rotbuf *rb) return (rb->cursor - rb->buf) + (rb->ebuf - rb->start); } +/* Return the total number of bytes remaining to be advanced to reach the end + * of the given rotated buffer. If the buffer has overrun, this will be zero. + * + * @author Andrew Bettison + */ +__ROTBUF_INLINE size_t rotbuf_remain(struct rotbuf *rb) +{ + if (rb->wrap) + return 0; + if (rb->cursor < rb->start) + return rb->start - rb->cursor; + return (rb->ebuf - rb->cursor) + (rb->start - rb->buf); +} + /* Return the total number of bytes advanced through the given rotated buffer, including any * overrun. * @@ -132,13 +146,17 @@ __ROTBUF_INLINE void rotbuf_advance(struct rotbuf *rb, size_t len) if (rb->wrap) rb->wrap += len; else if (len) { - rb->cursor += len; - if (rb->cursor >= rb->ebuf) { - rb->cursor -= rb->buf - rb->ebuf; - if (rb->cursor >= rb->start) { - rb->wrap = 1 + rb->cursor - rb->start; + if (rb->cursor >= rb->start) { + if ((rb->cursor += len) >= rb->ebuf) { + rb->cursor -= rb->ebuf - rb->buf; + if (rb->cursor >= rb->start) { + rb->wrap = 1 + (rb->cursor - rb->start); rb->cursor = rb->start; + } } + } else if ((rb->cursor += len) >= rb->start) { + rb->wrap = 1 + (rb->cursor - rb->start); + rb->cursor = rb->start; } } }