Welcome to mirror list, hosted at ThFree Co, Russian Federation.

writer.h « rapidjson « include - github.com/miloyip/rapidjson.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 38dc8b8c20cafe28776208438bda7f9112302376 (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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#ifndef RAPIDJSON_WRITER_H_
#define RAPIDJSON_WRITER_H_

#include "rapidjson.h"
#include "internal/stack.h"
#include "internal/strfunc.h"
#include <cstdio>	// snprintf() or _sprintf_s()
#include <new>		// placement new

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#endif

namespace rapidjson {

//! JSON writer
/*! Writer implements the concept Handler.
	It generates JSON text by events to an output os.

	User may programmatically calls the functions of a writer to generate JSON text.

	On the other side, a writer can also be passed to objects that generates events, 

	for example Reader::Parse() and Document::Accept().

	\tparam OutputStream Type of output stream.
	\tparam SourceEncoding Encoding of both source strings.
	\tparam TargetEncoding Encoding of and output stream.
	\note implements Handler concept
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = MemoryPoolAllocator<> >
class Writer {
public:
	typedef typename SourceEncoding::Ch Ch;

	Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : 
		os_(os), level_stack_(allocator, levelDepth * sizeof(Level)) {}

	//@name Implementation of Handler
	//@{
	Writer& Null()					{ Prefix(kNullType);   WriteNull();			return *this; }
	Writer& Bool(bool b)			{ Prefix(b ? kTrueType : kFalseType); WriteBool(b); return *this; }
	Writer& Int(int i)				{ Prefix(kNumberType); WriteInt(i);			return *this; }
	Writer& Uint(unsigned u)		{ Prefix(kNumberType); WriteUint(u);		return *this; }
	Writer& Int64(int64_t i64)		{ Prefix(kNumberType); WriteInt64(i64);		return *this; }
	Writer& Uint64(uint64_t u64)	{ Prefix(kNumberType); WriteUint64(u64);	return *this; }
	Writer& Double(double d)		{ Prefix(kNumberType); WriteDouble(d);		return *this; }

	Writer& String(const Ch* str, SizeType length, bool copy = false) {
		(void)copy;
		Prefix(kStringType);
		WriteString(str, length);
		return *this;
	}

	Writer& StartObject() {
		Prefix(kObjectType);
		new (level_stack_.template Push<Level>()) Level(false);
		WriteStartObject();
		return *this;
	}

	Writer& EndObject(SizeType memberCount = 0) {
		(void)memberCount;
		RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
		RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
		level_stack_.template Pop<Level>(1);
		WriteEndObject();
		if (level_stack_.Empty())	// end of json text
			os_.Flush();
		return *this;
	}

	Writer& StartArray() {
		Prefix(kArrayType);
		new (level_stack_.template Push<Level>()) Level(true);
		WriteStartArray();
		return *this;
	}

	Writer& EndArray(SizeType elementCount = 0) {
		(void)elementCount;
		RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
		RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
		level_stack_.template Pop<Level>(1);
		WriteEndArray();
		if (level_stack_.Empty())	// end of json text
			os_.Flush();
		return *this;
	}
	//@}

	//! Simpler but slower overload.
	Writer& String(const Ch* str) { return String(str, internal::StrLen(str)); }

protected:
	//! Information for each nested level
	struct Level {
		Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
		size_t valueCount;	//!< number of values in this level
		bool inArray;		//!< true if in array, otherwise in object
	};

	static const size_t kDefaultLevelDepth = 32;

	void WriteNull()  {
		os_.Put('n'); os_.Put('u'); os_.Put('l'); os_.Put('l');
	}

	void WriteBool(bool b)  {
		if (b) {
			os_.Put('t'); os_.Put('r'); os_.Put('u'); os_.Put('e');
		}
		else {
			os_.Put('f'); os_.Put('a'); os_.Put('l'); os_.Put('s'); os_.Put('e');
		}
	}

	void WriteInt(int i) {
		if (i < 0) {
			os_.Put('-');
			i = -i;
		}
		WriteUint((unsigned)i);
	}

	void WriteUint(unsigned u) {
		char buffer[10];
		char *p = buffer;
		do {
			*p++ = (u % 10) + '0';
			u /= 10;
		} while (u > 0);

		do {
			--p;
			os_.Put(*p);
		} while (p != buffer);
	}

	void WriteInt64(int64_t i64) {
		if (i64 < 0) {
			os_.Put('-');
			i64 = -i64;
		}
		WriteUint64((uint64_t)i64);
	}

	void WriteUint64(uint64_t u64) {
		char buffer[20];
		char *p = buffer;
		do {
			*p++ = char(u64 % 10) + '0';
			u64 /= 10;
		} while (u64 > 0);

		do {
			--p;
			os_.Put(*p);
		} while (p != buffer);
	}

	//! \todo Optimization with custom double-to-string converter.
	void WriteDouble(double d) {
		char buffer[100];
#ifdef _MSC_VER
		int ret = sprintf_s(buffer, sizeof(buffer), "%g", d);
#else
		int ret = snprintf(buffer, sizeof(buffer), "%g", d);
#endif
		RAPIDJSON_ASSERT(ret >= 1);
		for (int i = 0; i < ret; i++)
			os_.Put(buffer[i]);
	}

	void WriteString(const Ch* str, SizeType length)  {
		static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		static const char escape[256] = {
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
			//0    1    2    3    4    5    6    7    8    9    A    B    C    D    E    F
			'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
			'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
			  0,   0, '"',   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, // 20
			Z16, Z16,																		// 30~4F
			  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,'\\',   0,   0,   0, // 50
			Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16								// 60~FF
#undef Z16
		};

		os_.Put('\"');
		GenericStringStream<SourceEncoding> is(str);
		while (is.Tell() < length) {
			const Ch c = is.Peek();
			if ((sizeof(Ch) == 1 || (unsigned)c < 256) && escape[(unsigned char)c])  {
				is.Take();
				os_.Put('\\');
				os_.Put(escape[(unsigned char)c]);
				if (escape[(unsigned char)c] == 'u') {
					os_.Put('0');
					os_.Put('0');
					os_.Put(hexDigits[(unsigned char)c >> 4]);
					os_.Put(hexDigits[(unsigned char)c & 0xF]);
				}
			}
			else
				Transcoder<SourceEncoding, TargetEncoding>::Transcode(is, os_);
		}
		os_.Put('\"');
	}

	void WriteStartObject()	{ os_.Put('{'); }
	void WriteEndObject()	{ os_.Put('}'); }
	void WriteStartArray()	{ os_.Put('['); }
	void WriteEndArray()	{ os_.Put(']'); }

	void Prefix(Type type) {
		(void)type;
		if (level_stack_.GetSize() != 0) { // this value is not at root
			Level* level = level_stack_.template Top<Level>();
			if (level->valueCount > 0) {
				if (level->inArray) 
					os_.Put(','); // add comma if it is not the first element in array
				else  // in object
					os_.Put((level->valueCount % 2 == 0) ? ',' : ':');
			}
			if (!level->inArray && level->valueCount % 2 == 0)
				RAPIDJSON_ASSERT(type == kStringType);  // if it's in object, then even number should be a name
			level->valueCount++;
		}
		else
			RAPIDJSON_ASSERT(type == kObjectType || type == kArrayType);
	}

	OutputStream& os_;
	internal::Stack<Allocator> level_stack_;

private:
	// Prohibit assignment for VC C4512 warning
	Writer& operator=(const Writer& w);
};

} // namespace rapidjson

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif // RAPIDJSON_RAPIDJSON_H_