ringbuf/ringbuf.h

40 lines
1.2 KiB
C
Raw Normal View History

2024-06-23 14:08:57 +02:00
/* SPDX-License-Identifier: MIT */
2024-06-23 16:27:51 +02:00
#pragma once
#ifndef rb_size_t
#define rb_size_t int
#endif
2024-06-27 02:35:39 +02:00
/** Signatures of generic functions */
typedef void *(*ALLOC_T)(rb_size_t);
typedef void *(*MEMCPY_T)(void *, const void *, rb_size_t);
2024-06-23 14:15:56 +02:00
/**
2024-06-23 14:08:57 +02:00
* Ring buffer, also known as circular buffer.
*/
struct RingBuf {
2024-06-23 16:27:51 +02:00
rb_size_t struct_size; /* Size of the struct */
rb_size_t capacity; /* The physical capacity of the entire ringbuf */
2024-06-27 02:35:39 +02:00
rb_size_t size; /* The current size of the ring buffer */
2024-06-23 16:27:51 +02:00
rb_size_t write_idx; /* The write head */
rb_size_t read_idx; /* THe read head */
2024-06-27 00:05:49 +02:00
void **buffer; /* The actual data */
2024-06-23 14:08:57 +02:00
};
enum WriteResult { CollisionError, Ok };
/** Initialize the ring buffer */
2024-06-27 01:21:25 +02:00
void rb_init(struct RingBuf *rb, rb_size_t capacity, void *(*alloc)(rb_size_t),
rb_size_t struct_size);
2024-06-23 14:08:57 +02:00
/** Insert data to the ring buffer */
2024-06-23 16:27:51 +02:00
enum WriteResult rb_push(struct RingBuf *rb, void *data[], rb_size_t amount,
void *(*memcpy)(void *, const void *, rb_size_t));
2024-06-23 14:08:57 +02:00
/** Read data from the ring buffer */
2024-06-27 01:21:25 +02:00
void rb_read(struct RingBuf *rb, void *dest, int amount);
/** Free the ring buffer */
void rb_destroy(struct RingBuf *rb, void(free)());