-
Notifications
You must be signed in to change notification settings - Fork 20
/
dynstr.c
94 lines (77 loc) · 1.64 KB
/
dynstr.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* See LICENSE file for copyright and license details.
*
* Copyright (c) 2013 Joyent, Inc.
* Copyright (c) 2024 MNX Cloud, Inc.
*/
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include "dynstr.h"
struct string {
size_t str_strlen;
size_t str_datalen;
char *str_data;
};
#define STRING_CHUNK_SIZE 64
void
dynstr_reset(string_t *str)
{
if (str->str_data == NULL)
return;
str->str_strlen = 0;
str->str_data[0] = '\0';
}
size_t
dynstr_len(string_t *str)
{
return (str->str_strlen);
}
const char *
dynstr_cstr(string_t *str)
{
return (str->str_data);
}
void
dynstr_appendc(string_t *str, char newc)
{
size_t chunksz = STRING_CHUNK_SIZE;
if (str->str_strlen + 1 >= str->str_datalen) {
str->str_datalen += chunksz;
str->str_data = realloc(str->str_data, str->str_datalen);
if (str->str_data == NULL)
err(1, "could not allocate memory for string");
}
str->str_data[str->str_strlen++] = newc;
str->str_data[str->str_strlen] = '\0';
}
void
dynstr_append(string_t *str, const char *news)
{
size_t len = strlen(news);
size_t chunksz = STRING_CHUNK_SIZE;
while (chunksz < len)
chunksz *= 2;
if (len + str->str_strlen >= str->str_datalen) {
str->str_datalen += chunksz;
str->str_data = realloc(str->str_data, str->str_datalen);
if (str->str_data == NULL)
err(1, "could not allocate memory for string");
}
strcpy(str->str_data + str->str_strlen, news);
str->str_strlen += len;
}
string_t *
dynstr_new(void)
{
string_t *ret = calloc(1, sizeof (string_t));
if (ret == NULL)
err(10, "could not allocate memory for string");
return (ret);
}
void
dynstr_free(string_t *str)
{
free(str->str_data);
free(str);
}