Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Circular Buffer

Name: Anonymous 2011-01-06 10:01

Hi /prog/

Some time ago I started to write a well designed library of useful algorithms in C. As long as I needed more stuff, I simply added pieces.

Today I'm pretty bored, so I'd like to add an implementation for circular buffers. Since however I don't really need it (it's just for fun), I'm wondering which is the most useful semantics for a circular buffer.

For instance:
[list]
[*] Is it worthy to write a primitive which applies a function on every availabe element from the oldest to the most recent?
[*] What if the buffer is full and I want to insert a new element? Should I overwrite the oldest one or should I make the request fail instead?
[/list]

Which are, in general, the kind of functionalities you'll prefer?

Name: Anonymous 2011-01-06 10:54

>>1

#ifdef __STDC_VERSION__
#if (__STDC_VERSION__ >= 199901L)
#define _inline inline
#else
#define _inline
#endif
#else
#define _inline
#endif

#ifdef __GNUC__
#define _pure __attribute__ ((pure))
#define _pure_inline __attribute__ ((pure) (always_inline))
#else
#define _pure
#define _pure_inline
#endif

typedef struct cbuf_t {
   int *buffer;
   int length;
} cbuf_t;

cbuf_t *cbuf_new(int);
_inline int cbuf_at(cbuf_t *, int) _pure_inline;
int cbuf_ref(cbuf_t *, int) _pure;
void cbuf_set(cbuf_t *, int, int);
void cbuf_destroy(cbuf_t *);

cbuf_t *cbuf_new(int length) {
   cbuf_t *buf = malloc(sizeof(buf));
   buf->buffer = malloc(sizeof(int)*length);
   buf->length = length;
   return buf;
}
int cbuf_at(cbuf_t *buf, int i) { //
   return (i>=buf->length)?(i-buf->length):i;
int cbuf_ref(cbuf_t *BUFFA, int index) {
   return BUFFA->buffer[cbuf_at(index)];
}
void cbuf_set(cbuf_t *BUFFA, int index, int val) {
   BUFFA->buffer[cbuf_at(index)] = val;
}
void cbuf_destroy(cbuf_t *buf) {
   free(buf->buffer);
   free(buf);
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List