[systemd-devel] [RFC 02/12] ring: add basic ring-buffer helper

Lennart Poettering lennart at poettering.net
Tue Dec 10 16:39:38 PST 2013


On Thu, 28.11.13 09:19, David Herrmann (dh.herrmann at gmail.com) wrote:

> > Hmm, so if end and start match the buffer is empty? So you can never
> > fill it entirely? Or am I missing something?
> >
> > I'd always maintain start index + fill level instead of a start
> > index + end index, to avoid the confusion regarding the fill-level...
> 
> Well, start+end is how ring-buffers were implemented historically. I
> think the reason is that "wrapping over" is easier to calculate for
> indices than for lengths (you cannot do: r->len = (r->len + 1) &
> RING_MASK). Even all examples on wikipedia use two indices
> (http://en.wikipedia.org/wiki/Circular_buffer). And all kernel
> ring-buffers use start/end..

Well, you only need the wrapping over for the reading side, the writing
side never needs that.

int append(..., length, ...) {
         ...
         if (current_length + length > MAX_LENGTH)
                return -ENOBUFS;
         ...
         current_length += length;
         ...
}

int remove(..., length, ...) {
         ...
         if (length > current_length)
                return -EAGAIN;
         ...
         rindex = (rindex + length) & RING_MASK;
         current_length -= length;
         ...
}

Lennart

-- 
Lennart Poettering, Red Hat


More information about the systemd-devel mailing list