master
h 96 lines 9.39 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #ifndef NETDATA_TEMPLATE_ENUM_H
4 #define NETDATA_TEMPLATE_ENUM_H
5
6 #define ENUM_STR_MAP_DEFINE(type) \
7 static struct { \
8 type id; \
9 const char *name; \
10 } type ## _names[]
11
12 #define ENUM_STR_DEFINE_FUNCTIONS_EXTERN(type) \
13 type type ## _2id(const char *str); \
14 const char *type##_2str(type id);
15
16 #define ENUM_STR_DEFINE_FUNCTIONS(type, def, def_str) \
17 type type##_2id(const char *str) \
18 { \
19 if (!str || !*str) \
20 return def; \
21 \
22 for (size_t i = 0; type ## _names[i].name; i++) { \
23 if (strcmp(type ## _names[i].name, str) == 0) \
24 return type ## _names[i].id; \
25 } \
26 \
27 return def; \
28 } \
29 \
30 const char *type##_2str(type id) \
31 { \
32 for (size_t i = 0; type ## _names[i].name; i++) { \
33 if (id == type ## _names[i].id) \
34 return type ## _names[i].name; \
35 } \
36 \
37 return def_str; \
38 }
39
40 // --------------------------------------------------------------------------------------------------------------------
41
42 #define BITMAP_STR_DEFINE_FUNCTIONS_EXTERN(type) \
43 type type ## _2id_one(const char *str); \
44 const char *type##_2str_one(type id); \
45 void type##_2json(BUFFER *wb, const char *key, type id); \
46 void type##_2buffer(BUFFER *wb, type id, const char *separator);
47
48 #define BITMAP_STR_DEFINE_FUNCTIONS(type, def, def_str) \
49 type type##_2id_one(const char *str) \
50 { \
51 if (!str || !*str) \
52 return def; \
53 \
54 for (size_t i = 0; type##_names[i].name; i++) { \
55 if (strcmp(type##_names[i].name, str) == 0) \
56 return type##_names[i].id; \
57 } \
58 \
59 return def; \
60 } \
61 \
62 const char *type##_2str_one(type id) \
63 { \
64 for (size_t i = 0; type##_names[i].name; i++) { \
65 if (id == type##_names[i].id) \
66 return type##_names[i].name; \
67 } \
68 \
69 return def_str; \
70 } \
71 \
72 void type##_2json(BUFFER *wb, const char *key, type id) \
73 { \
74 buffer_json_member_add_array(wb, key); \
75 for (size_t i = 0; id && type##_names[i].name; i++) { \
76 if ((id & type##_names[i].id) == type##_names[i].id) { \
77 buffer_json_add_array_item_string(wb, type##_names[i].name); \
78 id &= ~(type##_names[i].id); \
79 } \
80 } \
81 buffer_json_array_close(wb); \
82 } \
83 \
84 void type##_2buffer(BUFFER *wb, type id, const char *separator) \
85 { \
86 size_t added = 0; \
87 for (size_t i = 0; id && type##_names[i].name; i++) { \
88 if ((id & type##_names[i].id) == type##_names[i].id) { \
89 if(added++) buffer_strcat(wb, separator); \
90 buffer_strcat(wb, type##_names[i].name); \
91 id &= ~(type##_names[i].id); \
92 } \
93 } \
94 }
95
96 #endif //NETDATA_TEMPLATE_ENUM_H