62 lines
1.6 KiB
C
62 lines
1.6 KiB
C
|
#include "utils.h"
|
||
|
|
||
|
int ring_buffer_read(struct ring_buffer* rb, char* dest, int size) {
|
||
|
int slice1 = size;
|
||
|
int slice2 = 0;
|
||
|
|
||
|
int used_space = ring_buffer_used_space (rb);
|
||
|
if (used_space < slice1)
|
||
|
slice1 = used_space;
|
||
|
|
||
|
if (RING_BUFFER_SIZE - rb->head < slice1) {
|
||
|
slice1 = RING_BUFFER_SIZE - rb->head;
|
||
|
slice2 = size - slice1;
|
||
|
if (used_space - slice1 < slice2)
|
||
|
slice2 = used_space - slice1;
|
||
|
}
|
||
|
|
||
|
memcpy(dest, rb->buffer + rb->head, slice1);
|
||
|
memcpy(dest+slice1, rb->buffer, slice2);
|
||
|
|
||
|
return slice1 + slice2;
|
||
|
}
|
||
|
|
||
|
void ring_buffer_ack_read(struct ring_buffer* rb, int size) {
|
||
|
if (size > ring_buffer_used_space (rb)) {
|
||
|
fprintf(stderr, "You try to ack more data than contained in the ring buffer\n");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
rb->head = (rb->head + size) % RING_BUFFER_SIZE;
|
||
|
}
|
||
|
|
||
|
int ring_buffer_write(struct ring_buffer* rb, char* source, int size) {
|
||
|
if (size > ring_buffer_free_space (rb)) {
|
||
|
fprintf(stderr, "You try to write more data than available space in the buffer\n");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
int slice1 = size;
|
||
|
int slice2 = 0;
|
||
|
|
||
|
if (RING_BUFFER_SIZE - rb->tail < slice1) {
|
||
|
slice1 = RING_BUFFER_SIZE - rb->tail;
|
||
|
slice2 = size - slice1;
|
||
|
}
|
||
|
|
||
|
memcpy(rb->buffer + rb->tail, source, slice1);
|
||
|
memcpy(rb->buffer, source + slice1, slice2);
|
||
|
|
||
|
rb->tail = (rb->tail + slice1 + slice2) % RING_BUFFER_SIZE;
|
||
|
|
||
|
return slice1 + slice2;
|
||
|
}
|
||
|
|
||
|
int ring_buffer_free_space(struct ring_buffer* rb) {
|
||
|
if (rb->head > rb->tail) return rb->head - rb->tail;
|
||
|
return RING_BUFFER_SIZE + (rb->tail - rb->head);
|
||
|
}
|
||
|
|
||
|
int ring_buffer_used_space(struct ring_buffer* rb) {
|
||
|
return RING_BUFFER_SIZE - ring_buffer_free_space (rb);
|
||
|
}
|