2 * Copyright (C) 2006 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file ringbuffer.c simple ringbuffer implementation */
10 #include "ringbuffer.h"
14 * holds all information about one ring buffer
16 * It is intentionally not exported via ringbuffer.h. Think abstract.
23 * the size of this ring buffer
29 * the actual entries of the ringbuffer
35 * the next entry will be added at this position
40 * how many entries the ring buffer contains
46 * initialize a new ringbuffer
48 * @param size the number of entries the ringbuffer holds
50 * This function initializes a circular ring buffer which can hold up to \a
51 * size entries of arbitrary type. If performance is an issue, \a size should
52 * be a power of two to make the underlying modulo operations cheap. Arbitrary
53 * many ringbuffers may be initialized via this function. Each ringbuffer is
54 * identified by a 'cookie'.
56 * Return value: A 'cookie' which identifies the ringbuffer just created and
57 * which must be passed to ringbuffer_add() and ringbuffer_get().
59 void *ringbuffer_new(unsigned size
)
61 struct ringbuffer
*rb
= para_calloc(sizeof(struct ringbuffer
));
62 rb
->entries
= para_calloc(size
* sizeof(void *));
68 * add one entry to a ringbuffer
70 * @param cookie the ringbuffer identifier
71 * @param data the data to be inserted
73 * insert \a data into the ringbuffer associated with \a cookie. As soon as
74 * the ringbuffer fills up, its oldest entry is disregarded and replaced by \a
77 * \return The old \a data pointer which is going to be disregarded, or
78 * NULL if the ringbuffer is not yet full.
80 void *ringbuffer_add(void *cookie
, void *data
)
82 struct ringbuffer
*rb
= cookie
;
83 void *ret
= rb
->entries
[rb
->head
];
84 rb
->entries
[rb
->head
] = data
;
85 rb
->head
= (rb
->head
+ 1) % rb
->size
;
86 if (rb
->filled
< rb
->size
)
92 * get one entry from a ringbuffer
94 * @param cookie the ringbuffer identifier
95 * @param num the number of the entry
97 * \return A pointer to data previously added, or NULL if entry number
98 * \a num is not available. \a num counts backwards from zero, i.e.
99 * ringbuffer_get_entry(0) gets the entry which was added most recently.
101 void *ringbuffer_get(void *cookie
, int num
)
103 struct ringbuffer
*rb
= cookie
;
104 int pos
= (rb
->head
+ rb
->size
- 1 - num
) % rb
->size
;
105 // fprintf(stderr, "pos = %d\n", pos);
106 return rb
->entries
[pos
];
110 * get the number of entries in the ring buffer
112 * @param cookie the ringbuffer identifier
114 * This function always succeeds and never returns a number greater than the
115 * size of the ring buffer.
117 unsigned ringbuffer_filled(void *cookie
)
119 struct ringbuffer
*rb
= cookie
;