forked from hvoigt/hamcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_buffer.c
More file actions
78 lines (62 loc) · 1.68 KB
/
data_buffer.c
File metadata and controls
78 lines (62 loc) · 1.68 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
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "data_buffer.h"
#define printlog printf
void *die_malloc(size_t size)
{
void *mem = malloc(size);
if (mem == NULL) {
printlog("Failed to allocate %lu bytes. Exiting", size);
exit(1);
}
return mem;
}
struct data_buffer *data_buffer_create()
{
struct data_buffer *msg = (struct data_buffer *)
die_malloc(sizeof(struct data_buffer));
msg->data = NULL;
msg->data_len = 0;
msg->alloc_len = 0;
return msg;
}
static void alloc_more(struct data_buffer *buffer, size_t len)
{
size_t new_len = (buffer->data_len + len) * 2;
new_len = new_len > buffer->alloc_len * 2 ? new_len :
buffer->alloc_len * 2;
buffer->data = (char *) realloc(buffer->data, new_len);
if (buffer->data == NULL) {
printlog("Error no more memory!");
exit(-1);
}
buffer->alloc_len = new_len;
}
void data_buffer_append(struct data_buffer *buffer, const char *data, size_t len)
{
if (buffer->data_len + len > buffer->alloc_len)
alloc_more(buffer, len);
memcpy(buffer->data + buffer->data_len, data, len);
buffer->data_len += len;
}
int data_buffer_printf(struct data_buffer *buffer, const char
*format, ...)
{
va_list args;
va_start(args, format);
int written = vsnprintf(buffer->data, buffer->alloc_len, format, args);
va_end(args);
if (written >= buffer->alloc_len)
alloc_more(buffer, written);
va_start(args, format);
written = vsnprintf(buffer->data, buffer->alloc_len, format, args);
va_end(args);
if (written >= buffer->alloc_len) {
printlog("Error: Failed to write into buffer");
exit(-1);
}
buffer->data_len = written;
return written;
}