forked from aarond10/https_dns_proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring_buffer.c
More file actions
92 lines (82 loc) · 2.19 KB
/
ring_buffer.c
File metadata and controls
92 lines (82 loc) · 2.19 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
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
84
85
86
87
88
89
90
91
92
#include <stddef.h>
#include <stdio.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include <stdlib.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include <string.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include "ring_buffer.h"
struct ring_buffer
{
char ** storage;
uint32_t size;
uint32_t next; // next slot to use in storage
uint8_t full;
} __attribute__((packed)) __attribute__((aligned(32)));
void ring_buffer_init(struct ring_buffer **rbp, uint32_t size)
{
*rbp = NULL;
if (size < 1) {
return;
}
struct ring_buffer *rb = (struct ring_buffer *)calloc(1, sizeof(struct ring_buffer));
if (!rb) {
return;
}
rb->storage = (char**)calloc(size, sizeof(char*));
if (!rb->storage) {
free((void*) rb);
return;
}
rb->size = size;
*rbp = rb;
}
void ring_buffer_free(struct ring_buffer **rbp)
{
struct ring_buffer *rb = *rbp;
if (!rb->storage) {
return;
}
for (uint32_t i = 0; i < rb->size; i++) {
if (rb->storage[i]) {
free(rb->storage[i]);
}
}
free((void*) rb->storage);
free((void*) rb);
*rbp = NULL;
}
void ring_buffer_dump(struct ring_buffer *rb, FILE * file)
{
if (!rb->storage) {
return;
}
if (rb->next == 0 && !rb->full) {
return; // empty
}
uint32_t current = rb->full ? rb->next : 0;
do
{
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
(void)fprintf(file, "%s\n", rb->storage[current]);
if (++current == rb->size) {
current = 0;
}
}
while (current != rb->next);
(void)fflush(file);
}
void ring_buffer_push_back(struct ring_buffer *rb, char* data, uint32_t size)
{
if (!rb->storage) {
return;
}
if (rb->storage[rb->next]) {
free(rb->storage[rb->next]);
}
rb->storage[rb->next] = (char*)malloc(size + 1);
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
memcpy(rb->storage[rb->next], data, size);
rb->storage[rb->next][size] = '\0';
if (++rb->next == rb->size) {
rb->next = 0;
rb->full = 1;
}
}