This repository has been archived by the owner on Dec 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathstringbuilder.c
77 lines (66 loc) · 1.43 KB
/
stringbuilder.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <string.h>
#include "stringbuilder.h"
static inline size_t align_size(size_t num)
{
return (num + 1023) / 1024 * 1024;
}
StringBuilder *string_builder_new(void)
{
StringBuilder *sb;
sb = malloc(sizeof(struct _StringBuilder));
sb->allocated_len = 0;
sb->len = 0;
sb->str = NULL;
return sb;
}
void string_builder_reserve(StringBuilder *sb, size_t len)
{
if (!sb || !len)
return;
if (sb->len + len >= sb->allocated_len)
{
sb->allocated_len = align_size(sb->len + len + 1);
sb->str = realloc(sb->str, sb->allocated_len);
}
}
void string_builder_append_length(StringBuilder *sb, const char *str, size_t len)
{
if (!sb || !str || !len || !*str)
return;
string_builder_reserve(sb, len);
memcpy(sb->str + sb->len, str, len);
sb->len += len;
sb->str[sb->len] = 0;
}
void string_builder_append(StringBuilder *sb, const char *str)
{
if (!sb || !str || !*str)
return;
string_builder_append_length(sb, str, strlen(str));
}
void string_builder_append_pstr(StringBuilder *sb, const PString *pstr)
{
if (!sb || !pstr)
return;
string_builder_append_length(sb, pstr->str, pstr->len);
}
char *string_builder_detach(StringBuilder *sb)
{
char *str;
if (!sb)
return NULL;
str = sb->str;
sb->allocated_len = 0;
sb->len = 0;
sb->str = NULL;
return str;
}
void string_builder_free(StringBuilder *sb)
{
if (sb)
{
if (sb->str)
free(sb->str);
free(sb);
}
}