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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
#include "strbuf.h"
#include <string.h>
#ifdef SAFE_STR
#include <stdio.h>
#define ERR(s) fprintf(stderr, "\x1B[0;31mERR\x1b[m (strbuf %3i): %s\n", __LINE__, s)
#endif
int CONSTRUCTOR_DECL(strbuf) {
this->mem = NULL;
this->alloc = 0;
this->len = 0;
this->ptr = 0;
return 0;
}
int CONSTRUCTOR_DECL(strbuf, size_t len) {
this->mem = calloc(sizeof(*this->mem), len);
this->alloc = len;
this->ptr = 0;
this->len = 0;
return 0;
}
int strbuf_realloc(strbuf* str, size_t len) {
#ifdef SAFE_STR
if (str->mem == NULL || str->alloc == 0) {
ERR("String memory not initialized");
return 1;
}
#endif
str->mem = realloc(str->mem, len);
str->alloc = len;
return 0;
}
int strbuf_free(strbuf* str) {
#ifdef SAFE_STR
if (str->alloc == 0 || str->mem == NULL) {
ERR("String not allocated");
return 1;
}
#endif
free (str->mem);
str->alloc = 0;
return 0;
}
int strbuf_append(strbuf* s, char c) {
s->mem[s->len] = c;
s->ptr = ++s->len;
return 0;
}
int strbuf_cap(strbuf* s) {
return strbuf_append(s, 0);
}
int strbuf_copy(strbuf* dest, strbuf* src) {
#ifdef SAFE_STR
if (dest->alloc < src->len) {
ERR("Not enough memmory allocated");
return 1;
}
#endif
dest->len = src->len;
memcpy(dest->mem, src->mem, src->len);
return 0;
}
int strbuf_cmp(strbuf* a, strbuf* b) {
return strcmp(a->mem, b->mem);
}
int strbuf_c(strbuf* a, char* b) {
return strcmp(a->mem, b) == 0;
}
char* charat(strbuf* s, int idx) {
#ifdef SAFE_STR
if (idx > s->len) {
ERR("Index out of bounds");
return (char*) -1;
}
#endif
return &s->mem[idx];
}
char* strbuf_cur(strbuf* s) {
return &s->mem[s->ptr];
}
int strbuf_reset(strbuf* s)
{
s->ptr = 0;
return 0;
}
int strbuf_init_copy(strbuf* dest, strbuf* src) {
#ifdef SAFE_STR
if (dest->alloc != 0) {
printf("%lu ", dest->alloc);
ERR("Dest already allocated");
return 1;
}
#endif
CONSTRUCT(strbuf, dest, src->len + 1);
strbuf_copy(dest, src);
return 0;
}
char* strbuf_end(strbuf* s) {
return &s->mem[s->len];
}
int strbuf_soft_reset(strbuf* s) {
s->ptr = s->len = 0;
return 0;
}
|