AmendHub

Download

cyberslak

/

lightsout

/

dbuf.c

 

(View History)

cyberslak   Add LICENSE information Latest amendment: 22 on 2025-03-15

1 // SPDX-License-Identifier: MIT
2
3 #include <string.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include "dbuf.h"
8 #include "util.h"
9
10 // va_copy is C99
11 // nevertheless, Codewarrior Pro 5 defines va_copy without advertising C99 support
12 // so check for both C99 support and defined(va_copy)
13 #if (!defined(__STDC_VERSION__) || __STDC_VERSION__ <= 199901L) && !defined(va_copy)
14 #define va_copy(dst, src) dst = src
15 #endif
16
17 void db_init(struct dbuf* db, size_t capacity)
18 {
19 db->buf = xmalloc(capacity);
20 db->capacity = capacity;
21 db->len = 0;
22 }
23
24 static void db_grow(struct dbuf* db, size_t new_capacity)
25 {
26 db->buf = xrealloc(db->buf, new_capacity);
27 db->capacity = new_capacity;
28 }
29
30 void db_extend(struct dbuf* db, u8* buf, size_t len)
31 {
32 if (db->len + len > db->capacity)
33 db_grow(db, (db->capacity + len) * 2);
34
35 memcpy(&db->buf[db->len], buf, len);
36 db->len += len;
37 }
38
39 void db_printf(struct dbuf* db, const char* fmt, ...)
40 {
41 size_t required_len, len;
42 va_list arg, arg2;
43 va_start(arg, fmt);
44 va_copy(arg2, arg);
45
46 required_len = vsnprintf((char*)&db->buf[0], 0, fmt, arg) + 1;
47 if (db->len + required_len > db->capacity)
48 db_grow(db, 2 * (db->capacity + required_len));
49
50 len = vsnprintf((char*)&db->buf[db->len], required_len, fmt, arg2);
51 db->len += len;
52 }
53
54 void db_clear(struct dbuf* db)
55 {
56 db->len = 0;
57 db->buf[0] = 0;
58 }
59
60 void db_destroy(struct dbuf* db)
61 {
62 free(db->buf);
63 }