Fumofumotris/source/fumoengine/include/ringbuffer.c

69 lines
1.5 KiB
C
Raw Normal View History

2024-04-25 20:08:24 +00:00
#include "ringbuffer.h"
2024-04-30 21:41:31 +00:00
2024-04-25 20:08:24 +00:00
#include <string.h>
2024-04-30 21:41:31 +00:00
2024-05-07 22:10:15 +00:00
void *get_ptr(RingBufferT T, struct RingBufferHead *head, usize i)
2024-04-25 20:08:24 +00:00
{
2024-04-30 04:43:41 +00:00
u8 *bytes = (u8 *)head;
return bytes + T->OFFSET + T->SIZE * i;
2024-04-25 20:08:24 +00:00
}
2024-05-07 22:10:15 +00:00
usize RingBufferEmpty(RingBufferT T, struct RingBufferHead *head)
2024-04-25 20:08:24 +00:00
{
2024-04-29 20:01:48 +00:00
return T->LEN - head->len;
2024-04-25 20:08:24 +00:00
}
2024-05-07 22:10:15 +00:00
void *RingBufferGet(RingBufferT T, struct RingBufferHead *head, usize i)
2024-04-29 20:01:48 +00:00
{
2024-05-07 22:10:15 +00:00
usize wrap_i = (head->start + i) % T->LEN;
2024-04-29 20:01:48 +00:00
return get_ptr(T, head, wrap_i);
}
void *RingBufferNext(RingBufferT T, struct RingBufferHead *head)
{
2024-05-07 22:10:15 +00:00
usize wrap_i = (head->start + head->len) % T->LEN;
2024-04-29 20:01:48 +00:00
return get_ptr(T, head, wrap_i);
}
void RingBufferAdd(RingBufferT T, struct RingBufferHead *dest, void *item)
{
memcpy(RingBufferNext(T, dest), item, T->SIZE);
2024-04-30 04:43:41 +00:00
dest->len += 1;
2024-04-29 20:01:48 +00:00
}
void RingBufferTransfer(
RingBufferT T,
struct RingBufferHead *dest,
2024-04-30 04:43:41 +00:00
struct RingBufferHead *tmp
2024-04-29 20:01:48 +00:00
) {
2024-05-15 22:10:47 +00:00
usize copy_max = min(T->LEN - dest->len, tmp->len);
2024-04-29 20:01:48 +00:00
2024-05-07 22:10:15 +00:00
for (usize i = 0; i < copy_max; i++) {
2024-04-30 04:43:41 +00:00
void *to = RingBufferGet(T, dest, dest->len + i);
void *from = RingBufferGet(T, tmp, i);
2024-04-29 20:01:48 +00:00
memcpy(to, from, T->SIZE);
}
dest->len += copy_max;
2024-04-30 04:43:41 +00:00
tmp->len -= copy_max;
2024-04-29 20:01:48 +00:00
}
2024-05-07 22:10:15 +00:00
usize RingBufferOut(
2024-04-30 04:43:41 +00:00
RingBufferT T,
2024-05-07 22:10:15 +00:00
usize n,
2024-04-30 04:43:41 +00:00
void *dest,
struct RingBufferHead *src
) {
2024-05-15 22:10:47 +00:00
usize copy_max = min(n, src->len);
2024-04-25 20:08:24 +00:00
2024-05-07 22:10:15 +00:00
for (usize i = 0; i < copy_max; i++) {
2024-04-30 04:43:41 +00:00
void *to = (u8 *)dest + i * T->SIZE;
2024-04-29 20:01:48 +00:00
void *from = RingBufferGet(T, src, i);
memcpy(to, from, T->SIZE);
2024-04-25 20:08:24 +00:00
}
2024-04-30 04:43:41 +00:00
src->len -= copy_max;
2024-04-29 20:01:48 +00:00
return copy_max;
2024-04-25 20:08:24 +00:00
}