-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircbuffer.cpp
83 lines (75 loc) · 1.78 KB
/
circbuffer.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct circular_buffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
} circular_buffer;
static circular_buffer circ_buff;
void cb_init(size_t capacity)
{
size_t sz = 4;
circular_buffer *cb = &circ_buff;
cb->buffer = malloc(capacity * sz);
if(cb->buffer == NULL)
{
// handle error
}
cb->buffer_end = (char *)cb->buffer + capacity * sz;
cb->capacity = capacity;
cb->count = 0;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
void cb_free()
{
circular_buffer *cb = &circ_buff;
free(cb->buffer);
// clear out other fields too, just to be safe
}
int cb_push_back(int item)
{
circular_buffer *cb = &circ_buff;
if(cb->count == cb->capacity)
{
printf("Debug Buffer Full\n");
return -1;
}
std::memcpy(cb->head, &item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
return 0;
}
int cb_pop_front(int *item)
{
circular_buffer *cb = &circ_buff;
if(cb->count == 0)
{
return -1;
}
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
cb->count--;
return 0;
}
void mainzzzz(void)
{
int value=100;
cb_init(100);
cb_push_back(value);
value=0;
cb_pop_front(&value);
printf("%d\n",value);
}