Bug 1507805 [wpt PR 14092] - [css-grid] Some fixes on grid-container-scrollbar-*...
[gecko.git] / mfbt / JSONWriter.h
bloba2426c312c4b334ab7b9865c6a5ca6dcebe4d4af
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
21 // such problems.
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.
43 // EXAMPLE
44 // -------
45 // Assume that |MyWriteFunc| is a class that implements |JSONWriteFunc|. The
46 // following code:
48 // JSONWriter w(MakeUnique<MyWriteFunc>());
49 // w.Start();
50 // {
51 // w.NullProperty("null");
52 // w.BoolProperty("bool", true);
53 // w.IntProperty("int", 1);
54 // w.StartArrayProperty("array");
55 // {
56 // w.StringElement("string");
57 // w.StartObjectElement();
58 // {
59 // w.DoubleProperty("double", 3.4);
60 // w.StartArrayProperty("single-line array", w.SingleLineStyle);
61 // {
62 // w.IntElement(1);
63 // w.StartObjectElement(); // SingleLineStyle is inherited from
64 // w.EndObjectElement(); // above for this collection
65 // }
66 // w.EndArray();
67 // }
68 // w.EndObjectElement();
69 // }
70 // w.EndArrayProperty();
71 // }
72 // w.End();
74 // will produce pretty-printed output for the following JSON object:
76 // {
77 // "null": null,
78 // "bool": true,
79 // "int": 1,
80 // "array": [
81 // "string",
82 // {
83 // "double": 3.4,
84 // "single-line array": [1, {}]
85 // }
86 // ]
87 // }
89 // The nesting in the example code is obviously optional, but can aid
90 // readability.
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"
103 #include <stdio.h>
105 namespace mozilla {
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.
110 class JSONWriteFunc
112 public:
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.
119 namespace detail {
120 extern MFBT_DATA const char gTwoCharEscapes[256];
121 } // namespace detail
123 class JSONWriter
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').
138 class EscapedString
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.
143 bool mIsOwned;
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)
155 u = u & 0xf;
156 return u < 10 ? '0' + u : 'a' + (u - 10);
159 public:
160 explicit EscapedString(const char* aStr)
161 : mUnownedStr(nullptr)
162 , mOwnedStr(nullptr)
164 const char* p;
166 // First, see if we need to modify the string.
167 size_t nExtra = 0;
168 p = aStr;
169 while (true) {
170 uint8_t u = *p; // ensure it can't be interpreted as negative
171 if (u == 0) {
172 break;
174 if (detail::gTwoCharEscapes[u]) {
175 nExtra += 1;
176 } else if (u <= 0x1f) {
177 nExtra += 5;
179 p++;
182 if (nExtra == 0) {
183 // No escapes needed. Easy.
184 mIsOwned = false;
185 mUnownedStr = aStr;
186 return;
189 // Escapes are needed. We'll create a new string.
190 mIsOwned = true;
191 size_t len = (p - aStr) + nExtra;
192 mOwnedStr = MakeUnique<char[]>(len + 1);
194 p = aStr;
195 size_t i = 0;
197 while (true) {
198 uint8_t u = *p; // ensure it can't be interpreted as negative
199 if (u == 0) {
200 mOwnedStr[i] = 0;
201 break;
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);
213 } else {
214 mOwnedStr[i++] = u;
216 p++;
220 ~EscapedString()
222 SanityCheck();
225 const char* get() const
227 SanityCheck();
228 return mIsOwned ? mOwnedStr.get() : mUnownedStr;
232 public:
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
240 SingleLineStyle
243 protected:
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
249 void Indent()
251 for (size_t i = 0; i < mDepth; i++) {
252 mWriter->Write(" ");
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
258 // before.
259 void Separator()
261 if (mNeedComma[mDepth]) {
262 mWriter->Write(",");
264 if (mDepth > 0 && mNeedNewlines[mDepth]) {
265 mWriter->Write("\n");
266 Indent();
267 } else if (mNeedComma[mDepth]) {
268 mWriter->Write(" ");
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)
282 Separator();
283 if (aMaybePropertyName) {
284 PropertyNameAndColon(aMaybePropertyName);
286 mWriter->Write(aStringValue);
287 mNeedComma[mDepth] = true;
290 void QuotedScalar(const char* aMaybePropertyName, const char* aStringValue)
292 Separator();
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)
315 Separator();
316 if (aMaybePropertyName) {
317 PropertyNameAndColon(aMaybePropertyName);
319 mWriter->Write(aStartChar);
320 mNeedComma[mDepth] = true;
321 mDepth++;
322 NewVectorEntries();
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");
333 mDepth--;
334 Indent();
335 } else {
336 mDepth--;
338 mWriter->Write(aEndChar);
341 public:
342 explicit JSONWriter(UniquePtr<JSONWriteFunc> aWriter)
343 : mWriter(std::move(aWriter))
344 , mNeedComma()
345 , mNeedNewlines()
346 , mDepth(0)
348 NewVectorEntries();
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.
361 // Prints: {
362 void Start(CollectionStyle aStyle = MultiLineStyle)
364 StartCollection(nullptr, "{", aStyle);
367 // Prints: }
368 void End() { EndCollection("}\n"); }
370 // Prints: "<aName>": null
371 void NullProperty(const char* aName)
373 Scalar(aName, "null");
376 // Prints: null
377 void NullElement() { NullProperty(nullptr); }
379 // Prints: "<aName>": <aBool>
380 void BoolProperty(const char* aName, bool aBool)
382 Scalar(aName, aBool ? "true" : "false");
385 // Prints: <aBool>
386 void BoolElement(bool aBool) { BoolProperty(nullptr, aBool); }
388 // Prints: "<aName>": <aInt>
389 void IntProperty(const char* aName, int64_t aInt)
391 char buf[64];
392 SprintfLiteral(buf, "%" PRId64, aInt);
393 Scalar(aName, buf);
396 // Prints: <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;
403 char buf[buflen];
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());
411 // Prints: <aDouble>
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());
421 // Prints: "<aStr>"
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);
431 // Prints: [
432 void StartArrayElement(CollectionStyle aStyle = MultiLineStyle)
434 StartArrayProperty(nullptr, aStyle);
437 // Prints: ]
438 void EndArray() { EndCollection("]"); }
440 // Prints: "<aName>": {
441 void StartObjectProperty(const char* aName,
442 CollectionStyle aStyle = MultiLineStyle)
444 StartCollection(aName, "{", aStyle);
447 // Prints: {
448 void StartObjectElement(CollectionStyle aStyle = MultiLineStyle)
450 StartObjectProperty(nullptr, aStyle);
453 // Prints: }
454 void EndObject() { EndCollection("}"); }
457 } // namespace mozilla
459 #endif /* mozilla_JSONWriter_h */