// SPDX-License-Identifier: MIT #include #include #include #include #include "dbuf.h" #include "util.h" // va_copy is C99 // nevertheless, Codewarrior Pro 5 defines va_copy without advertising C99 support // so check for both C99 support and defined(va_copy) #if (!defined(__STDC_VERSION__) || __STDC_VERSION__ <= 199901L) && !defined(va_copy) #define va_copy(dst, src) dst = src #endif void db_init(struct dbuf* db, size_t capacity) { db->buf = xmalloc(capacity); db->capacity = capacity; db->len = 0; } static void db_grow(struct dbuf* db, size_t new_capacity) { db->buf = xrealloc(db->buf, new_capacity); db->capacity = new_capacity; } void db_extend(struct dbuf* db, u8* buf, size_t len) { if (db->len + len > db->capacity) db_grow(db, (db->capacity + len) * 2); memcpy(&db->buf[db->len], buf, len); db->len += len; } void db_printf(struct dbuf* db, const char* fmt, ...) { size_t required_len, len; va_list arg, arg2; va_start(arg, fmt); va_copy(arg2, arg); required_len = vsnprintf((char*)&db->buf[0], 0, fmt, arg) + 1; if (db->len + required_len > db->capacity) db_grow(db, 2 * (db->capacity + required_len)); len = vsnprintf((char*)&db->buf[db->len], required_len, fmt, arg2); db->len += len; } void db_clear(struct dbuf* db) { db->len = 0; db->buf[0] = 0; } void db_destroy(struct dbuf* db) { free(db->buf); }