-
Notifications
You must be signed in to change notification settings - Fork 2
/
str.c
116 lines (97 loc) · 2.35 KB
/
str.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* Naive dynamically-allocated strings
*
* No attempts to be clever; hopefully your allocator will do an
* acceptable job. Not intended for high-performance or high-safety
* applications.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "overflow.h"
#include "str.h"
struct str *str_new(size_t len)
{
struct str *p = malloc(sizeof(*p) + len);
p->avail = len;
p->len = 0;
return p;
}
struct str *str_dup_cstr(const char *s)
{
size_t len = strlen(s);
struct str *p = str_new(len);
memcpy(p->data, s, len);
p->len = len;
return p;
}
void str_free(struct str **p)
{
if (NULL == *p) return;
(*p)->avail = (*p)->len = 0;
free(*p);
*p = NULL;
}
static bool str_grow(struct str **p)
{
size_t next = 16;
enum { BIG_STRING_LEN = 2048 };
if ((*p)->avail >= BIG_STRING_LEN)
next = (*p)->avail + ((*p)->avail >> 1);
else if ((*p)->avail >= next)
next = (*p)->avail * 2;
assert(next > (*p)->avail);
size_t total;
assert(!add_overflow(next, sizeof(struct str), &total));
struct str *q = realloc(*p, total);
if (q == NULL)
return false;
*p = q;
(*p)->avail = next;
return true;
}
static bool str_grow_to(struct str **p, size_t total)
{
if ((*p)->avail >= total)
return true;
struct str *q = realloc(*p, total + sizeof(struct str));
if (q == NULL)
return false;
*p = q;
(*p)->avail = total;
return true;
}
bool str_appendch(struct str **p, char c)
{
if (NULL == *p)
*p = str_new(16);
if ((*p)->len+1 >= (*p)->avail && !str_grow(p))
return false;
(*p)->data[(*p)->len++] = c;
return true;
}
bool str_append_bytes(struct str **p, const char *bytes, size_t len)
{
if (NULL == *p) {
*p = str_new(len);
memcpy((*p)->data, bytes, len);
return true;
}
size_t total;
if (add_overflow((*p)->len, len, &total))
abort();
if (total >= (*p)->avail && !str_grow_to(p, total))
return false;
memcpy((*p)->data+(*p)->len, bytes, len);
(*p)->len = total;
return true;
}
bool str_eq(const struct str *a, const struct str *b)
{
if (a->len != b->len)
return false;
return 0 == memcmp(a->data, b->data, a->len);
}
void str_print(FILE *out, const struct str *s)
{
fprintf(out, "%.*s", (int)s->len, s->data);
}