commits
tags
#include "strbuf.h"
#include <stdlib.h>
#include <string.h>
void sb_init(StrBuf *sb) {
sb->data = NULL;
sb->len = 0;
sb->cap = 0;
}
void sb_free(StrBuf *sb) {
free(sb->data);
sb->data = NULL;
sb->len = 0;
sb->cap = 0;
}
void sb_reserve(StrBuf *sb, int extra) {
int needed = sb->len + extra + 1; /* keep a spare byte for a null terminator */
if (needed <= sb->cap) return;
int newCap = sb->cap > 0 ? sb->cap : 16;
while (newCap < needed) newCap *= 2;
sb->data = realloc(sb->data, (size_t)newCap);
sb->cap = newCap;
}
void sb_set(StrBuf *sb, const char *s, int n) {
sb->len = 0;
sb_insert(sb, 0, s, n);
}
void sb_insert(StrBuf *sb, int pos, const char *s, int n) {
if (n <= 0) return;
sb_reserve(sb, n);
memmove(sb->data + pos + n, sb->data + pos, (size_t)(sb->len - pos));
memcpy(sb->data + pos, s, (size_t)n);
sb->len += n;
sb->data[sb->len] = '\0';
}
void sb_delete(StrBuf *sb, int pos, int n) {
if (n <= 0) return;
memmove(sb->data + pos, sb->data + pos + n, (size_t)(sb->len - pos - n));
sb->len -= n;
if (sb->data) sb->data[sb->len] = '\0';
}
void sb_append(StrBuf *sb, const char *s, int n) {
sb_insert(sb, sb->len, s, n);
}
void sb_append_char(StrBuf *sb, char c) {
sb_append(sb, &c, 1);
}
void sb_clear(StrBuf *sb) {
sb->len = 0;
if (sb->data) sb->data[0] = '\0';
}