forked from mgnauck/wgslminify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.c
52 lines (40 loc) · 958 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
#include "buffer.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const size_t default_increment = 64;
bool write_buf_inc(buffer *buf, char value, size_t buf_inc)
{
if(buf->pos == buf->size) {
char *new_ptr = realloc(buf->ptr, buf->size + buf_inc);
if(!new_ptr) {
fprintf(stderr, "Allocation failed: %s\n", strerror(errno));
return true;
}
buf->ptr = new_ptr;
buf->size += buf_inc;
}
buf->ptr[buf->pos++] = value;
return false;
}
bool write_buf(buffer* buf, char value)
{
return write_buf_inc(buf, value, default_increment);
}
char *buf_to_str(buffer *buf, bool free_buf)
{
char *str = NULL;
if(!write_buf_inc(buf, '\0', 1)) {
str = strdup(buf->ptr);
if(!str)
fprintf(stderr, "Allocation failed: %s\n", strerror(errno));
}
if(free_buf) {
free(buf->ptr);
buf->ptr = NULL;
buf->size = 0;
buf->pos = 0;
}
return str;
}