blob: e311c8fd5680e90457484e29ec8e873d6fc62c61 (
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
|
#include "../../include/std/buffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void tsl_buffer_init(TslBuffer *self) {
self->data = NULL;
self->size = 0;
self->capacity = 0;
}
void tsl_buffer_deinit(TslBuffer *self) {
free(self->data);
}
static int tsl_buffer_ensure_capacity(TslBuffer *self, size_t new_size) {
void *new_ptr;
if(new_size <= self->capacity)
return 1;
if(self->capacity != 0) {
size_t new_capacity = self->capacity;
while(new_capacity < new_size) {
new_capacity <<= 1;
}
new_size = new_capacity;
}
new_ptr = realloc(self->data, new_size);
if(!new_ptr) {
fprintf(stderr, "Error: buffer append failed. Reason: out of memory\n");
return 0;
}
self->data = new_ptr;
self->capacity = new_size;
return 1;
}
int tsl_buffer_append(TslBuffer *self, const void *data, size_t size) {
if(!tsl_buffer_ensure_capacity(self, self->size + size))
return 0;
memcpy((char*)self->data + self->size, data, size);
self->size += size;
return 1;
}
void* tsl_buffer_begin(TslBuffer *self) {
return self->data;
}
void* tsl_buffer_end(TslBuffer *self) {
return (char*)self->data + self->size;
}
|