ringbuf/ringbuf.h
2024-06-30 20:06:30 +02:00

43 lines
1.4 KiB
C

/* SPDX-License-Identifier: MIT */
#pragma once
#ifndef rb_size_t
#define rb_size_t int
#endif
/** Signatures of generic functions */
typedef void *(*ALLOC_T)(rb_size_t);
typedef void *(*MEMCPY_T)(void *, const void *, rb_size_t);
/**
* Ring buffer, also known as circular buffer.
*/
struct RingBuf {
rb_size_t struct_size; /* Size of the struct */
rb_size_t capacity; /* The physical capacity of the entire ringbuf */
rb_size_t count; /* The number of elements in the buffer */
void *write_head; /* Address of the write head */
void *read_head; /* Address of the read head */
void *buffer; /* The actual data */
void *buffer_end; /* The end of the buffer */
} __attribute__((packed));
// TODO: Perhaps unify these to RBResult?
enum WriteResult { Full, WriteOk }; /** Result of a write */
enum ReadResult { Empty, ReadOk }; /** Result of a read */
/** Initialize the ring buffer */
void rb_init(struct RingBuf *rb, rb_size_t capacity, void *(*alloc)(rb_size_t),
rb_size_t struct_size);
/** Insert data to the ring buffer */
enum WriteResult rb_push_back(struct RingBuf *rb, const void *item,
MEMCPY_T memcpy_fn);
/** Read data from the ring buffer */
enum ReadResult rb_pop_front(struct RingBuf *rb, void *item);
/** Free the ring buffer */
void rb_destroy(struct RingBuf *rb, void(free)());