generic circular buffer implementation in C
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
circbuf/circbuf.h

52 lines
1.0 KiB

9 years ago
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
9 years ago
// Circular Character Buffer implementation
typedef struct CircularBuffer_struct {
uint8_t *buf;
size_t cap;
size_t lr; // last read pos
size_t nw; // next write pos
} circbuf_t;
9 years ago
/** Init a buffer */
void cbuf_init(circbuf_t *inst, size_t capacity);
/** Deinit a buffer (free the memory) */
void cbuf_deinit(circbuf_t *inst);
9 years ago
/** Test for full buffer */
bool cbuf_full(circbuf_t *inst);
9 years ago
/** Test for empty buffer */
bool cbuf_empty(circbuf_t *inst);
9 years ago
/** Write a byte to buffer, returns success */
bool cbuf_write(circbuf_t *inst, uint8_t b);
9 years ago
/**
* Read a byte from the buffer, return susccess.
* If `b` is NULL, the read byte is discarded.
*/
bool cbuf_read(circbuf_t *inst, uint8_t *b);
9 years ago
/**
* Get n-th byte from the buffer, without removing it.
* Returns false if offset is invalid (ie. empty buffer).
*/
bool cbuf_peek(circbuf_t *inst, size_t nth, uint8_t *b);
9 years ago
/** Remove all data from buffer */
void cbuf_clear(circbuf_t *inst);