master
h 90 lines 2.13 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #ifndef NETDATA_LOG2JOURNAL_TXT_H
4 #define NETDATA_LOG2JOURNAL_TXT_H
5
6 #include "log2journal.h"
7
8 // ----------------------------------------------------------------------------
9 // A dynamically sized, reusable text buffer,
10 // allowing us to be fast (no allocations during iterations) while having the
11 // smallest possible allocations.
12
13 typedef struct txt_l2j {
14 char *txt;
15 uint32_t size;
16 uint32_t len;
17 } TXT_L2J;
18
19 static inline void txt_l2j_cleanup(TXT_L2J *t) {
20 if(!t)
21 return;
22
23 if(t->txt)
24 freez(t->txt);
25
26 t->txt = NULL;
27 t->size = 0;
28 t->len = 0;
29 }
30
31 #define TXT_L2J_ALLOC_ALIGN 1024
32
33 static inline size_t txt_l2j_compute_new_size(size_t old_size, size_t required_size) {
34 size_t size = (required_size % TXT_L2J_ALLOC_ALIGN == 0) ? required_size : required_size + TXT_L2J_ALLOC_ALIGN;
35 size = (size / TXT_L2J_ALLOC_ALIGN) * TXT_L2J_ALLOC_ALIGN;
36
37 if(size < old_size * 2)
38 size = old_size * 2;
39
40 return size;
41 }
42
43 static inline void txt_l2j_resize(TXT_L2J *dst, size_t required_size, bool keep) {
44 if(required_size <= dst->size)
45 return;
46
47 size_t new_size = txt_l2j_compute_new_size(dst->size, required_size);
48
49 if(keep && dst->txt)
50 dst->txt = reallocz(dst->txt, new_size);
51 else {
52 txt_l2j_cleanup(dst);
53 dst->txt = mallocz(new_size);
54 dst->len = 0;
55 }
56
57 dst->size = new_size;
58 }
59
60 static inline void txt_l2j_set(TXT_L2J *dst, const char *s, int32_t len) {
61 if(!s || !*s || len == 0) {
62 s = "";
63 len = 0;
64 }
65
66 if(len == -1)
67 len = (int32_t)strlen(s);
68
69 txt_l2j_resize(dst, len + 1, false);
70 memcpy(dst->txt, s, len);
71 dst->txt[len] = '\0';
72 dst->len = len;
73 }
74
75 static inline void txt_l2j_append(TXT_L2J *dst, const char *s, int32_t len) {
76 if(!dst->txt || !dst->len)
77 txt_l2j_set(dst, s, len);
78
79 else {
80 if(len == -1)
81 len = (int32_t)strlen(s);
82
83 txt_l2j_resize(dst, dst->len + len + 1, true);
84 memcpy(&dst->txt[dst->len], s, len);
85 dst->len += len;
86 dst->txt[dst->len] = '\0';
87 }
88 }
89
90 #endif //NETDATA_LOG2JOURNAL_TXT_H