summaryrefslogtreecommitdiff
path: root/src/buffer.c
blob: 51a3e3c88e4477bed15ac77e1dc4ff70ee81ef5e (plain) (blame)
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
//
// Created by Anshul Gupta on 4/4/25.
//

#include "buffer.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "alloc.h"

buffer_t buffer_new(size_t cap)
{
	buffer_t buf;

	if (cap == 0)
		return (buffer_t) {NULL, 0, 0};

	cap = (cap + 7) & ~7; // Align to 8 bytes
	buf.data = gmalloc(cap);
	if (!buf.data)
		abort();

	return (buffer_t) {buf.data, 0, cap};
}

void buffer_free(buffer_t buf) { gfree(buf.data); }

void buffer_reserve(buffer_t *buf, size_t cap)
{
	if (buf->cap >= cap)
		return;

	cap = (cap + 7) & ~7; // Align to 8 bytes
	uint8_t *new_data = grealloc(buf->data, cap);
	if (!new_data)
		abort();
	buf->data = new_data;
	buf->cap = cap;
}

void buffer_append(buffer_t *buf, const void *data, size_t len)
{
	if (buf->len + len > buf->cap)
		buffer_reserve(buf, buf->len + len);

	memcpy(buf->data + buf->len, data, len);
	buf->len += len;
	assert(buf->len <= buf->cap);
}