Debian Codegraph @

libdrgn/string_builder.c

raw
1 // Copyright (c) Meta Platforms, Inc. and affiliates.
2 // SPDX-License-Identifier: LGPL-2.1-or-later
3
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 #include "bitops.h"
9 #include "string_builder.h"
10 #include "util.h"
11
12 bool string_builder_null_terminate(struct string_builder *sb)
13 {
14 if (!string_builder_reserve_for_append(sb, 1))
15 return false;
16 sb->str[sb->len] = '\0';
17 return true;
18 }
19
20 bool string_builder_reserve(struct string_builder *sb, size_t capacity)
21 {
22 if (capacity <= sb->capacity)
23 return true;
24 char *tmp = realloc(sb->str, capacity);
25 if (!tmp)
26 return false;
27 sb->str = tmp;
28 sb->capacity = capacity;
29 return true;
30 }
31
32 bool string_builder_reserve_for_append(struct string_builder *sb, size_t n)
33 {
34 if (n == 0)
35 return true;
36 size_t capacity;
37 if (__builtin_add_overflow(sb->len, n, &capacity))
38 return false;
39 if (capacity < (SIZE_MAX / 2) + 1)
40 capacity = next_power_of_two(capacity);
41 return string_builder_reserve(sb, capacity);
42 }
43
44 bool string_builder_appendc(struct string_builder *sb, char c)
45 {
46 if (!string_builder_reserve_for_append(sb, 1))
47 return false;
48 sb->str[sb->len++] = c;
49 return true;
50 }
51
52 bool string_builder_appendn(struct string_builder *sb, const char *str,
53 size_t len)
54 {
55 if (len == 0)
56 return true;
57 if (!string_builder_reserve_for_append(sb, len))
58 return false;
59 memcpy(&sb->str[sb->len], str, len);
60 sb->len += len;
61 return true;
62 }
63
64 bool string_builder_vappendf(struct string_builder *sb, const char *format,
65 va_list ap)
66 {
67 va_list aq;
68 int len;
69
70 again:
71 va_copy(aq, ap);
72 len = vsnprintf(add_to_possibly_null_pointer(sb->str, sb->len),
73 sb->capacity - sb->len, format, aq);
74 va_end(aq);
75 if (len < 0)
76 return false;
77 if (sb->len + len < sb->capacity) {
78 sb->len += len;
79 return true;
80 }
81
82 /*
83 * vsnprintf() always null-terminates the string, so we have to allocate
84 * an extra character.
85 */
86 if (!string_builder_reserve_for_append(sb, len + 1))
87 return false;
88 goto again;
89 }
90
91 bool string_builder_appendf(struct string_builder *sb, const char *format, ...)
92 {
93 va_list ap;
94 bool ret;
95
96 va_start(ap, format);
97 ret = string_builder_vappendf(sb, format, ap);
98 va_end(ap);
99 return ret;
100 }
101
102 bool string_builder_line_break(struct string_builder *sb)
103 {
104 if (!sb->len || sb->str[sb->len - 1] == '\n')
105 return true;
106 return string_builder_appendc(sb, '\n');
107 }