-
Notifications
You must be signed in to change notification settings - Fork 8
/
uhf_buffer.c
71 lines (62 loc) · 1.6 KB
/
uhf_buffer.c
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
#include "uhf_buffer.h"
#include <stdlib.h>
#include <string.h>
Buffer* uhf_buffer_alloc(size_t initial_capacity) {
Buffer* buf = (Buffer*)malloc(sizeof(Buffer));
buf->data = (uint8_t*)malloc(sizeof(uint8_t) * initial_capacity);
if(!buf->data) {
free(buf);
return NULL;
}
buf->size = 0;
buf->capacity = initial_capacity;
buf->head = 0;
buf->tail = 0;
return buf;
}
bool uhf_buffer_append_single(Buffer* buf, uint8_t data) {
if(buf->closed) return false;
buf->data[buf->tail] = data;
buf->tail = (buf->tail + 1) % buf->capacity;
if(buf->size < buf->capacity) {
buf->size++;
} else {
buf->head = (buf->head + 1) % buf->capacity;
}
return true;
}
bool uhf_buffer_append(Buffer* buf, uint8_t* data, size_t data_size) {
if(buf->closed) return false;
for(size_t i = 0; i < data_size; i++) {
buf->data[buf->tail] = data[i];
buf->tail = (buf->tail + 1) % buf->capacity;
if(buf->size < buf->capacity) {
buf->size++;
} else {
buf->head = (buf->head + 1) % buf->capacity;
}
}
return true;
}
uint8_t* uhf_buffer_get_data(Buffer* buf) {
return &buf->data[buf->head];
}
size_t uhf_buffer_get_size(Buffer* buf) {
return buf->size;
}
bool uhf_is_buffer_closed(Buffer* buf) {
return buf->closed;
}
void uhf_buffer_close(Buffer* buf) {
buf->closed = true;
}
void uhf_buffer_reset(Buffer* buf) {
buf->head = 0;
buf->tail = 0;
buf->size = 0;
buf->closed = false;
}
void uhf_buffer_free(Buffer* buf) {
free(buf->data);
free(buf);
}