blob: 05f99f26ee58998c0c25b9633a995ea5b25e6548 (
plain)
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
|
#include "buffer.h"
#include "alloc.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
void buffer_init(Buffer *self) {
self->data = NULL;
self->size = 0;
self->capacity = 0;
}
void buffer_deinit(Buffer *self) {
free(self->data);
self->data = NULL;
self->size = 0;
self->capacity = 0;
}
static void buffer_ensure_capacity(Buffer *self, size_t new_size) {
size_t new_capacity = self->capacity;
if(new_size <= self->capacity)
return;
if(new_capacity == 0)
new_capacity = 8;
while(new_capacity < new_size) {
/* new_capacity *= 1.5 */
new_capacity += (new_capacity >> 1);
}
self->data = realloc_or_crash(self->data, new_capacity);
self->capacity = new_capacity;
}
void buffer_append(Buffer *self, const void *data, size_t size) {
buffer_ensure_capacity(self, self->size + size);
memcpy((char*)self->data + self->size, data, size);
self->size += size;
}
void* buffer_pop(Buffer *self, size_t size) {
assert(self->size >= size);
self->size -= size;
return (char*)self->data + self->size;
}
void* buffer_begin(Buffer *self) {
return self->data;
}
void* buffer_end(Buffer *self) {
return (char*)self->data + self->size;
}
size_t buffer_get_size(Buffer *self, size_t type_size) {
return self->size / type_size;
}
void buffer_clear(Buffer *self) {
self->size = 0;
}
|