-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathringbuf_dynamic.c
More file actions
56 lines (48 loc) · 1.12 KB
/
ringbuf_dynamic.c
File metadata and controls
56 lines (48 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
typedef struct {
void *buffer;
void *buffer_end;
size_t capacity;
size_t count;
size_t size;
void *head;
void *tail;
} ringBuffer_t;
void rb_init(ringBuffer_t *cb, size_t capacity, size_t size)
{
cb->buffer = malloc(capacity * size);
cb->buffer_end = (char *)cb->buffer + capacity * size;
cb->capacity = capacity;
cb->count = 0;
cb->size = size;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
void rb_free(ringBuffer_t *cb)
{
free(cb->buffer);
}
void rb_push(ringBuffer_t *cb, const void *item)
{
memcpy(cb->head, item, cb->size);
cb->head = (char*)cb->head + cb->size;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
}
uint8_t* rb_pop(ringBuffer_t *cb)
{
if (cb->count == 0)
return 0;
//memcpy(item, cb->tail, cb->size);
uint8_t *pMem = (uint8_t *)cb->tail;
cb->tail = (char*)cb->tail + cb->size;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
cb->count--;
return pMem;
}