Implementations
C Implementation
A naive C implementation:
#include <stdbool.h>
#define BUFFER_SIZE 10
typedef struct {
int read_head;
int write_head;
int count;
int data[BUFFER_SIZE];
} buffer_t;
void buffer_init(buffer_t *buf) {
buf->read_head = 0;
buf->write_head = 0;
buf->count = 0;
}
bool buffer_is_full(buffer_t *buf) {
return buf->count == BUFFER_SIZE;
}
bool buffer_is_empty(buffer_t *buf) {
return buf->count == 0;
}
bool buffer_write(buffer_t *buf, int value) {
if (buffer_is_full(buf)) {
return false;
}
buf->data[buf->write_head] = value;
buf->write_head = (buf->write_head + 1) % BUFFER_SIZE;
buf->count++;
return true;
}
bool buffer_read(buffer_t *buf, int *out_value) {
if (buffer_is_empty(buf)) {
return false;
}
*out_value = buf->data[buf->read_head];
buf->read_head = (buf->read_head + 1) % BUFFER_SIZE;
buf->count--;
return true;
}