-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsonWriter.h
105 lines (87 loc) · 2.03 KB
/
JsonWriter.h
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#pragma once
#include "StringBuilder.h"
struct Json_Writer {
bool elements[4096 * 2] = {};
int index = 0;
String_Builder *builder = nullptr;
void next_element(bool is_key = false) {
if (elements[index])
Write(builder, ",");
if (is_key)
elements[index] = 0;
else
elements[index] = true;
}
void push_scope() {
next_element();
Assert(index >= 0 && index < ArrayCount(elements) - 1);
index += 1;
elements[index] = 0;
}
void pop_scope() {
Assert(index > 0 && index < ArrayCount(elements));
index -= 1;
}
void begin_object() {
push_scope();
Write(builder, "{");
}
void end_object() {
Write(builder, "}");
pop_scope();
}
void begin_array() {
push_scope();
Write(builder, "[");
}
void end_array() {
Write(builder, "]");
pop_scope();
}
void write_key(const char *key) {
next_element(true);
WriteFormatted(builder, "\"%\": ", key);
}
template <typename ...Args>
void write_single_value(const char *fmt, Args... args) {
next_element();
Write(builder, "\"");
WriteFormatted(builder, fmt, args...);
Write(builder, "\"");
}
void begin_string_value() {
next_element();
Write(builder, "\"");
}
void append_builder(String_Builder *src) {
for (auto buk = &src->head; buk; buk = buk->next) {
WriteBuffer(builder, buk->data, buk->written);
}
}
template <typename ...Args>
void append_string_value(const char *fmt, Args... args) {
WriteFormatted(builder, fmt, args...);
}
void end_string_value() {
Write(builder, "\"");
}
void write_key_null(const char *key) {
next_element();
WriteFormatted(builder, "\"%\": ", key);
Write(builder, "null");
}
template <typename ...Args>
void write_key_value_formatted(const char *key, const char *fmt, Args... args) {
next_element();
WriteFormatted(builder, "\"%\": ", key);
Write(builder, "\"");
WriteFormatted(builder, fmt, args...);
Write(builder, "\"");
}
template <typename Arg>
void write_key_value(const char *key, Arg arg) {
next_element();
WriteFormatted(builder, "\"%\": ", key);
Write(builder, arg);
}
};