aboutsummaryrefslogtreecommitdiff
path: root/src/string-builder.h
blob: 0ba8a4edfb89edae5bd8d4b068a7abf971add4ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef INCLUDED_STRING_BUILDER_H
#define INCLUDED_STRING_BUILDER_H

#include <stddef.h>
#include <string.h>
#include "utils.h"
#include "dynamic-array.h"

struct string_builder {
  union { char *items, *string; };
  size_t  count;
  size_t  capacity;
};
#define STRING_BUILDER struct string_builder *

#define STRING_BUILDER_APPEND_CHAR(SB, CHAR)    \
  DYNAMIC_ARRAY_APPEND (SB, CHAR)

#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE)    \
  DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE)

#define STRING_BUILDER_APPEND_CSTR(SB, CSTR)    \
  ({                                            \
    const char *s = (CSTR);                     \
    size_t      n = strlen (s);                 \
    DYNAMIC_ARRAY_APPEND_MANY(SB, s, n);        \
  })

#define STRING_BUILDER_APPEND_CSTRS(SB, ...)                    \
  string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL)

#define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV)              \
  DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).beg, STRING_VIEW_LEN (SV));

#define STRING_BUILDER_APPEND_NULL(SB)  \
  DYNAMIC_ARRAY_APPEND (SB, '\0')

#define STRING_BUILDER_RESET(SB)        \
  DYNAMIC_ARRAY_RESET (SB)

#define STRING_BUILDER_FREE(SB) \
  DYNAMIC_ARRAY_FREE(SB)

extern void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n);
extern void string_builder_append_cstrs  (STRING_BUILDER,                     ...);
extern void string_builder_printf        (STRING_BUILDER, const char *format, ...);

#endif