12 #define SB_INCREMENT 200
14 stringbuf *sb_alloc(void)
16 stringbuf *sb = (stringbuf *)malloc(sizeof(*sb));
27 void sb_free(stringbuf *sb)
35 void sb_realloc(stringbuf *sb, int newlen)
37 sb->data = (char *)realloc(sb->data, newlen);
38 sb->remaining = newlen - sb->last;
41 void sb_append(stringbuf *sb, const char *str)
43 sb_append_len(sb, str, strlen(str));
46 void sb_append_len(stringbuf *sb, const char *str, int len)
48 int utf8_strlen(const char *str, int bytelen);
49 if (sb->remaining < len + 1) {
50 sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
52 memcpy(sb->data + sb->last, str, len);
53 sb->data[sb->last + len] = 0;
58 sb->chars += utf8_strlen(str, len);
62 char *sb_to_string(stringbuf *sb)
64 if (sb->data == NULL) {
65 /* Return an allocated empty string, not null */
69 /* Just return the data and free the stringbuf structure */
76 /* Insert and delete operations */
78 /* Moves up all the data at position 'pos' and beyond by 'len' bytes
79 * to make room for new data
81 * Note: Does *not* update sb->chars
83 static void sb_insert_space(stringbuf *sb, int pos, int len)
85 assert(pos <= sb->last);
87 /* Make sure there is enough space */
88 if (sb->remaining < len) {
89 sb_realloc(sb, sb->last + len + SB_INCREMENT);
92 memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
95 /* And null terminate */
96 sb->data[sb->last] = 0;
100 * Move down all the data from pos + len, effectively
101 * deleting the data at position 'pos' of length 'len'
103 static void sb_delete_space(stringbuf *sb, int pos, int len)
105 assert(pos < sb->last);
106 assert(pos + len <= sb->last);
109 sb->chars -= utf8_strlen(sb->data + pos, len);
113 memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
115 sb->remaining += len;
116 /* And null terminate */
117 sb->data[sb->last] = 0;
120 void sb_insert(stringbuf *sb, int index, const char *str)
122 if (index >= sb->last) {
123 /* Inserting after the end of the list appends. */
127 int len = strlen(str);
129 sb_insert_space(sb, index, len);
130 memcpy(sb->data + index, str, len);
132 sb->chars += utf8_strlen(str, len);
138 * Delete the bytes at index 'index' for length 'len'
139 * Has no effect if the index is past the end of the list.
141 void sb_delete(stringbuf *sb, int index, int len)
143 if (index < sb->last) {
144 char *pos = sb->data + index;
149 sb_delete_space(sb, pos - sb->data, len);
153 void sb_clear(stringbuf *sb)