JSONPrinter.h (2795B)
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/. */ 6 7 #ifndef vm_JSONPrinter_h 8 #define vm_JSONPrinter_h 9 10 #include "mozilla/TimeStamp.h" 11 12 #include <stdio.h> 13 14 #include "js/Printer.h" 15 #include "js/TypeDecls.h" 16 17 class JSLinearString; 18 19 namespace js { 20 21 class JSONPrinter { 22 protected: 23 int indentLevel_ = 0; 24 int inlineLevel_ = 0; 25 bool indent_; 26 bool first_ = true; 27 GenericPrinter& out_; 28 29 void indent(); 30 31 void beforeValue(); 32 33 public: 34 explicit JSONPrinter(GenericPrinter& out, bool indent = true) 35 : indent_(indent), out_(out) {} 36 37 void setIndentLevel(int indentLevel) { indentLevel_ = indentLevel; } 38 39 void beginObject(); 40 void beginList(); 41 void beginObjectProperty(const char* name); 42 void beginListProperty(const char* name); 43 void beginInlineListProperty(const char* name); 44 45 void value(const char* format, ...) MOZ_FORMAT_PRINTF(2, 3); 46 void value(int value); 47 48 void boolProperty(const char* name, bool value); 49 50 void property(const char* name, const JSLinearString* value); 51 void property(const char* name, const char* value); 52 void property(const char* name, int32_t value); 53 void property(const char* name, uint32_t value); 54 void property(const char* name, int64_t value); 55 void property(const char* name, uint64_t value); 56 #if defined(XP_DARWIN) || defined(__OpenBSD__) || defined(__wasi__) 57 // On OSX and OpenBSD, size_t is long unsigned, uint32_t is unsigned, and 58 // uint64_t is long long unsigned. Everywhere else, size_t matches either 59 // uint32_t or uint64_t. 60 void property(const char* name, size_t value); 61 #endif 62 63 void formatProperty(const char* name, const char* format, ...) 64 MOZ_FORMAT_PRINTF(3, 4); 65 void formatPropertyVA(const char* name, const char* format, va_list ap); 66 67 void propertyName(const char* name); 68 69 // JSON requires decimals to be separated by periods, but the LC_NUMERIC 70 // setting may cause printf to use commas in some locales. 71 enum TimePrecision { SECONDS, MILLISECONDS, MICROSECONDS }; 72 void property(const char* name, const mozilla::TimeDuration& dur, 73 TimePrecision precision); 74 75 void floatProperty(const char* name, double value, size_t precision); 76 77 GenericPrinter& beginStringProperty(const char* name); 78 void endStringProperty(); 79 80 GenericPrinter& beginString(); 81 void endString(); 82 83 void nullProperty(const char* name); 84 void nullValue(); 85 86 void endObject(); 87 void endList(); 88 void endInlineList(); 89 90 protected: 91 void beginInline(); 92 void endInline(); 93 }; 94 95 } // namespace js 96 97 #endif /* vm_JSONPrinter_h */