-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer_lib.c
More file actions
65 lines (53 loc) · 1.52 KB
/
buffer_lib.c
File metadata and controls
65 lines (53 loc) · 1.52 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "buffer_lib.h"
#define DEFAULT_INIT_SIZE 512
#define ALLOC_CUR_REALLOC(buf, temp_size) \
if (buf->alloc_cur <= (buf->len + temp_size)) { \
while (buf->alloc_cur <= (buf->len + temp_size)) { \
buf->alloc_cur += DEFAULT_INIT_SIZE; \
} \
buf->val = realloc(buf->val, buf->alloc_cur); \
}
void buffer_init(buffer* buf) {
memset(buf, 0, sizeof(buffer));
buf->val = malloc(DEFAULT_INIT_SIZE);
buf->alloc_cur = DEFAULT_INIT_SIZE;
*buf->val = 0;
}
void buffer_string_append(buffer* buf, const char* val) {
size_t buf_len = strlen(val);
ALLOC_CUR_REALLOC(buf, buf_len);
memcpy(buf->val + buf->len, val, buf_len);
buf->len += buf_len;
}
void buffer_append_n(buffer* buf, const char* val, size_t len) {
ALLOC_CUR_REALLOC(buf, len);
memcpy(buf->val + buf->len, val, len);
buf->len += len;
}
void buffer_append_char(buffer* buf, const char val) {
ALLOC_CUR_REALLOC(buf, 1);
buf->val[buf->len++] = val;
}
void buffer_begin(buffer* buf) {
*buf->val = 0;
buf->len = 0;
}
void buffer_begin_reinit(buffer* buf) {
if (buf->val) {
free(buf->val);
buf->val = malloc(DEFAULT_INIT_SIZE);
*buf->val = 0;
buf->len = 0;
buf->alloc_cur = DEFAULT_INIT_SIZE;
}
}
void buffer_finalize(buffer* buf) {
if (buf->val) free(buf->val);
buf->val = NULL;
buf->len = 0;
buf->alloc_cur = 0;
}