forked from martanne/vis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.c
54 lines (47 loc) · 1009 Bytes
/
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
#include <stdlib.h>
#include <string.h>
#include "buffer.h"
#include "util.h"
#define BUF_SIZE 1024
bool buffer_alloc(Buffer *buf, size_t size) {
if (size < BUF_SIZE)
size = BUF_SIZE;
if (buf->size < size) {
if (buf->size > 0)
size *= 2;
buf->data = realloc(buf->data, size);
if (!buf->data) {
buf->size = 0;
buf->len = 0;
return false;
}
buf->size = size;
}
return true;
}
void buffer_truncate(Buffer *buf) {
buf->len = 0;
}
void buffer_free(Buffer *buf) {
if (!buf)
return;
free(buf->data);
buf->data = NULL;
buf->len = 0;
buf->size = 0;
}
bool buffer_put(Buffer *buf, const void *data, size_t len) {
if (!buffer_alloc(buf, len))
return false;
memcpy(buf->data, data, len);
buf->len = len;
return true;
}
bool buffer_append(Buffer *buf, const void *data, size_t len) {
size_t rem = buf->size - buf->len;
if (len > rem && !buffer_alloc(buf, buf->size + len - rem))
return false;
memcpy(buf->data + buf->len, data, len);
buf->len += len;
return true;
}