14 #define SB_INCREMENT 200
16 stringbuf *sb_alloc(void)
18 stringbuf *sb = (stringbuf *)malloc(sizeof(*sb));
29 void sb_free(stringbuf *sb)
37 void sb_realloc(stringbuf *sb, int newlen)
39 sb->data = (char *)realloc(sb->data, newlen);
40 sb->remaining = newlen - sb->last;
43 void sb_append(stringbuf *sb, const char *str)
45 sb_append_len(sb, str, strlen(str));
48 void sb_append_len(stringbuf *sb, const char *str, int len)
50 if (sb->remaining < len + 1) {
51 sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
53 memcpy(sb->data + sb->last, str, len);
54 sb->data[sb->last + len] = 0;
59 sb->chars += utf8_strlen(str, len);
63 char *sb_to_string(stringbuf *sb)
65 if (sb->data == NULL) {
66 /* Return an allocated empty string, not null */
70 /* Just return the data and free the stringbuf structure */
77 /* Insert and delete operations */
79 /* Moves up all the data at position 'pos' and beyond by 'len' bytes
80 * to make room for new data
82 * Note: Does *not* update sb->chars
84 static void sb_insert_space(stringbuf *sb, int pos, int len)
86 assert(pos <= sb->last);
88 /* Make sure there is enough space */
89 if (sb->remaining < len) {
90 sb_realloc(sb, sb->last + len + SB_INCREMENT);
93 memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
96 /* And null terminate */
97 sb->data[sb->last] = 0;
101 * Move down all the data from pos + len, effectively
102 * deleting the data at position 'pos' of length 'len'
104 static void sb_delete_space(stringbuf *sb, int pos, int len)
106 assert(pos < sb->last);
107 assert(pos + len <= sb->last);
110 sb->chars -= utf8_strlen(sb->data + pos, len);
114 memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
116 sb->remaining += len;
117 /* And null terminate */
118 sb->data[sb->last] = 0;
121 void sb_insert(stringbuf *sb, int index, const char *str)
123 if (index >= sb->last) {
124 /* Inserting after the end of the list appends. */
128 int len = strlen(str);
130 sb_insert_space(sb, index, len);
131 memcpy(sb->data + index, str, len);
133 sb->chars += utf8_strlen(str, len);
139 * Delete the bytes at index 'index' for length 'len'
140 * Has no effect if the index is past the end of the list.
142 void sb_delete(stringbuf *sb, int index, int len)
144 if (index < sb->last) {
145 char *pos = sb->data + index;
150 sb_delete_space(sb, pos - sb->data, len);
154 void sb_clear(stringbuf *sb)