-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.c
More file actions
75 lines (60 loc) · 1.63 KB
/
Copy pathbuffer.c
File metadata and controls
75 lines (60 loc) · 1.63 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
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "errors.h"
#include "buffer.h"
void buffer_init(struct buffer *b) {
b->data = NULL;
b->size = 0;
b->alloc_size = 0;
b->write_pos = 0;
}
#define CHUNK_SIZE 128
static void buffer_resize(struct buffer *b, size_t size) {
char *temp;
temp = realloc(b->data, size);
if(temp == NULL)
no_memory();
b->data = temp;
b->alloc_size = size;
}
void buffer_add_char(struct buffer *b, char c) {
size_t to_alloc;
if(b == NULL)
return;
if(b->write_pos >= b->alloc_size) {
to_alloc = CHUNK_SIZE * (b->write_pos / CHUNK_SIZE + 1);
buffer_resize(b, to_alloc);
}
if(b->write_pos > b->size)
memset(b->data + b->size, 0, b->write_pos - b->size);
b->data[b->write_pos] = c;
b->write_pos++;
if(b->write_pos > b->size)
b->size = b->write_pos;
}
/* adds a string but not the \0 at the end to the buffer */
void buffer_add_str(struct buffer *b, const char *s) {
buffer_add_mem(b, s, strlen(s));
}
/* adds a chunk of memory with size s to the buffer */
void buffer_add_mem(struct buffer *b, const void *m, size_t s) {
size_t total_maximum, to_alloc;
if(b == NULL || m == NULL)
return;
total_maximum = b->write_pos + s;
if(total_maximum >= b->alloc_size) {
to_alloc = CHUNK_SIZE * (total_maximum / CHUNK_SIZE + 1);
buffer_resize(b, to_alloc);
}
if(b->write_pos > b->size)
memset(b->data + b->size, 0, b->write_pos - b->size);
memcpy(b->data + b->write_pos, m, s);
b->write_pos = total_maximum;
if(total_maximum > b->size)
b->size = total_maximum;
}
void buffer_add_u16l(struct buffer *b, uint16_t i) {
buffer_add_char(b, i & 0xff);
buffer_add_char(b, i >> 8);
}