blob: c05e182397fdaeeba6c0433aafd2635128dea201 (
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
#include <merror.h>
#include <stdlib.h>
#include "lex.h"
/* init a empty string buffer */
inline void string_init(struct string *string)
{
string->len = 0;
string->size = 0;
string->allocated = true;
string->str = NULL;
}
/* free a string buffer */
inline void string_free(struct string *string)
{
if (string->allocated && string->str)
free(string->str);
}
/* clone a string buffer */
inline int string_clone(struct string *dst, const struct string *const src)
{
dst->len = src->len;
dst->size = src->len;
dst->allocated = src->allocated;
/// bss strings do not need to be
/// malloced or copied
if (src->allocated == false) {
dst->str = src->str;
return M_SUCCESS;
}
dst->str = malloc(sizeof(char) * src->len);
if (dst->str == NULL) {
PERROR("cannot alloc");
return M_ERROR;
}
memcpy(dst->str, src->str, sizeof(char) * src->len);
return M_SUCCESS;
}
/* moves a string */
inline void string_move(struct string *dst, struct string *src)
{
dst->len = src->len;
dst->size = src->len;
dst->allocated = src->allocated;
dst->str = src->str;
// delete ptr in src
src->str = NULL;
}
/* pushes a char onto a string */
int string_push(struct string *string, char c)
{
if (string->len >= string->size) {
int len = string->size ? string->size * 2 : 8;
char *new = realloc(string->str, sizeof(char) + len);
if (new == NULL) {
PERROR("cannot realloc");
return M_ERROR;
}
string->size = len;
string->str = new;
}
string->str[string->len++] = c;
return M_SUCCESS;
}
void string_bss(struct string *string, char *src)
{
int len = strlen(src);
string->str = src;
string->len = len;
string->size = len;
string->allocated = false;
}
|