1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* A JSON pretty-printer class. */
9 // A typical JSON-writing library requires you to first build up a data
10 // structure that represents a JSON object and then serialize it (to file, or
11 // somewhere else). This approach makes for a clean API, but building the data
12 // structure takes up memory. Sometimes that isn't desirable, such as when the
13 // JSON data is produced for memory reporting.
15 // The JSONWriter class instead allows JSON data to be written out
16 // incrementally without building up large data structures.
18 // The API is slightly uglier than you would see in a typical JSON-writing
19 // library, but still fairly easy to use. It's possible to generate invalid
20 // JSON with JSONWriter, but typically the most basic testing will identify any
23 // Similarly, there are no RAII facilities for automatically closing objects
24 // and arrays. These would be nice if you are generating all your code within
25 // nested functions, but in other cases you'd have to maintain an explicit
26 // stack of RAII objects and manually unwind it, which is no better than just
27 // calling "end" functions. Furthermore, the consequences of forgetting to
28 // close an object or array are obvious and, again, will be identified via
29 // basic testing, unlike other cases where RAII is typically used (e.g. smart
30 // pointers) and the consequences of defects are more subtle.
32 // Importantly, the class does solve the two hard problems of JSON
33 // pretty-printing, which are (a) correctly escaping strings, and (b) adding
34 // appropriate indentation and commas between items.
36 // By default, every property is placed on its own line. However, it is
37 // possible to request that objects and arrays be placed entirely on a single
38 // line, which can reduce output size significantly in some cases.
40 // Strings used (for property names and string property values) are |const
41 // char*| throughout, and can be ASCII or UTF-8.
45 // Assume that |MyWriteFunc| is a class that implements |JSONWriteFunc|. The
48 // JSONWriter w(MakeUnique<MyWriteFunc>());
51 // w.NullProperty("null");
52 // w.BoolProperty("bool", true);
53 // w.IntProperty("int", 1);
54 // w.StartArrayProperty("array");
56 // w.StringElement("string");
57 // w.StartObjectElement();
59 // w.DoubleProperty("double", 3.4);
60 // w.StartArrayProperty("single-line array", w.SingleLineStyle);
63 // w.StartObjectElement(); // SingleLineStyle is inherited from
64 // w.EndObjectElement(); // above for this collection
68 // w.EndObjectElement();
70 // w.EndArrayProperty();
74 // will produce pretty-printed output for the following JSON object:
84 // "single-line array": [1, {}]
89 // The nesting in the example code is obviously optional, but can aid
92 #ifndef mozilla_JSONWriter_h
93 #define mozilla_JSONWriter_h
95 #include "double-conversion/double-conversion.h"
96 #include "mozilla/Assertions.h"
97 #include "mozilla/IntegerPrintfMacros.h"
98 #include "mozilla/PodOperations.h"
99 #include "mozilla/Sprintf.h"
100 #include "mozilla/UniquePtr.h"
101 #include "mozilla/Vector.h"
107 // A quasi-functor for JSONWriter. We don't use a true functor because that
108 // requires templatizing JSONWriter, and the templatization seeps to lots of
109 // places we don't want it to.
113 virtual void Write(const char* aStr
) = 0;
114 virtual ~JSONWriteFunc() {}
117 // Ideally this would be within |EscapedString| but when compiling with GCC
118 // on Linux that caused link errors, whereas this formulation didn't.
120 extern MFBT_DATA
const char gTwoCharEscapes
[256];
121 } // namespace detail
125 // From http://www.ietf.org/rfc/rfc4627.txt:
127 // "All Unicode characters may be placed within the quotation marks except
128 // for the characters that must be escaped: quotation mark, reverse
129 // solidus, and the control characters (U+0000 through U+001F)."
131 // This implementation uses two-char escape sequences where possible, namely:
133 // \", \\, \b, \f, \n, \r, \t
135 // All control characters not in the above list are represented with a
136 // six-char escape sequence, e.g. '\u000b' (a.k.a. '\v').
140 // Only one of |mUnownedStr| and |mOwnedStr| are ever non-null. |mIsOwned|
141 // indicates which one is in use. They're not within a union because that
142 // wouldn't work with UniquePtr.
144 const char* mUnownedStr
;
145 UniquePtr
<char[]> mOwnedStr
;
147 void SanityCheck() const
149 MOZ_ASSERT_IF( mIsOwned
, mOwnedStr
.get() && !mUnownedStr
);
150 MOZ_ASSERT_IF(!mIsOwned
, !mOwnedStr
.get() && mUnownedStr
);
153 static char hexDigitToAsciiChar(uint8_t u
)
156 return u
< 10 ? '0' + u
: 'a' + (u
- 10);
160 explicit EscapedString(const char* aStr
)
161 : mUnownedStr(nullptr)
166 // First, see if we need to modify the string.
170 uint8_t u
= *p
; // ensure it can't be interpreted as negative
174 if (detail::gTwoCharEscapes
[u
]) {
176 } else if (u
<= 0x1f) {
183 // No escapes needed. Easy.
189 // Escapes are needed. We'll create a new string.
191 size_t len
= (p
- aStr
) + nExtra
;
192 mOwnedStr
= MakeUnique
<char[]>(len
+ 1);
198 uint8_t u
= *p
; // ensure it can't be interpreted as negative
203 if (detail::gTwoCharEscapes
[u
]) {
204 mOwnedStr
[i
++] = '\\';
205 mOwnedStr
[i
++] = detail::gTwoCharEscapes
[u
];
206 } else if (u
<= 0x1f) {
207 mOwnedStr
[i
++] = '\\';
208 mOwnedStr
[i
++] = 'u';
209 mOwnedStr
[i
++] = '0';
210 mOwnedStr
[i
++] = '0';
211 mOwnedStr
[i
++] = hexDigitToAsciiChar((u
& 0x00f0) >> 4);
212 mOwnedStr
[i
++] = hexDigitToAsciiChar(u
& 0x000f);
225 const char* get() const
228 return mIsOwned
? mOwnedStr
.get() : mUnownedStr
;
233 // Collections (objects and arrays) are printed in a multi-line style by
234 // default. This can be changed to a single-line style if SingleLineStyle is
235 // specified. If a collection is printed in single-line style, every nested
236 // collection within it is also printed in single-line style, even if
237 // multi-line style is requested.
238 enum CollectionStyle
{
239 MultiLineStyle
, // the default
244 const UniquePtr
<JSONWriteFunc
> mWriter
;
245 Vector
<bool, 8> mNeedComma
; // do we need a comma at depth N?
246 Vector
<bool, 8> mNeedNewlines
; // do we need newlines at depth N?
247 size_t mDepth
; // the current nesting depth
251 for (size_t i
= 0; i
< mDepth
; i
++) {
256 // Adds whatever is necessary (maybe a comma, and then a newline and
257 // whitespace) to separate an item (property or element) from what's come
261 if (mNeedComma
[mDepth
]) {
264 if (mDepth
> 0 && mNeedNewlines
[mDepth
]) {
265 mWriter
->Write("\n");
267 } else if (mNeedComma
[mDepth
]) {
272 void PropertyNameAndColon(const char* aName
)
274 EscapedString
escapedName(aName
);
275 mWriter
->Write("\"");
276 mWriter
->Write(escapedName
.get());
277 mWriter
->Write("\": ");
280 void Scalar(const char* aMaybePropertyName
, const char* aStringValue
)
283 if (aMaybePropertyName
) {
284 PropertyNameAndColon(aMaybePropertyName
);
286 mWriter
->Write(aStringValue
);
287 mNeedComma
[mDepth
] = true;
290 void QuotedScalar(const char* aMaybePropertyName
, const char* aStringValue
)
293 if (aMaybePropertyName
) {
294 PropertyNameAndColon(aMaybePropertyName
);
296 mWriter
->Write("\"");
297 mWriter
->Write(aStringValue
);
298 mWriter
->Write("\"");
299 mNeedComma
[mDepth
] = true;
302 void NewVectorEntries()
304 // If these tiny allocations OOM we might as well just crash because we
305 // must be in serious memory trouble.
306 MOZ_RELEASE_ASSERT(mNeedComma
.resizeUninitialized(mDepth
+ 1));
307 MOZ_RELEASE_ASSERT(mNeedNewlines
.resizeUninitialized(mDepth
+ 1));
308 mNeedComma
[mDepth
] = false;
309 mNeedNewlines
[mDepth
] = true;
312 void StartCollection(const char* aMaybePropertyName
, const char* aStartChar
,
313 CollectionStyle aStyle
= MultiLineStyle
)
316 if (aMaybePropertyName
) {
317 PropertyNameAndColon(aMaybePropertyName
);
319 mWriter
->Write(aStartChar
);
320 mNeedComma
[mDepth
] = true;
323 mNeedNewlines
[mDepth
] =
324 mNeedNewlines
[mDepth
- 1] && aStyle
== MultiLineStyle
;
327 // Adds the whitespace and closing char necessary to end a collection.
328 void EndCollection(const char* aEndChar
)
330 MOZ_ASSERT(mDepth
> 0);
331 if (mNeedNewlines
[mDepth
]) {
332 mWriter
->Write("\n");
338 mWriter
->Write(aEndChar
);
342 explicit JSONWriter(UniquePtr
<JSONWriteFunc
> aWriter
)
343 : mWriter(std::move(aWriter
))
351 // Returns the JSONWriteFunc passed in at creation, for temporary use. The
352 // JSONWriter object still owns the JSONWriteFunc.
353 JSONWriteFunc
* WriteFunc() const { return mWriter
.get(); }
355 // For all the following functions, the "Prints:" comment indicates what the
356 // basic output looks like. However, it doesn't indicate the whitespace and
357 // trailing commas, which are automatically added as required.
359 // All property names and string properties are escaped as necessary.
362 void Start(CollectionStyle aStyle
= MultiLineStyle
)
364 StartCollection(nullptr, "{", aStyle
);
368 void End() { EndCollection("}\n"); }
370 // Prints: "<aName>": null
371 void NullProperty(const char* aName
)
373 Scalar(aName
, "null");
377 void NullElement() { NullProperty(nullptr); }
379 // Prints: "<aName>": <aBool>
380 void BoolProperty(const char* aName
, bool aBool
)
382 Scalar(aName
, aBool
? "true" : "false");
386 void BoolElement(bool aBool
) { BoolProperty(nullptr, aBool
); }
388 // Prints: "<aName>": <aInt>
389 void IntProperty(const char* aName
, int64_t aInt
)
392 SprintfLiteral(buf
, "%" PRId64
, aInt
);
397 void IntElement(int64_t aInt
) { IntProperty(nullptr, aInt
); }
399 // Prints: "<aName>": <aDouble>
400 void DoubleProperty(const char* aName
, double aDouble
)
402 static const size_t buflen
= 64;
404 const double_conversion::DoubleToStringConverter
&converter
=
405 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
406 double_conversion::StringBuilder
builder(buf
, buflen
);
407 converter
.ToShortest(aDouble
, &builder
);
408 Scalar(aName
, builder
.Finalize());
412 void DoubleElement(double aDouble
) { DoubleProperty(nullptr, aDouble
); }
414 // Prints: "<aName>": "<aStr>"
415 void StringProperty(const char* aName
, const char* aStr
)
417 EscapedString
escapedStr(aStr
);
418 QuotedScalar(aName
, escapedStr
.get());
422 void StringElement(const char* aStr
) { StringProperty(nullptr, aStr
); }
424 // Prints: "<aName>": [
425 void StartArrayProperty(const char* aName
,
426 CollectionStyle aStyle
= MultiLineStyle
)
428 StartCollection(aName
, "[", aStyle
);
432 void StartArrayElement(CollectionStyle aStyle
= MultiLineStyle
)
434 StartArrayProperty(nullptr, aStyle
);
438 void EndArray() { EndCollection("]"); }
440 // Prints: "<aName>": {
441 void StartObjectProperty(const char* aName
,
442 CollectionStyle aStyle
= MultiLineStyle
)
444 StartCollection(aName
, "{", aStyle
);
448 void StartObjectElement(CollectionStyle aStyle
= MultiLineStyle
)
450 StartObjectProperty(nullptr, aStyle
);
454 void EndObject() { EndCollection("}"); }
457 } // namespace mozilla
459 #endif /* mozilla_JSONWriter_h */