blob: cbf4ef8e7b7e3cc8351d2b4c282f60f0585b00b2 [file] [log] [blame]
David Reissdb0ea152008-02-18 01:49:37 +00001// Copyright (c) 2006- Facebook
2// Distributed under the Thrift Software License
3//
4// See accompanying file LICENSE or visit the Thrift site at:
5// http://developers.facebook.com/thrift/
6
7#ifndef _THRIFT_PROTOCOL_TJSONPROTOCOL_H_
8#define _THRIFT_PROTOCOL_TJSONPROTOCOL_H_ 1
9
10#include "TProtocol.h"
David Reissdb0ea152008-02-18 01:49:37 +000011
12#include <stack>
13
14namespace facebook { namespace thrift { namespace protocol {
15
16// Forward declaration
17class TJSONContext;
18
19/**
20 * JSON protocol for Thrift.
21 *
David Reiss1e62ab42008-02-21 22:37:45 +000022 * Implements a protocol which uses JSON as the wire-format.
23 *
David Reissdb0ea152008-02-18 01:49:37 +000024 * Thrift types are represented as described below:
25 *
26 * 1. Every Thrift integer type is represented as a JSON number.
27 *
28 * 2. Thrift doubles are represented as JSON numbers. Some special values are
29 * represented as strings:
30 * a. "NaN" for not-a-number values
31 * b. "Infinity" for postive infinity
32 * c. "-Infinity" for negative infinity
33 *
34 * 3. Thrift string values are emitted as JSON strings, with appropriate
35 * escaping.
36 *
37 * 4. Thrift binary values are encoded into Base64 and emitted as JSON strings.
38 * The readBinary() method is written such that it will properly skip if
39 * called on a Thrift string (although it will decode garbage data).
40 *
41 * 5. Thrift structs are represented as JSON objects, with the field ID as the
42 * key, and the field value represented as a JSON object with a single
43 * key-value pair. The key is a short string identifier for that type,
44 * followed by the value. The valid type identifiers are: "tf" for bool,
45 * "i8" for byte, "i16" for 16-bit integer, "i32" for 32-bit integer, "i64"
46 * for 64-bit integer, "dbl" for double-precision loating point, "str" for
47 * string (including binary), "rec" for struct ("records"), "map" for map,
48 * "lst" for list, "set" for set.
49 *
50 * 6. Thrift lists and sets are represented as JSON arrays, with the first
51 * element of the JSON array being the string identifier for the Thrift
52 * element type and the second element of the JSON array being the count of
53 * the Thrift elements. The Thrift elements then follow.
54 *
55 * 7. Thrift maps are represented as JSON arrays, with the first two elements
56 * of the JSON array being the string identifiers for the Thrift key type
57 * and value type, followed by the count of the Thrift pairs, followed by a
58 * JSON object containing the key-value pairs. Note that JSON keys can only
59 * be strings, which means that the key type of the Thrift map should be
60 * restricted to numeric or string types -- in the case of numerics, they
61 * are serialized as strings.
62 *
63 * 8. Thrift messages are represented as JSON arrays, with the protocol
64 * version #, the message name, the message type, and the sequence ID as
65 * the first 4 elements.
66 *
67 * More discussion of the double handling is probably warranted. The aim of
68 * the current implementation is to match as closely as possible the behavior
69 * of Java's Double.toString(), which has no precision loss. Implementors in
70 * other languages should strive to achieve that where possible. I have not
71 * yet verified whether boost:lexical_cast, which is doing that work for me in
72 * C++, loses any precision, but I am leaving this as a future improvement. I
73 * may try to provide a C component for this, so that other languages could
74 * bind to the same underlying implementation for maximum consistency.
75 *
76 * Note further that JavaScript itself is not capable of representing
77 * floating point infinities -- presumably when we have a JavaScript Thrift
78 * client, this would mean that infinities get converted to not-a-number in
79 * transmission. I don't know of any work-around for this issue.
80 *
81 * @author Chad Walters <chad@powerset.com>
82 */
83class TJSONProtocol : public TProtocol {
84 public:
85
86 TJSONProtocol(boost::shared_ptr<TTransport> ptrans);
87
88 ~TJSONProtocol();
89
90 private:
91
92 void pushContext(boost::shared_ptr<TJSONContext> c);
93
94 void popContext();
95
96 uint32_t writeJSONEscapeChar(uint8_t ch);
97
98 uint32_t writeJSONChar(uint8_t ch);
99
100 uint32_t writeJSONString(const std::string &str);
101
102 uint32_t writeJSONBase64(const std::string &str);
103
104 template <typename NumberType>
105 uint32_t writeJSONInteger(NumberType num);
106
107 uint32_t writeJSONDouble(double num);
108
109 uint32_t writeJSONObjectStart() ;
110
111 uint32_t writeJSONObjectEnd();
112
113 uint32_t writeJSONArrayStart();
114
115 uint32_t writeJSONArrayEnd();
116
117 uint32_t readJSONSyntaxChar(uint8_t ch);
118
119 uint32_t readJSONEscapeChar(uint8_t *out);
120
121 uint32_t readJSONString(std::string &str, bool skipContext = false);
122
123 uint32_t readJSONBase64(std::string &str);
124
125 uint32_t readJSONNumericChars(std::string &str);
126
127 template <typename NumberType>
128 uint32_t readJSONInteger(NumberType &num);
129
130 uint32_t readJSONDouble(double &num);
131
132 uint32_t readJSONObjectStart();
133
134 uint32_t readJSONObjectEnd();
135
136 uint32_t readJSONArrayStart();
137
138 uint32_t readJSONArrayEnd();
139
140 public:
141
142 /**
143 * Writing functions.
144 */
145
146 uint32_t writeMessageBegin(const std::string& name,
147 const TMessageType messageType,
148 const int32_t seqid);
149
150 uint32_t writeMessageEnd();
151
David Reiss64120002008-04-29 23:12:24 +0000152 uint32_t writeStructBegin(const char* name);
David Reissdb0ea152008-02-18 01:49:37 +0000153
154 uint32_t writeStructEnd();
155
David Reiss64120002008-04-29 23:12:24 +0000156 uint32_t writeFieldBegin(const char* name,
David Reissdb0ea152008-02-18 01:49:37 +0000157 const TType fieldType,
158 const int16_t fieldId);
159
160 uint32_t writeFieldEnd();
161
162 uint32_t writeFieldStop();
163
164 uint32_t writeMapBegin(const TType keyType,
165 const TType valType,
166 const uint32_t size);
167
168 uint32_t writeMapEnd();
169
170 uint32_t writeListBegin(const TType elemType,
171 const uint32_t size);
172
173 uint32_t writeListEnd();
174
175 uint32_t writeSetBegin(const TType elemType,
176 const uint32_t size);
177
178 uint32_t writeSetEnd();
179
180 uint32_t writeBool(const bool value);
181
182 uint32_t writeByte(const int8_t byte);
183
184 uint32_t writeI16(const int16_t i16);
185
186 uint32_t writeI32(const int32_t i32);
187
188 uint32_t writeI64(const int64_t i64);
189
190 uint32_t writeDouble(const double dub);
191
192 uint32_t writeString(const std::string& str);
193
194 uint32_t writeBinary(const std::string& str);
195
196 /**
197 * Reading functions
198 */
199
200 uint32_t readMessageBegin(std::string& name,
201 TMessageType& messageType,
202 int32_t& seqid);
203
204 uint32_t readMessageEnd();
205
206 uint32_t readStructBegin(std::string& name);
207
208 uint32_t readStructEnd();
209
210 uint32_t readFieldBegin(std::string& name,
211 TType& fieldType,
212 int16_t& fieldId);
213
214 uint32_t readFieldEnd();
215
216 uint32_t readMapBegin(TType& keyType,
217 TType& valType,
218 uint32_t& size);
219
220 uint32_t readMapEnd();
221
222 uint32_t readListBegin(TType& elemType,
223 uint32_t& size);
224
225 uint32_t readListEnd();
226
227 uint32_t readSetBegin(TType& elemType,
228 uint32_t& size);
229
230 uint32_t readSetEnd();
231
232 uint32_t readBool(bool& value);
233
234 uint32_t readByte(int8_t& byte);
235
236 uint32_t readI16(int16_t& i16);
237
238 uint32_t readI32(int32_t& i32);
239
240 uint32_t readI64(int64_t& i64);
241
242 uint32_t readDouble(double& dub);
243
244 uint32_t readString(std::string& str);
245
246 uint32_t readBinary(std::string& str);
247
David Reiss1e62ab42008-02-21 22:37:45 +0000248 class LookaheadReader {
249
250 public:
251
252 LookaheadReader(TTransport &trans) :
253 trans_(&trans),
254 hasData_(false) {
255 }
256
257 uint8_t read() {
258 if (hasData_) {
259 hasData_ = false;
260 }
261 else {
262 trans_->readAll(&data_, 1);
263 }
264 return data_;
265 }
266
267 uint8_t peek() {
268 if (!hasData_) {
269 trans_->readAll(&data_, 1);
270 }
271 hasData_ = true;
272 return data_;
273 }
274
275 private:
276 TTransport *trans_;
277 bool hasData_;
278 uint8_t data_;
279 };
280
David Reissdb0ea152008-02-18 01:49:37 +0000281 private:
282
283 std::stack<boost::shared_ptr<TJSONContext> > contexts_;
284 boost::shared_ptr<TJSONContext> context_;
David Reiss1e62ab42008-02-21 22:37:45 +0000285 LookaheadReader reader_;
David Reissdb0ea152008-02-18 01:49:37 +0000286};
287
288/**
289 * Constructs input and output protocol objects given transports.
290 */
David Reiss4c266cc2009-01-15 23:56:24 +0000291class TJSONProtocolFactory : public TProtocolFactory {
David Reissdb0ea152008-02-18 01:49:37 +0000292 public:
293 TJSONProtocolFactory() {}
294
295 virtual ~TJSONProtocolFactory() {}
296
297 boost::shared_ptr<TProtocol> getProtocol(boost::shared_ptr<TTransport> trans) {
298 return boost::shared_ptr<TProtocol>(new TJSONProtocol(trans));
299 }
300};
301
302}}} // facebook::thrift::protocol
303
304
David Reiss28f298d2008-05-01 06:17:36 +0000305// TODO(dreiss): Move part of ThriftJSONString into a .cpp file and remove this.
306#include <transport/TBufferTransports.h>
307
David Reissdb0ea152008-02-18 01:49:37 +0000308namespace facebook { namespace thrift {
309
310template<typename ThriftStruct>
311 std::string ThriftJSONString(const ThriftStruct& ts) {
312 using namespace facebook::thrift::transport;
313 using namespace facebook::thrift::protocol;
314 TMemoryBuffer* buffer = new TMemoryBuffer;
315 boost::shared_ptr<TTransport> trans(buffer);
316 TJSONProtocol protocol(trans);
317
318 ts.write(&protocol);
319
320 uint8_t* buf;
321 uint32_t size;
322 buffer->getBuffer(&buf, &size);
323 return std::string((char*)buf, (unsigned int)size);
324}
325
326}} // facebook::thrift
327
328#endif // #define _THRIFT_PROTOCOL_TJSONPROTOCOL_H_ 1